From d8825b30bf3cfb531bc5a930899d35f1394631fa Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:49:36 +0400 Subject: [PATCH 1/6] Refuse a dynamic with no parameter values instead of running it as current law (failing) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tests for C1 · 47. API v1 refuses to store a dynamic without values, so a dynamic for which sim reads no parameter_values rows has values this release can't see, such as values moved to tables it doesn't read. Running it as current law would store that result under a key naming the dynamic. - read_dynamic_reform raises DynamicWithoutValuesError for a dynamic with no rows, alone or with a policy; a dynamic whose values all start after 2200 is still read, as {} (it passes already, and pins that only a dynamic with no rows is refused). - The economy and household stores raise it, a report side's wrapped in ReportSideError, and the side refusal type includes it. - Every route answers it 400 dynamic_without_values: economy simulations, reports and budget windows, household calculations and reports, and the re-runs of reports, simulations and household reports. The OpenAPI document lists the code for the economy and household routes. Co-Authored-By: Claude Opus 5.5 --- .../tests/test_dynamic_reform.py | 85 +++++++++++++++++++ .../tests/test_economy_run_store.py | 7 ++ .../tests/test_household_job_store.py | 7 ++ .../tests/test_household_report_store.py | 19 ++++- .../tests/test_budget_window_submissions.py | 23 +++++ .../tests/test_economy_reruns.py | 36 ++++++++ .../tests/test_economy_submissions.py | 27 ++++++ .../tests/test_household_calculations.py | 12 +++ .../tests/test_household_report_reruns.py | 18 ++++ .../test_household_report_submissions.py | 17 +++- .../tests/test_openapi.py | 5 +- .../tests/test_simulation_values_refusal.py | 19 +++++ 12 files changed, 272 insertions(+), 3 deletions(-) diff --git a/libs/policyengine-simulation-persistence/tests/test_dynamic_reform.py b/libs/policyengine-simulation-persistence/tests/test_dynamic_reform.py index 73b28072b..efb98abd4 100644 --- a/libs/policyengine-simulation-persistence/tests/test_dynamic_reform.py +++ b/libs/policyengine-simulation-persistence/tests/test_dynamic_reform.py @@ -14,6 +14,7 @@ import pytest from conftest import act_as_the_service, in_session, rolled_back_transaction from policyengine_simulation_persistence import ( + DynamicWithoutValuesError, MissingPolicyParametersError, OverlappingReformError, SimulationReform, @@ -144,6 +145,90 @@ def test_a_dynamic_of_another_country_is_refused(public_api_database_url) -> Non assert uk_reform == {ELASTICITY: {"2026-01-01.2200-12-31": -0.05}} +@pytest.mark.public_api_schema +def test_a_dynamic_without_values_is_refused_instead_of_read_as_current_law( + public_api_database_url, +) -> None: + """API v1 stores no dynamic without values, so none read means values sim can't see. + + Applying such a dynamic as current law would store that result under a + key naming the dynamic, so the read refuses it, alone or with a policy. + """ + with rolled_back_transaction(public_api_database_url) as connection: + catalog = insert_catalog_version( + connection, + country="us", + model_id=insert_model(connection, "us"), + policyengine_version="6.17.1", + parameter_names=[ELASTICITY, CTC_AMOUNT], + ) + policy_id = insert_policy( + connection, catalog, [StoredValue(CTC_AMOUNT, 3_000, START)] + ) + dynamic_without_values_id = insert_dynamic(connection, catalog) + act_as_the_service(connection) + + with pytest.raises(DynamicWithoutValuesError) as alone: + in_session( + connection, + read_dynamic_reform, + country="us", + dynamic_id=dynamic_without_values_id, + catalog_version_id=catalog.version_id, + ) + with pytest.raises(DynamicWithoutValuesError) as with_policy: + in_session( + connection, + read_simulation_reform, + country="us", + policy_id=policy_id, + dynamic_id=dynamic_without_values_id, + catalog_version_id=catalog.version_id, + ) + + assert str(alone.value) == ( + f"us's dynamic {dynamic_without_values_id} has no parameter values" + ) + assert str(with_policy.value) == str(alone.value) + # It is not a missing dynamic: the dynamic exists. + assert not isinstance(alone.value, UnknownDynamicError) + + +@pytest.mark.public_api_schema +def test_a_dynamic_whose_values_all_start_after_2200_is_read_and_applies_nothing( + public_api_database_url, +) -> None: + """Its values are read, but no year a calculation can be for is in their periods. + + Only a dynamic with no stored values is refused: this one's current-law + result is its own correct result. + """ + with rolled_back_transaction(public_api_database_url) as connection: + catalog = insert_catalog_version( + connection, + country="us", + model_id=insert_model(connection, "us"), + policyengine_version="6.17.1", + parameter_names=[ELASTICITY], + ) + dynamic_id = insert_dynamic( + connection, + catalog, + [StoredValue(ELASTICITY, -0.05, datetime(2201, 1, 1, tzinfo=UTC))], + ) + act_as_the_service(connection) + + reform = in_session( + connection, + read_dynamic_reform, + country="us", + dynamic_id=dynamic_id, + catalog_version_id=catalog.version_id, + ) + + assert reform == {} + + @pytest.mark.public_api_schema def test_a_dynamic_changing_parameters_the_run_lacks_names_each_of_them( public_api_database_url, diff --git a/libs/policyengine-simulation-persistence/tests/test_economy_run_store.py b/libs/policyengine-simulation-persistence/tests/test_economy_run_store.py index f8c963473..2e0d9cd0c 100644 --- a/libs/policyengine-simulation-persistence/tests/test_economy_run_store.py +++ b/libs/policyengine-simulation-persistence/tests/test_economy_run_store.py @@ -29,6 +29,7 @@ from policyengine_simulation_persistence import ( CatalogDataset, CatalogRegion, + DynamicWithoutValuesError, EconomyCatalogRows, EconomyPopulation, EconomyRecordOutcomeUnknownError, @@ -419,6 +420,7 @@ def test_a_report_and_a_simulation_are_read_as_they_stand( ("reform", UnknownPolicyError), ("reform", MissingPolicyParametersError), ("baseline", OverlappingReformError), + ("reform", DynamicWithoutValuesError), ], ) def test_a_reports_refused_values_name_the_side_they_belong_to( @@ -440,12 +442,16 @@ def test_a_reports_refused_values_name_the_side_they_belong_to( dynamic_id = insert_dynamic( connection, economy.catalog, [StoredValue(ELASTICITY, -0.05, START)] ) + dynamic_without_values_id = insert_dynamic(connection, economy.catalog) act_as_the_service(connection) refused = { UnknownDynamicError: SimulationChoice(None, uuid4()), UnknownPolicyError: SimulationChoice(uuid4(), None), MissingPolicyParametersError: SimulationChoice(lacking_policy_id, None), OverlappingReformError: SimulationChoice(overlapping_policy_id, dynamic_id), + DynamicWithoutValuesError: SimulationChoice( + None, dynamic_without_values_id + ), }[error_type] choices = {"baseline": CURRENT_LAW, "reform": CURRENT_LAW, side: refused} @@ -525,6 +531,7 @@ def test_every_side_refusal_is_raised_with_its_side(monkeypatch) -> None: UnknownDynamicError: UnknownDynamicError("no dynamic"), MissingPolicyParametersError: MissingPolicyParametersError(["gov.a"]), OverlappingReformError: OverlappingReformError(["gov.a"]), + DynamicWithoutValuesError: DynamicWithoutValuesError("no values"), } assert set(get_args(SideRefusal.__value__)) == set(refusals) diff --git a/libs/policyengine-simulation-persistence/tests/test_household_job_store.py b/libs/policyengine-simulation-persistence/tests/test_household_job_store.py index 5ce52a00e..0aa933bf7 100644 --- a/libs/policyengine-simulation-persistence/tests/test_household_job_store.py +++ b/libs/policyengine-simulation-persistence/tests/test_household_job_store.py @@ -21,6 +21,7 @@ simulation_engine, ) from policyengine_simulation_persistence import ( + DynamicWithoutValuesError, EconomyRecordOutcomeUnknownError, HouseholdJobReferenceError, HouseholdJobStatus, @@ -219,6 +220,7 @@ def test_a_dynamic_that_cannot_be_applied_is_refused(public_api_database_url) -> uk_dynamic_id = insert_dynamic( connection, uk_catalog, [StoredValue(ELASTICITY, -0.05, START)] ) + dynamic_without_values_id = insert_dynamic(connection, catalog) act_as_the_service(connection) store = _store_on(connection) @@ -237,6 +239,8 @@ def read(dynamic_id: UUID) -> None: read(overlapping_dynamic_id) with pytest.raises(MissingPolicyParametersError) as lacking: read(lacking_dynamic_id) + with pytest.raises(DynamicWithoutValuesError) as without_values: + read(dynamic_without_values_id) assert str(other_country.value) == f"us has no dynamic {uk_dynamic_id}" assert overlapping.value.parameter_names == (CTC_AMOUNT,) @@ -244,6 +248,9 @@ def read(dynamic_id: UUID) -> None: "dynamic", ("gov.simulation.removed",), ) + assert str(without_values.value) == ( + f"us's dynamic {dynamic_without_values_id} has no parameter values" + ) def test_each_missing_input_is_named(public_api_database_url) -> None: diff --git a/libs/policyengine-simulation-persistence/tests/test_household_report_store.py b/libs/policyengine-simulation-persistence/tests/test_household_report_store.py index 55375cc09..68b2a2049 100644 --- a/libs/policyengine-simulation-persistence/tests/test_household_report_store.py +++ b/libs/policyengine-simulation-persistence/tests/test_household_report_store.py @@ -17,6 +17,7 @@ from conftest import act_as_the_service, rolled_back_transaction, session_factory_on from household_report_rows import insert_household_report_rows from policyengine_simulation_persistence import ( + DynamicWithoutValuesError, HouseholdReportStore, MissingPolicyParametersError, OverlappingReformError, @@ -177,7 +178,7 @@ def test_each_sides_dynamic_is_applied_with_its_policy(public_api_database_url) } -def test_a_sides_dynamic_of_another_country_or_overlapping_its_policy_is_refused( +def test_a_sides_dynamic_of_another_country_overlapping_or_without_values_is_refused( public_api_database_url, ) -> None: with rolled_back_transaction(public_api_database_url) as connection: @@ -199,6 +200,7 @@ def test_a_sides_dynamic_of_another_country_or_overlapping_its_policy_is_refused dynamic_id = insert_dynamic( connection, catalog, [StoredValue(ELASTICITY, -0.05, START)] ) + dynamic_without_values_id = insert_dynamic(connection, catalog) act_as_the_service(connection) store = _store_on(connection) @@ -223,12 +225,27 @@ def test_a_sides_dynamic_of_another_country_or_overlapping_its_policy_is_refused policyengine_version=POLICYENGINE_VERSION, ) + with pytest.raises(ReportSideError) as without_values: + store.read_inputs( + country="us", + household_id=household_id, + choices={ + "baseline": CURRENT_LAW, + "reform": SimulationChoice( + None, dynamic_id=dynamic_without_values_id + ), + }, + policyengine_version=POLICYENGINE_VERSION, + ) + assert other_country.value.side == "baseline" assert isinstance(other_country.value.error, UnknownDynamicError) assert str(other_country.value.error) == f"us has no dynamic {uk_dynamic_id}" assert overlapping.value.side == "reform" assert isinstance(overlapping.value.error, OverlappingReformError) assert overlapping.value.error.parameter_names == (ELASTICITY,) + assert without_values.value.side == "reform" + assert isinstance(without_values.value.error, DynamicWithoutValuesError) def test_each_missing_input_is_refused(public_api_database_url) -> None: diff --git a/projects/policyengine-simulation-entry/tests/test_budget_window_submissions.py b/projects/policyengine-simulation-entry/tests/test_budget_window_submissions.py index d799c7548..38f0037c3 100644 --- a/projects/policyengine-simulation-entry/tests/test_budget_window_submissions.py +++ b/projects/policyengine-simulation-entry/tests/test_budget_window_submissions.py @@ -41,17 +41,20 @@ ReportSubmissionService, ) from policyengine_simulation_entry.economy_submission_errors import ( + EconomySubmissionRefusedError, EconomySubmissionUnavailableError, ) from policyengine_simulation_entry.economy_submissions import ServiceSettings from policyengine_simulation_persistence import ( BudgetWindowInputs, + DynamicWithoutValuesError, EconomyReportDefinition, FoundBudgetWindow, FoundSide, FoundWindowRun, FoundWindowYear, ReportRunStatus, + ReportSideError, SimulationInputs, ) from policyengine_stage12_persistence import ( @@ -276,6 +279,26 @@ def test_a_window_is_created_with_a_run_per_year_and_its_first_five_started() -> } +def test_a_window_whose_side_has_a_dynamic_without_values_is_refused() -> None: + """No window, year or call is created for values this release can't read.""" + store = FakeWindowStore( + read_failure=ReportSideError( + "reform", DynamicWithoutValuesError("store text: no values") + ) + ) + caller = FakeCaller() + + with pytest.raises(EconomySubmissionRefusedError) as refused: + _submit(_service(store, caller=caller)) + + assert (refused.value.code, refused.value.detail) == ( + "dynamic_without_values", + "us's stored dynamic that the request's reform names has no parameter " + "values the service can read.", + ) + assert (store.windows, caller.report_runs) == ([], []) + + def test_each_later_year_is_derived_from_the_first() -> None: store = FakeWindowStore() caller = FakeCaller() diff --git a/projects/policyengine-simulation-entry/tests/test_economy_reruns.py b/projects/policyengine-simulation-entry/tests/test_economy_reruns.py index 0eb96f1da..1b1c3f72d 100644 --- a/projects/policyengine-simulation-entry/tests/test_economy_reruns.py +++ b/projects/policyengine-simulation-entry/tests/test_economy_reruns.py @@ -42,6 +42,7 @@ ) from policyengine_simulation_persistence import ( CatalogDataset, + DynamicWithoutValuesError, EconomyRecordOutcomeUnknownError, EconomyRecordReferenceError, FoundBudgetWindow, @@ -392,6 +393,41 @@ def test_a_stored_policy_the_current_catalog_cannot_set_is_located_on_its_side() assert store.report_reruns == [] +def test_a_stored_dynamic_without_values_is_refused_naming_the_report_side() -> None: + store = FakeRerunStore( + inputs_failure=ReportSideError( + "baseline", DynamicWithoutValuesError("store text: no values") + ) + ) + caller = FakeCaller() + + with pytest.raises(EconomySubmissionRefusedError) as refused: + _rerun_report(rerun_service(store, caller=caller)) + + assert (refused.value.code, refused.value.detail) == ( + "dynamic_without_values", + "us's stored dynamic that the report's baseline names has no parameter " + "values the service can read.", + ) + assert (store.report_reruns, caller.report_runs) == ([], []) + + +def test_a_stored_simulations_dynamic_without_values_is_refused() -> None: + store = FakeRerunStore( + inputs_failure=DynamicWithoutValuesError("store text: no values") + ) + + with pytest.raises(EconomySubmissionRefusedError) as refused: + _rerun_simulation(rerun_service(store)) + + assert (refused.value.code, refused.value.detail) == ( + "dynamic_without_values", + "us's stored dynamic that the simulation names has no parameter values " + "the service can read.", + ) + assert store.simulation_reruns == [] + + @pytest.mark.parametrize("stored", [STORED_REPORT, STORED_WINDOW]) def test_a_stored_report_asking_for_cliffs_is_not_rerun_until_cliffs_exist( stored, diff --git a/projects/policyengine-simulation-entry/tests/test_economy_submissions.py b/projects/policyengine-simulation-entry/tests/test_economy_submissions.py index e6a2e4864..0337257e1 100644 --- a/projects/policyengine-simulation-entry/tests/test_economy_submissions.py +++ b/projects/policyengine-simulation-entry/tests/test_economy_submissions.py @@ -46,6 +46,7 @@ ) from policyengine_simulation_persistence import ( CatalogDataset, + DynamicWithoutValuesError, EconomyRecordOutcomeUnknownError, EconomyRecordReferenceError, EconomyReportDefinition, @@ -331,6 +332,25 @@ def test_a_missing_row_is_refused_before_anything_is_written(error, code) -> Non assert (store.reports, store.simulations, caller.report_runs) == ([], [], []) +def test_a_dynamic_without_values_is_refused_before_anything_is_written() -> None: + """A dynamic whose values this release can't read is never run as current law.""" + store = FakeStore(read_failure=DynamicWithoutValuesError("store text: no values")) + caller = FakeCaller() + + with pytest.raises(EconomySubmissionRefusedError) as report_refusal: + _submit_report(service(store, caller=caller)) + with pytest.raises(EconomySubmissionRefusedError) as simulation_refusal: + _submit_simulation(service(store, caller=caller)) + + assert report_refusal.value.code == simulation_refusal.value.code + assert simulation_refusal.value.code == "dynamic_without_values" + assert simulation_refusal.value.detail == ( + "us's stored dynamic that the request names has no parameter values the " + "service can read." + ) + assert (store.reports, store.simulations, caller.report_runs) == ([], [], []) + + def test_values_the_catalog_version_lacks_cannot_be_calculated() -> None: error = MissingPolicyParametersError(["gov.a", "gov.b"], source="dynamic") store = FakeStore(read_failure=error) @@ -729,6 +749,13 @@ def test_a_reports_overlapping_parameters_are_located_on_their_side() -> None: "unknown_dynamic", "us has no stored dynamic the request's baseline names.", ), + ( + ReportSideError("reform", DynamicWithoutValuesError(ERROR_TEXT)), + {}, + "dynamic_without_values", + "us's stored dynamic that the request's reform names has no parameter " + "values the service can read.", + ), ], ) def test_a_refusals_detail_is_built_from_the_request_not_the_error( diff --git a/projects/policyengine-simulation-entry/tests/test_household_calculations.py b/projects/policyengine-simulation-entry/tests/test_household_calculations.py index 3eb46ecab..b3f3c5f1c 100644 --- a/projects/policyengine-simulation-entry/tests/test_household_calculations.py +++ b/projects/policyengine-simulation-entry/tests/test_household_calculations.py @@ -39,6 +39,7 @@ default_household_worker, ) from policyengine_simulation_persistence import ( + DynamicWithoutValuesError, EconomyRecordOutcomeUnknownError, HouseholdCalculationInputs, HouseholdJobRecord, @@ -514,6 +515,17 @@ async def test_without_spm_settings_or_a_saved_selection_none_is_sent(): "unknown_dynamic", "us has no dynamic z", ), + # A dynamic whose values this release can't read is the service's state. + ( + FakeStore( + read_failure=DynamicWithoutValuesError( + "us's dynamic z has no parameter values" + ) + ), + FakeWorkers(), + "dynamic_without_values", + "us's dynamic z has no parameter values", + ), ], ) async def test_a_missing_row_or_function_is_refused_before_anything_is_written( diff --git a/projects/policyengine-simulation-entry/tests/test_household_report_reruns.py b/projects/policyengine-simulation-entry/tests/test_household_report_reruns.py index e1b6aa84c..bbbf0676b 100644 --- a/projects/policyengine-simulation-entry/tests/test_household_report_reruns.py +++ b/projects/policyengine-simulation-entry/tests/test_household_report_reruns.py @@ -61,6 +61,7 @@ ) from policyengine_simulation_entry.simulation_database import SimulationDatabase from policyengine_simulation_persistence import ( + DynamicWithoutValuesError, EconomyRecordOutcomeUnknownError, EconomyRecordReferenceError, FoundReportRun, @@ -320,6 +321,23 @@ def test_a_stored_sides_dynamic_of_another_country_is_refused_at_the_report() -> assert households.report_reruns == [] +def test_a_stored_sides_dynamic_without_values_is_refused_at_the_report() -> None: + households = FakeHouseholdReportStore( + read_failure=ReportSideError("baseline", DynamicWithoutValuesError("no values")) + ) + service, _, _ = _services(households=households) + + with pytest.raises(EconomySubmissionRefusedError) as refused: + _rerun(service) + + assert (refused.value.code, refused.value.detail) == ( + "dynamic_without_values", + "us's stored dynamic that the report's baseline names has no parameter " + "values the service can read.", + ) + assert households.report_reruns == [] + + def test_a_household_rerun_answers_503_when_household_reports_are_not_configured() -> ( None ): diff --git a/projects/policyengine-simulation-entry/tests/test_household_report_submissions.py b/projects/policyengine-simulation-entry/tests/test_household_report_submissions.py index cf2ed939c..4f1ad058a 100644 --- a/projects/policyengine-simulation-entry/tests/test_household_report_submissions.py +++ b/projects/policyengine-simulation-entry/tests/test_household_report_submissions.py @@ -57,6 +57,7 @@ VersionManifestUnavailableError, ) from policyengine_simulation_persistence import ( + DynamicWithoutValuesError, EconomyRecordOutcomeUnknownError, EconomyRecordReferenceError, FoundReportRun, @@ -373,6 +374,13 @@ def test_a_policy_compared_with_itself_is_calculated_on_one_run(): "unknown_dynamic", "us has no stored dynamic the request's baseline names.", ), + ( + ReportSideError("reform", DynamicWithoutValuesError("no values")), + EconomySubmissionRefusedError, + "dynamic_without_values", + "us's stored dynamic that the request's reform names has no parameter " + "values the service can read.", + ), ( DATABASE_ERROR, EconomySubmissionUnavailableError, @@ -380,7 +388,14 @@ def test_a_policy_compared_with_itself_is_calculated_on_one_run(): "The simulation database could not be read.", ), ], - ids=["catalog-version", "household", "policy", "dynamic", "database"], + ids=[ + "catalog-version", + "household", + "policy", + "dynamic", + "dynamic-without-values", + "database", + ], ) def test_each_missing_input_is_refused_before_anything_is_written( failure, expected_type, code, detail diff --git a/projects/policyengine-simulation-entry/tests/test_openapi.py b/projects/policyengine-simulation-entry/tests/test_openapi.py index c32108e79..e67a35d59 100644 --- a/projects/policyengine-simulation-entry/tests/test_openapi.py +++ b/projects/policyengine-simulation-entry/tests/test_openapi.py @@ -302,7 +302,9 @@ def test_household_routes_declare_every_answer(): ] assert "job_state_unknown" not in code["enum"] assert "internal_error" in code["enum"] - assert {"unknown_policy", "unknown_dynamic"} <= set(code["enum"]) + assert {"unknown_policy", "unknown_dynamic", "dynamic_without_values"} <= set( + code["enum"] + ) def test_a_household_job_read_declares_only_the_answers_a_read_gives(): @@ -409,6 +411,7 @@ def test_economy_routes_declare_every_answer(): "unknown_region", "unknown_dataset", "unknown_dynamic", + "dynamic_without_values", "unknown_catalog_version", "unknown_household", "no_household_function", diff --git a/projects/policyengine-simulation-entry/tests/test_simulation_values_refusal.py b/projects/policyengine-simulation-entry/tests/test_simulation_values_refusal.py index 4a9b28319..79a16b38f 100644 --- a/projects/policyengine-simulation-entry/tests/test_simulation_values_refusal.py +++ b/projects/policyengine-simulation-entry/tests/test_simulation_values_refusal.py @@ -15,6 +15,7 @@ simulation_values_refusal, ) from policyengine_simulation_persistence import ( + DynamicWithoutValuesError, MissingPolicyParametersError, OverlappingReformError, UnknownCatalogVersionError, @@ -63,6 +64,24 @@ def test_a_policy_or_dynamic_the_country_lacks_is_refused_in_the_callers_words( assert STORE_TEXT not in refusal.detail +def test_a_dynamic_without_values_is_refused_as_the_services_state() -> None: + """The dynamic exists, but this release reads none of its values. + + API v1 stores no dynamic without values, so the values are stored where + this release doesn't read them: a state of the service, not a row the + caller chose that doesn't exist, so the code is not ``unknown_dynamic``. + """ + refusal = _refusal(DynamicWithoutValuesError(STORE_TEXT)) + + assert isinstance(refusal, EconomySubmissionRefusedError) + assert (refusal.code, refusal.detail) == ( + "dynamic_without_values", + "uk's stored dynamic that the request's reform names has no parameter " + "values the service can read.", + ) + assert STORE_TEXT not in refusal.detail + + @pytest.mark.parametrize( ("error", "code", "field_name", "reason_type"), [ From 98836e210337f69b5204ad98333e5925360a13dc Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:51:55 +0400 Subject: [PATCH 2/6] Refuse a dynamic with no parameter values instead of running it as current law MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit C1 · 47. API v1 refuses to store a dynamic without values, so when sim finds a dynamic but no parameter_values row for it, the values are stored where this release doesn't read them (as after C1 · 50's revision moves them to their own tables). Running such a dynamic as current law stored that result under a key naming the dynamic, which later requests reused. - read_dynamic_reform raises DynamicWithoutValuesError when no value row names the dynamic, after the existence and country check. The rows are read once (_read_values) and turned into the reform separately (_reform_from_values). A dynamic whose values are read but whose periods hold no day, such as values starting after 2200, is still read as no change. - SideRefusal includes it, so every report side's refusal names its side. - Every route answers it 400 dynamic_without_values, a code among the service's state codes, as unknown_catalog_version is while a release deploys: economy simulations, reports and budget windows, household reports and every re-run through simulation_values_refusal, with a detail written from the request; household calculations with the store's text, as that route's other refusals. API v1 answers a sim 400 with any code other than unknown_region, unknown_dataset and unknown_dynamic as 503, with the code and reason, so it needs no change. - Every path reads a dynamic's values through read_dynamic_reform before it finds or creates any row, and nothing reads them after submission, so this one check covers them all. Co-Authored-By: Claude Opus 5.5 --- changelog.d/c1-47-empty-dynamic.changed.md | 1 + .../README.md | 11 ++- .../__init__.py | 2 + .../economy_inputs.py | 6 +- .../economy_run_store.py | 4 +- .../household_job_store.py | 4 +- .../household_report_store.py | 3 +- .../policy_reform.py | 70 ++++++++++++------- .../policyengine-simulation-entry/README.md | 21 +++--- .../economy_api_models.py | 4 ++ .../economy_submission_errors.py | 13 +++- .../household_api_models.py | 3 + .../household_calculations.py | 5 ++ 13 files changed, 104 insertions(+), 43 deletions(-) create mode 100644 changelog.d/c1-47-empty-dynamic.changed.md diff --git a/changelog.d/c1-47-empty-dynamic.changed.md b/changelog.d/c1-47-empty-dynamic.changed.md new file mode 100644 index 000000000..4e29c0288 --- /dev/null +++ b/changelog.d/c1-47-empty-dynamic.changed.md @@ -0,0 +1 @@ +A simulation naming a stored dynamic with no parameter values, economy or household alike and their re-runs included, is refused with 400 `dynamic_without_values` instead of being calculated and stored as current law. API v1 stores no dynamic without values, so such a dynamic's values are stored where this release doesn't read them. diff --git a/libs/policyengine-simulation-persistence/README.md b/libs/policyengine-simulation-persistence/README.md index f63af85a3..5005f1746 100644 --- a/libs/policyengine-simulation-persistence/README.md +++ b/libs/policyengine-simulation-persistence/README.md @@ -260,8 +260,9 @@ their own, opened by `from_session_factory` with `bounded_session`: model, the stored household and each side's policy and dynamic values, combined (`read_simulation_reform`), together, raising `UnknownCatalogVersionError`, `UnknownHouseholdError` or `ReportSideError` -for the side whose policy or dynamic is missing in the country, sets -parameters the catalog version lacks, or sets one the other also sets; +for the side whose policy or dynamic is missing in the country, is a +dynamic with no values stored, sets parameters the catalog version lacks, or +sets one the other also sets; `find_or_create_report` raises `EconomyRecordOutcomeUnknownError` when the commit fails after the rows were inserted; and `record_report_call` and `fail_unstarted_report` use the economy report run writes. @@ -341,7 +342,11 @@ version lacks raises `MissingPolicyParametersError`, naming each one, and a policy the country doesn't have raises `UnknownPolicyError`. `read_dynamic_reform` reads a stored dynamic the same way: a dynamic, like a policy, belongs to one country, and one the country doesn't have, another -country's included, raises `UnknownDynamicError`. `combine_reforms` joins a +country's included, raises `UnknownDynamicError`. A dynamic with no +parameter values stored raises `DynamicWithoutValuesError` rather than being +applied as current law: API v1 stores no dynamic without values, so its +values are where this release doesn't read them, and a current-law result +would be stored under a key naming the dynamic. `combine_reforms` joins a simulation's policy and dynamic values, refusing a parameter both set (`OverlappingReformError`), and `read_simulation_reform` reads both and joins them, as every simulation does: economy (`read_simulation_values`), diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/__init__.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/__init__.py index 407af2453..05852bde3 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/__init__.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/__init__.py @@ -159,6 +159,7 @@ ServiceBase, ) from policyengine_simulation_persistence.policy_reform import ( + DynamicWithoutValuesError, MissingPolicyParametersError, OverlappingReformError, PolicyReform, @@ -238,6 +239,7 @@ "DecileImpact", "DecileType", "Dynamic", + "DynamicWithoutValuesError", "EconomyCatalogRows", "EconomyPopulation", "EconomyRecordOutcomeUnknownError", diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/economy_inputs.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/economy_inputs.py index 216ef4762..a67d70c4d 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/economy_inputs.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/economy_inputs.py @@ -32,6 +32,7 @@ UnknownCatalogVersionError, ) from policyengine_simulation_persistence.policy_reform import ( + DynamicWithoutValuesError, MissingPolicyParametersError, OverlappingReformError, UnknownDynamicError, @@ -52,6 +53,7 @@ type SideRefusal = ( UnknownPolicyError | UnknownDynamicError + | DynamicWithoutValuesError | MissingPolicyParametersError | OverlappingReformError ) @@ -88,8 +90,8 @@ class ReportSideError(Exception): """A report side's policy or dynamic is refused. ``side`` names the side, and ``error`` is the policy reader's refusal: - UnknownPolicyError, UnknownDynamicError, MissingPolicyParametersError or - OverlappingReformError. + UnknownPolicyError, UnknownDynamicError, DynamicWithoutValuesError, + MissingPolicyParametersError or OverlappingReformError. """ def __init__(self, side: ReportSide, error: SideRefusal) -> None: diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/economy_run_store.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/economy_run_store.py index dec3009ab..9331f45c2 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/economy_run_store.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/economy_run_store.py @@ -132,8 +132,8 @@ def read_simulation_inputs( Raise UnknownCatalogVersionError, UnknownRegionError or UnknownDatasetError, or the policy reader's UnknownPolicyError, - UnknownDynamicError or MissingPolicyParametersError, or - OverlappingReformError. + UnknownDynamicError, DynamicWithoutValuesError or + MissingPolicyParametersError, or OverlappingReformError. """ with self._transaction() as session: catalog = read_catalog_rows(session, request) diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/household_job_store.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/household_job_store.py index 12559df3b..c9e054dd8 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/household_job_store.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/household_job_store.py @@ -101,8 +101,8 @@ def read_inputs( simulation's are (``read_simulation_reform``). Raise UnknownCatalogVersionError, UnknownHouseholdError, or the readers' UnknownPolicyError, UnknownDynamicError (a dynamic of another - country included), MissingPolicyParametersError or - OverlappingReformError. + country included), DynamicWithoutValuesError, + MissingPolicyParametersError or OverlappingReformError. """ with self._transaction() as session: catalog_version_id = read_catalog_version_id( diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/household_report_store.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/household_report_store.py index 896547d3e..228924ab1 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/household_report_store.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/household_report_store.py @@ -144,7 +144,8 @@ def read_inputs( (``read_simulation_reform``). Raise UnknownCatalogVersionError or UnknownHouseholdError, or ReportSideError naming the side whose policy or dynamic is missing in the country (UnknownPolicyError, - UnknownDynamicError), sets parameters the catalog version lacks + UnknownDynamicError), is a dynamic with no values stored + (DynamicWithoutValuesError), sets parameters the catalog version lacks (MissingPolicyParametersError) or sets one the other also sets (OverlappingReformError). """ diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/policy_reform.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/policy_reform.py index bc8ada98d..926326a3f 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/policy_reform.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/policy_reform.py @@ -9,7 +9,9 @@ way, and a dynamic, like a policy, belongs to one country. A simulation, economy or household, applies its policy's and its dynamic's values together (``read_simulation_reform``), and is refused when both set the same parameter -(``combine_reforms``). +(``combine_reforms``). API v1 stores no dynamic without values, so a dynamic +the reader finds no values for is refused rather than applied as current +law: its values are stored where this release doesn't read them. Each period is a range, ``YYYY-MM-DD.YYYY-MM-DD``, with the dates read in UTC. A value with no end date follows .py's own rule @@ -51,7 +53,7 @@ from datetime import datetime from uuid import UUID - from sqlalchemy import ColumnElement + from sqlalchemy import ColumnElement, Row from sqlalchemy.orm import Session # The last day a value without an end date is applied. @@ -71,6 +73,16 @@ class UnknownDynamicError(LookupError): """API v1 has no such dynamic in the country.""" +class DynamicWithoutValuesError(LookupError): + """API v1 has the dynamic, but no parameter values are stored for it here. + + API v1 refuses to store a dynamic without values, so its values are + stored where this release does not read them. Applying it as current law + would store a result under a key naming the dynamic, which later + requests would reuse. + """ + + class MissingPolicyParametersError(ValueError): """The policy, or dynamic, sets parameters the calculation's catalog version lacks. @@ -150,9 +162,9 @@ def read_policy_reform( if found is None: msg = f"{country} has no policy {policy_id}" raise UnknownPolicyError(msg) - return _read_reform( + return _reform_from_values( session, - owner=ParameterValue.policy_id == policy_id, + _read_values(session, owner=ParameterValue.policy_id == policy_id), catalog_version_id=catalog_version_id, source="policy", ) @@ -169,9 +181,11 @@ def read_dynamic_reform( The periods follow the same rule as a policy's. Raise UnknownDynamicError when the country has no such dynamic, a dynamic - stored for another country included, and MissingPolicyParametersError, + stored for another country included; DynamicWithoutValuesError when no + parameter value is stored for it; and MissingPolicyParametersError, naming the dynamic as its source, when ``catalog_version_id`` lacks a - parameter it sets. + parameter it sets. A dynamic whose values are read but whose periods + hold no day, as for values starting after 2200, is read as no change. """ found = session.execute( select(Dynamic.id).where( @@ -181,11 +195,12 @@ def read_dynamic_reform( if found is None: msg = f"{country} has no dynamic {dynamic_id}" raise UnknownDynamicError(msg) - return _read_reform( - session, - owner=ParameterValue.dynamic_id == dynamic_id, - catalog_version_id=catalog_version_id, - source="dynamic", + values = _read_values(session, owner=ParameterValue.dynamic_id == dynamic_id) + if not values: + msg = f"{country}'s dynamic {dynamic_id} has no parameter values" + raise DynamicWithoutValuesError(msg) + return _reform_from_values( + session, values, catalog_version_id=catalog_version_id, source="dynamic" ) @@ -214,6 +229,7 @@ def read_simulation_reform( None for either reads nothing for it. Raise UnknownPolicyError or UnknownDynamicError for one the country doesn't have, + DynamicWithoutValuesError for a dynamic with no values stored, MissingPolicyParametersError for one setting a parameter ``catalog_version_id`` lacks, and OverlappingReformError when both set a parameter. @@ -254,19 +270,11 @@ def combine_reforms(policy: PolicyReform, dynamic: PolicyReform) -> PolicyReform return {**policy, **dynamic} -def _read_reform( - session: Session, - *, - owner: ColumnElement[bool], - catalog_version_id: UUID, - source: ReformSource, -) -> PolicyReform: - """Return the values ``owner`` selects, by parameter name and .py's periods. - - Raise MissingPolicyParametersError, naming ``source``, when - ``catalog_version_id`` lacks a parameter they set. - """ - values = session.execute( +def _read_values( + session: Session, *, owner: ColumnElement[bool] +) -> Sequence[Row[tuple[str, object, datetime, datetime | None]]]: + """Return the values ``owner`` selects, by parameter name, then start date.""" + return session.execute( select( Parameter.name, ParameterValue.value_json, @@ -278,6 +286,20 @@ def _read_reform( .where(owner) .order_by(Parameter.name, ParameterValue.start_date) ).all() + + +def _reform_from_values( + session: Session, + values: Sequence[Row[tuple[str, object, datetime, datetime | None]]], + *, + catalog_version_id: UUID, + source: ReformSource, +) -> PolicyReform: + """Return ``values`` by parameter name and .py's periods (``_read_values``). + + Raise MissingPolicyParametersError, naming ``source``, when + ``catalog_version_id`` lacks a parameter they set. + """ names = sorted({row.name for row in values}) available = set( session.execute( diff --git a/projects/policyengine-simulation-entry/README.md b/projects/policyengine-simulation-entry/README.md index 727ad24a0..c8e1f0baa 100644 --- a/projects/policyengine-simulation-entry/README.md +++ b/projects/policyengine-simulation-entry/README.md @@ -95,9 +95,10 @@ once it has one, and its `error_message`. A submission is refused before anything is written: with 400 and a `code` when the household, policy, dynamic or catalog version for the default worker's .py version is missing (a dynamic of another country is -`unknown_dynamic`), or the default worker has no household function for the -country; with 422, one reason per field, when the stored household has no -default year, the policy or dynamic sets parameters that catalog version +`unknown_dynamic`), the dynamic has no parameter values this release reads +(`dynamic_without_values`), or the default worker has no household function +for the country; with 422, one reason per field, when the stored household +has no default year, the policy or dynamic sets parameters that catalog version lacks (located at `policy_id` or `dynamic_id`), the dynamic sets a parameter the policy also sets (located at `dynamic_id`), or the household contract refuses the stored data. A job naming a row deleted @@ -163,8 +164,10 @@ A request is refused before anything is written: with 400 and a `code` when a row it names is missing (`unknown_region` and `unknown_dynamic` name the caller's own choice, and `unknown_dataset` its region's dataset; `unknown_catalog_version`, `unknown_policy`, `no_economy_worker`, -`dataset_not_in_bundle` and `missing_reference` are the service's state, -such as a catalog version missing while a release deploys), or, for a report +`dataset_not_in_bundle`, `missing_reference` and `dynamic_without_values` +are the service's state, such as a catalog version missing while a release +deploys, or a stored dynamic with no parameter values this release reads, +which is never applied as current law), or, for a report on the local-area dataset, when the default worker or the catalog can't serve it (`local_areas_unsupported` and `local_area_dataset_mismatch`, also the service's state; see "Local areas"); and with 422 and a `code` when a @@ -305,8 +308,9 @@ refuses what the report would calculate, located at the field it traces to: A policy or dynamic setting parameters the catalog version lacks is 422 `missing_parameters`, located at that side's `policy_id` or `dynamic_id`; a dynamic setting a parameter its side's policy also sets is 422 -`overlapping_parameters`; and a dynamic of another country is 400 -`unknown_dynamic`. +`overlapping_parameters`; a dynamic of another country is 400 +`unknown_dynamic`; and a dynamic with no parameter values this release reads +is 400 `dynamic_without_values`. ## Re-running a report or simulation @@ -382,7 +386,8 @@ record (a 422 reason's `loc` starts with `report` or `simulation`), with a household report's own codes: 400 `unknown_household` and `no_household_function`, and 422 `household_not_calculable`, located at the report's `household_id` or a side's `policy_id` or `dynamic_id`; a side's -dynamic of another country is 400 `unknown_dynamic`, and one setting a +dynamic of another country is 400 `unknown_dynamic`, one with no parameter +values this release reads 400 `dynamic_without_values`, and one setting a parameter the side's policy sets 422 `overlapping_parameters`, located at that side's `dynamic_id`. Without household reports configured, a household report the service could re-run answers 503 diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_api_models.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_api_models.py index 4e12ef597..0aac9b9cb 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_api_models.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_api_models.py @@ -108,6 +108,10 @@ # The catalog version's constituency and local-authority regions don't # all use the dataset the default worker calculates local areas on. "local_area_dataset_mismatch", + # A stored dynamic has no parameter values this release reads. API v1 + # stores no dynamic without values, so they are stored where this release + # doesn't read them; the dynamic is not applied as current law. + "dynamic_without_values", ] EconomyRefusalCode = Literal[CallerRowRefusalCode, ServiceStateRefusalCode] # Why stored values cannot be calculated (422). diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_submission_errors.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_submission_errors.py index 769571734..72af06072 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_submission_errors.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_submission_errors.py @@ -18,6 +18,7 @@ from typing import TYPE_CHECKING, Final, Literal from policyengine_simulation_persistence import ( + DynamicWithoutValuesError, LocalAreaDatasetMismatchError, MissingPolicyParametersError, OverlappingReformError, @@ -274,7 +275,9 @@ def simulation_values_refusal( Economy and household simulations alike: a policy or dynamic the country doesn't have, a dynamic of another country included, is refused - (400), its detail saying what ``named_by``; one setting parameters the + (400), its detail saying what ``named_by``; so is a dynamic with no + parameter values stored (``dynamic_without_values``), whose values this + release can't read, a state of the service; one setting parameters the catalog version for ``policyengine_version`` lacks, or a dynamic setting one its policy sets, cannot be calculated (422), each reason located under ``location`` at ``policy_id`` or ``dynamic_id``. Every detail is @@ -290,6 +293,14 @@ def simulation_values_refusal( code="unknown_dynamic", detail=f"{country} has no stored dynamic {named_by} names.", ) + if isinstance(error, DynamicWithoutValuesError): + return EconomySubmissionRefusedError( + code="dynamic_without_values", + detail=( + f"{country}'s stored dynamic that {named_by} names has no parameter " + "values the service can read." + ), + ) if isinstance(error, MissingPolicyParametersError): field_name = "policy_id" if error.source == "policy" else "dynamic_id" return EconomySubmissionUnprocessableError( diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_api_models.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_api_models.py index 029f07839..cbabbdd04 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_api_models.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_api_models.py @@ -29,6 +29,9 @@ "unknown_policy", # The country has no such dynamic: a dynamic of another country included. "unknown_dynamic", + # The dynamic has no parameter values this release reads, so it is not + # applied as current law: the service's state, as for economy routes. + "dynamic_without_values", # The default worker has no household function for the country. "no_household_function", # The database refused the job: a row it names was deleted after the reads. diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_calculations.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_calculations.py index 07389e224..640ca1195 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_calculations.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_calculations.py @@ -43,6 +43,7 @@ log_extra, ) from policyengine_simulation_persistence import ( + DynamicWithoutValuesError, EconomyRecordOutcomeUnknownError, HouseholdJobReferenceError, HouseholdJobStatus, @@ -473,6 +474,10 @@ async def _prepare( raise HouseholdCalculationRefusedError( code="unknown_dynamic", detail=str(error) ) from None + except DynamicWithoutValuesError as error: + raise HouseholdCalculationRefusedError( + code="dynamic_without_values", detail=str(error) + ) from None except MissingPolicyParametersError as error: field_name = "policy_id" if error.source == "policy" else "dynamic_id" raise HouseholdCalculationUnprocessableError( From a11dbbb0ca8d2a198091d8a334519c5d53ea0526 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:04:39 +0400 Subject: [PATCH 3/6] Check that the reform reader's two new statement functions take a session Review round 1: the session-signature test still named _read_reform, which the change split into _read_values and _reform_from_values, so its case raised AttributeError and the two new functions went unchecked. Co-Authored-By: Claude Opus 5.5 --- .../tests/test_economy_sessions.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libs/policyengine-simulation-persistence/tests/test_economy_sessions.py b/libs/policyengine-simulation-persistence/tests/test_economy_sessions.py index 9be355c7c..19b07d36e 100644 --- a/libs/policyengine-simulation-persistence/tests/test_economy_sessions.py +++ b/libs/policyengine-simulation-persistence/tests/test_economy_sessions.py @@ -201,7 +201,8 @@ (rerun_definitions, "read_simulation_definition"), (policy_reform, "read_policy_reform"), (policy_reform, "read_dynamic_reform"), - (policy_reform, "_read_reform"), + (policy_reform, "_read_values"), + (policy_reform, "_reform_from_values"), ) From f97cef8c467dd679f18a93643df5ae74f68b83a8 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:06:06 +0400 Subject: [PATCH 4/6] Say where a 400 can mean a dynamic without values, and test a window's re-run Review round 1's code-quality findings: - The household calculation route's 400 description and module docstring, the HouseholdRefusalCode comment, and the refusal errors' and read_refusal's docstrings now name a dynamic with no parameter values this release reads, not only a missing row or function. - A budget window's re-run refuses a side's dynamic without values, naming the side and creating no window run or call; a simulation's re-run starts no Modal call for one. Co-Authored-By: Claude Opus 5.5 --- .../economy_submission_errors.py | 11 +++++--- .../household_api_models.py | 3 ++- .../household_calculations.py | 6 ++++- .../household_routes.py | 23 +++++++++-------- .../tests/test_economy_reruns.py | 25 +++++++++++++++++-- 5 files changed, 50 insertions(+), 18 deletions(-) diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_submission_errors.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_submission_errors.py index 72af06072..6a936f513 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_submission_errors.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_submission_errors.py @@ -94,7 +94,11 @@ class RefusalSource: class EconomySubmissionRefusedError(Exception): - """A row the submission names, or a function it needs, is missing (400).""" + """A row or function the submission needs, or a dynamic's values, is missing (400). + + ``dynamic_without_values``: the dynamic exists, but this release reads + none of its parameter values. + """ def __init__(self, *, code: EconomyRefusalCode, detail: str) -> None: """Keep the reason's code and its description.""" @@ -200,8 +204,9 @@ def read_refusal( """Return the refusal a store read's error means, or None for any other error. A missing catalog version, region, dataset, policy or dynamic is refused - (400), and so is a catalog whose area regions don't use the dataset the - default worker calculates local areas on; a policy or dynamic setting + (400), and so are a dynamic with no parameter values this release reads + and a catalog whose area regions don't use the dataset the default worker + calculates local areas on; a policy or dynamic setting parameters the catalog version lacks, or both setting one, cannot be calculated (422). A report side's refusal (ReportSideError) is located on that side's fields, under ``source``: diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_api_models.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_api_models.py index cbabbdd04..a90efb699 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_api_models.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_api_models.py @@ -21,7 +21,8 @@ from pydantic.json_schema import SkipJsonSchema # Why a submission is refused (400): a row it names, or the household -# function it needs, does not exist. +# function it needs, does not exist, or its dynamic has no values this +# release reads. HouseholdRefusalCode = Literal[ # The country has no catalog version for the default worker's .py version. "unknown_catalog_version", diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_calculations.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_calculations.py index 640ca1195..40de7ed85 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_calculations.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_calculations.py @@ -109,7 +109,11 @@ class HouseholdCalculationRefusedError(Exception): - """A row the submission names, or the household function it needs, is missing.""" + """A row the submission names or the function it needs is missing, or its values. + + ``dynamic_without_values``: the dynamic exists, but this release reads + none of its parameter values. + """ def __init__(self, *, code: HouseholdRefusalCode, detail: str) -> None: """Keep the reason's code and its description.""" diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_routes.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_routes.py index 98abd50e9..f3b80f1cc 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_routes.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_routes.py @@ -9,16 +9,16 @@ returns the job as it stands: its status, the household function's result document once it has one, and its error message. -A refused submission answers 400 (a row it names, or the household function -it needs, is missing) or 422 (its fields, or the stored data it names, cannot -be calculated), naming why. Either route answers 503 with ``Retry-After`` -when household calculations are not configured or a dependency cannot be -read, and a submission does too when Modal refuses the call and its job was -failed; a submission's 503 always means no job will run. Every 500 of either -route is the JSON error with code ``internal_error``: an unexpected failure, -a request the service built and the household contract refuses, or a -submission whose job's commit failed after its row was inserted, so the job -may exist. +A refused submission answers 400 (a row it names, or the household function it +needs, is missing, or its dynamic has no values this release reads) or 422 +(its fields, or the stored data it names, cannot be calculated), naming why. +Either route answers 503 with ``Retry-After`` when household calculations are +not configured or a dependency cannot be read, and a submission does too when +Modal refuses the call and its job was failed; a submission's 503 always means +no job will run. Every 500 of either route is the JSON error with code +``internal_error``: an unexpected failure, a request the service built and the +household contract refuses, or a submission whose job's commit failed after +its row was inserted, so the job may exist. A submission gets its observability ID from the caller's header, or a new one, and passes it to the household function. ``household_jobs`` keeps no @@ -323,7 +323,8 @@ def add_household_calculation_routes( 400: { "description": ( "A row the request names, or the household function it " - "needs, is missing; code says which" + "needs, is missing, or its dynamic has no parameter values " + "this release reads; code says which" ), **_ERROR, }, diff --git a/projects/policyengine-simulation-entry/tests/test_economy_reruns.py b/projects/policyengine-simulation-entry/tests/test_economy_reruns.py index bb40277f6..0e414c862 100644 --- a/projects/policyengine-simulation-entry/tests/test_economy_reruns.py +++ b/projects/policyengine-simulation-entry/tests/test_economy_reruns.py @@ -417,16 +417,37 @@ def test_a_stored_simulations_dynamic_without_values_is_refused() -> None: store = FakeRerunStore( inputs_failure=DynamicWithoutValuesError("store text: no values") ) + caller = FakeCaller() with pytest.raises(EconomySubmissionRefusedError) as refused: - _rerun_simulation(rerun_service(store)) + _rerun_simulation(rerun_service(store, caller=caller)) assert (refused.value.code, refused.value.detail) == ( "dynamic_without_values", "us's stored dynamic that the simulation names has no parameter values " "the service can read.", ) - assert store.simulation_reruns == [] + assert (store.simulation_reruns, caller.simulation_runs) == ([], []) + + +def test_a_stored_windows_dynamic_without_values_is_refused_naming_the_side() -> None: + store = FakeRerunStore( + report_definition=STORED_WINDOW, + inputs_failure=ReportSideError( + "reform", DynamicWithoutValuesError("store text: no values") + ), + ) + caller = FakeCaller() + + with pytest.raises(EconomySubmissionRefusedError) as refused: + _rerun_report(rerun_service(store, caller=caller, advancer=FakeAdvancer(store))) + + assert (refused.value.code, refused.value.detail) == ( + "dynamic_without_values", + "us's stored dynamic that the report's reform names has no parameter " + "values the service can read.", + ) + assert (store.windows, caller.report_runs) == ([], []) def _started_cliff_runs(caller: FakeCaller) -> set[UUID]: From 4840b4f64f1e7db1a2c20a77050244aa75e43b26 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:18:48 +0400 Subject: [PATCH 5/6] Name dynamic_without_values in the 400 descriptions and say the values can't be read (failing) Review round 2's code-quality findings, tests first: - The economy create routes', re-run routes' and household calculation route's OpenAPI 400 descriptions name dynamic_without_values. - The reader's message says the dynamic has no parameter values the service can read, as every route's detail does; the household calculation route passes it on as its detail. - A report asking for cliffs, and a re-run asking for them, with a side's dynamic without values, writes and starts no cliff calculation (passes already); the report submission test raises the store's ReportSideError and checks the report's detail. Co-Authored-By: Claude Opus 5.5 --- .../tests/test_dynamic_reform.py | 3 +- .../tests/test_household_job_store.py | 3 +- .../tests/test_economy_reruns.py | 21 +++++++++++ .../tests/test_economy_submissions.py | 36 ++++++++++++++----- .../tests/test_household_calculations.py | 4 +-- .../tests/test_openapi.py | 3 ++ 6 files changed, 57 insertions(+), 13 deletions(-) diff --git a/libs/policyengine-simulation-persistence/tests/test_dynamic_reform.py b/libs/policyengine-simulation-persistence/tests/test_dynamic_reform.py index efb98abd4..309bb38da 100644 --- a/libs/policyengine-simulation-persistence/tests/test_dynamic_reform.py +++ b/libs/policyengine-simulation-persistence/tests/test_dynamic_reform.py @@ -187,7 +187,8 @@ def test_a_dynamic_without_values_is_refused_instead_of_read_as_current_law( ) assert str(alone.value) == ( - f"us's dynamic {dynamic_without_values_id} has no parameter values" + f"us's dynamic {dynamic_without_values_id} has no parameter values " + "the service can read" ) assert str(with_policy.value) == str(alone.value) # It is not a missing dynamic: the dynamic exists. diff --git a/libs/policyengine-simulation-persistence/tests/test_household_job_store.py b/libs/policyengine-simulation-persistence/tests/test_household_job_store.py index 0aa933bf7..29a132c3a 100644 --- a/libs/policyengine-simulation-persistence/tests/test_household_job_store.py +++ b/libs/policyengine-simulation-persistence/tests/test_household_job_store.py @@ -249,7 +249,8 @@ def read(dynamic_id: UUID) -> None: ("gov.simulation.removed",), ) assert str(without_values.value) == ( - f"us's dynamic {dynamic_without_values_id} has no parameter values" + f"us's dynamic {dynamic_without_values_id} has no parameter values " + "the service can read" ) diff --git a/projects/policyengine-simulation-entry/tests/test_economy_reruns.py b/projects/policyengine-simulation-entry/tests/test_economy_reruns.py index 0e414c862..cb523b1ea 100644 --- a/projects/policyengine-simulation-entry/tests/test_economy_reruns.py +++ b/projects/policyengine-simulation-entry/tests/test_economy_reruns.py @@ -413,6 +413,27 @@ def test_a_stored_dynamic_without_values_is_refused_naming_the_report_side() -> assert (store.report_reruns, caller.report_runs) == ([], []) +def test_a_rerun_asking_for_cliffs_with_a_dynamic_without_values_starts_nothing() -> ( + None +): + store = FakeRerunStore( + report_definition=replace(STORED_REPORT, keyed=True), + inputs_failure=ReportSideError( + "reform", DynamicWithoutValuesError("store text: no values") + ), + ) + caller = FakeCaller() + + with pytest.raises(EconomySubmissionRefusedError) as refused: + _rerun_report( + rerun_service(store, caller=caller), ReportRerunRequest(include_cliffs=True) + ) + + assert refused.value.code == "dynamic_without_values" + assert (store.report_reruns, store.cliff_requests) == ([], []) + assert (caller.report_runs, caller.cliff_calculations) == ([], []) + + def test_a_stored_simulations_dynamic_without_values_is_refused() -> None: store = FakeRerunStore( inputs_failure=DynamicWithoutValuesError("store text: no values") diff --git a/projects/policyengine-simulation-entry/tests/test_economy_submissions.py b/projects/policyengine-simulation-entry/tests/test_economy_submissions.py index e31755331..cbb85cccc 100644 --- a/projects/policyengine-simulation-entry/tests/test_economy_submissions.py +++ b/projects/policyengine-simulation-entry/tests/test_economy_submissions.py @@ -631,22 +631,40 @@ def test_a_missing_row_is_refused_before_anything_is_written(error, code) -> Non def test_a_dynamic_without_values_is_refused_before_anything_is_written() -> None: - """A dynamic whose values this release can't read is never run as current law.""" - store = FakeStore(read_failure=DynamicWithoutValuesError("store text: no values")) + """A dynamic whose values this release can't read is never run as current law. + + A report asking for cliffs writes and starts no cliff calculation either. + """ + report_store = FakeStore( + read_failure=ReportSideError( + "reform", DynamicWithoutValuesError("store text: no values") + ) + ) + simulation_store = FakeStore( + read_failure=DynamicWithoutValuesError("store text: no values") + ) caller = FakeCaller() with pytest.raises(EconomySubmissionRefusedError) as report_refusal: - _submit_report(service(store, caller=caller)) + _submit_report( + service(report_store, caller=caller), report_request(include_cliffs=True) + ) with pytest.raises(EconomySubmissionRefusedError) as simulation_refusal: - _submit_simulation(service(store, caller=caller)) + _submit_simulation(service(simulation_store, caller=caller)) - assert report_refusal.value.code == simulation_refusal.value.code - assert simulation_refusal.value.code == "dynamic_without_values" - assert simulation_refusal.value.detail == ( + assert (report_refusal.value.code, report_refusal.value.detail) == ( + "dynamic_without_values", + "us's stored dynamic that the request's reform names has no parameter " + "values the service can read.", + ) + assert (simulation_refusal.value.code, simulation_refusal.value.detail) == ( + "dynamic_without_values", "us's stored dynamic that the request names has no parameter values the " - "service can read." + "service can read.", ) - assert (store.reports, store.simulations, caller.report_runs) == ([], [], []) + assert (report_store.reports, report_store.cliff_requests) == ([], []) + assert simulation_store.simulations == [] + assert (caller.report_runs, caller.cliff_calculations) == ([], []) def test_values_the_catalog_version_lacks_cannot_be_calculated() -> None: diff --git a/projects/policyengine-simulation-entry/tests/test_household_calculations.py b/projects/policyengine-simulation-entry/tests/test_household_calculations.py index b3f3c5f1c..2457b9926 100644 --- a/projects/policyengine-simulation-entry/tests/test_household_calculations.py +++ b/projects/policyengine-simulation-entry/tests/test_household_calculations.py @@ -519,12 +519,12 @@ async def test_without_spm_settings_or_a_saved_selection_none_is_sent(): ( FakeStore( read_failure=DynamicWithoutValuesError( - "us's dynamic z has no parameter values" + "us's dynamic z has no parameter values the service can read" ) ), FakeWorkers(), "dynamic_without_values", - "us's dynamic z has no parameter values", + "us's dynamic z has no parameter values the service can read", ), ], ) diff --git a/projects/policyengine-simulation-entry/tests/test_openapi.py b/projects/policyengine-simulation-entry/tests/test_openapi.py index 68abcf444..3613c9b99 100644 --- a/projects/policyengine-simulation-entry/tests/test_openapi.py +++ b/projects/policyengine-simulation-entry/tests/test_openapi.py @@ -304,6 +304,7 @@ def test_household_routes_declare_every_answer(): ] assert "job_state_unknown" not in code["enum"] assert "internal_error" in code["enum"] + assert "dynamic_without_values" in submit["400"]["description"] assert {"unknown_policy", "unknown_dynamic", "dynamic_without_values"} <= set( code["enum"] ) @@ -401,6 +402,7 @@ def test_economy_routes_declare_every_answer(): record = path.removeprefix("/").removesuffix("s") assert f"{record}_id" in responses["503"]["description"] assert "nothing was written" in responses["400"]["description"] + assert "dynamic_without_values" in responses["400"]["description"] # A create answers the record and run it ended on, joined or created. assert "joined" in responses["201"]["description"] assert "found or created" in responses["503"]["description"] @@ -470,6 +472,7 @@ def test_rerun_routes_declare_every_answer(): assert _response_schema(responses[status_code]) == error assert _response_schema(responses["422"]) == unprocessable assert "run_id" in responses["503"]["description"] + assert "dynamic_without_values" in responses["400"]["description"] # Both answer the run they ended on, created or joined. assert "joined" in responses["201"]["description"] # No re-run is refused while a run is under way: an unforced one joins From d775da71bf0b82148629b8f16520aebb73ef3ff0 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:19:18 +0400 Subject: [PATCH 6/6] Name dynamic_without_values in the 400 descriptions and say the values can't be read Review round 2's code-quality findings: - The economy create routes' and re-run routes' 400 descriptions give dynamic_without_values as one of the service's states, and the household calculation route's names the code. - DynamicWithoutValuesError's message says the dynamic has no parameter values the service can read, so the household calculation route's detail, which passes it on, says what every other route's says. Co-Authored-By: Claude Opus 5.5 --- .../src/policyengine_simulation_persistence/policy_reform.py | 5 ++++- .../policyengine_simulation_entry/economy_rerun_routes.py | 4 +++- .../src/policyengine_simulation_entry/economy_routes.py | 4 +++- .../src/policyengine_simulation_entry/household_routes.py | 2 +- 4 files changed, 11 insertions(+), 4 deletions(-) diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/policy_reform.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/policy_reform.py index 926326a3f..edfc76b35 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/policy_reform.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/policy_reform.py @@ -197,7 +197,10 @@ def read_dynamic_reform( raise UnknownDynamicError(msg) values = _read_values(session, owner=ParameterValue.dynamic_id == dynamic_id) if not values: - msg = f"{country}'s dynamic {dynamic_id} has no parameter values" + msg = ( + f"{country}'s dynamic {dynamic_id} has no parameter values " + "the service can read" + ) raise DynamicWithoutValuesError(msg) return _reform_from_values( session, values, catalog_version_id=catalog_version_id, source="dynamic" diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_rerun_routes.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_rerun_routes.py index 391d651f3..7c43818b7 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_rerun_routes.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_rerun_routes.py @@ -177,7 +177,9 @@ def _responses(record: RecordName) -> dict[int | str, dict[str, Any]]: f"version, or a function the {record} needs is missing" f"{_HOUSEHOLD_ANSWERS[record].get(400, '')}; nothing was written. " f"{_STORED_ROW_CODES[record]} name the stored {record}'s own " - "rows; any other code is the service's state" + "rows; any other code is the service's state, such as " + "dynamic_without_values (a stored dynamic with no parameter values " + "this release reads)" ), **ERROR_ANSWER, }, diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_routes.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_routes.py index 75a5f3eae..fc6dfe509 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_routes.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_routes.py @@ -136,7 +136,9 @@ "none); a household report's unknown_household and " "no_household_function name its household and the default worker's " "household function; any other code is the service's state, such as " - "a catalog version missing while a release deploys, or, for a report " + "a catalog version missing while a release deploys, " + "dynamic_without_values (a stored dynamic with no parameter values this " + "release reads, which is never calculated as current law), or, for a report " "on the local-area dataset, local_areas_unsupported (the default " "worker declares no local-area report runs of this service's input " "version) and local_area_dataset_mismatch (the catalog version doesn't " diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_routes.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_routes.py index f3b80f1cc..95adda8c5 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_routes.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_routes.py @@ -324,7 +324,7 @@ def add_household_calculation_routes( "description": ( "A row the request names, or the household function it " "needs, is missing, or its dynamic has no parameter values " - "this release reads; code says which" + "this release reads (dynamic_without_values); code says which" ), **_ERROR, },