From 2bcd63e4815cc8e8edad035f4fb9c8f837ff01ce Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 05:01:37 +0400 Subject: [PATCH 1/8] Add failing tests for creating a report by key without a run MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit API v1's one-time migration (D4 · 1) creates each saved report's report with no run, and app v3 starts its first run when it is opened. These tests describe sim's new POST /reports/without-run, the persistence functions behind it, and the re-run of a keyed budget window that has no window run, which today has no years and is refused. The test that a window whose report no longer matches its own key gets no years passes already; it guards the key lookup the fix adds. Co-Authored-By: Claude Opus 5.5 --- .../tests/test_economy_window_reruns.py | 128 +++++ .../tests/test_reports_without_run.py | 503 ++++++++++++++++++ .../tests/test_openapi.py | 62 +++ .../tests/test_reports_without_run.py | 502 +++++++++++++++++ 4 files changed, 1195 insertions(+) create mode 100644 libs/policyengine-simulation-persistence/tests/test_reports_without_run.py create mode 100644 projects/policyengine-simulation-entry/tests/test_reports_without_run.py diff --git a/libs/policyengine-simulation-persistence/tests/test_economy_window_reruns.py b/libs/policyengine-simulation-persistence/tests/test_economy_window_reruns.py index b271f1247..05257b4c3 100644 --- a/libs/policyengine-simulation-persistence/tests/test_economy_window_reruns.py +++ b/libs/policyengine-simulation-persistence/tests/test_economy_window_reruns.py @@ -663,3 +663,131 @@ def test_a_forced_window_rerun_is_an_extra_run_beside_any_run_on_its_versions( assert all(run["forced"] for run in year_runs) assert len(simulation_runs) == 2 * len(WINDOW_YEARS) assert all(run["forced"] for run in simulation_runs) + + +def _remove_window_runs(connection: Connection, found: FoundBudgetWindow) -> None: + """Delete a keyed window's runs as the superuser, leaving a window with none. + + What is left is what a create without a run stores: the report and each + year's simulations, found by their keys. + """ + connection.execute(text("RESET ROLE")) + simulation_run_ids = [ + side.simulation_run_id + for year in found.years + for side in (year.baseline, year.reform) + ] + connection.execute( + text("DELETE FROM public.report_runs WHERE budget_window_run_id = :id"), + {"id": found.window_run.id}, + ) + connection.execute( + text("DELETE FROM public.budget_window_runs WHERE id = :id"), + {"id": found.window_run.id}, + ) + connection.execute( + text("DELETE FROM public.simulation_runs WHERE id = ANY(:ids)"), + {"ids": simulation_run_ids}, + ) + act_as_the_service(connection) + + +def _year_simulations(found: FoundBudgetWindow) -> tuple[WindowYearDefinition, ...]: + return tuple( + WindowYearDefinition( + year=year.year, + baseline_simulation_id=year.baseline.simulation_id, + reform_simulation_id=year.reform.simulation_id, + ) + for year in found.years + ) + + +def test_a_keyed_window_with_no_window_run_names_each_years_simulations_by_key( + public_api_database_url, +) -> None: + """D4 · 0: a window created without a run can be re-run for its first run.""" + with rolled_back_transaction(public_api_database_url) as connection: + economy = insert_economy_catalog(connection) + act_as_the_service(connection) + found = _keyed_window(connection, economy) + _remove_window_runs(connection, found) + + definition = in_session(connection, read_report_definition, found.report_id) + + assert definition is not None + assert (definition.kind, definition.keyed) == ("budget_window", True) + assert definition.window_years == _year_simulations(found) + + +def test_a_keyed_window_with_no_window_run_whose_row_lost_its_key_has_no_years( + public_api_database_url, +) -> None: + """Years are found by key only when the report's own key still matches it.""" + with rolled_back_transaction(public_api_database_url) as connection: + economy = insert_economy_catalog(connection) + act_as_the_service(connection) + found = _keyed_window(connection, economy) + _remove_window_runs(connection, found) + connection.execute(text("RESET ROLE")) + # Its window's first two years' simulations still exist under their + # keys, so only the report's own key tells this window apart. + connection.execute( + text("UPDATE public.reports SET budget_window_size = 2 WHERE id = :id"), + {"id": found.report_id}, + ) + act_as_the_service(connection) + + definition = in_session(connection, read_report_definition, found.report_id) + + assert definition is not None + assert definition.window_years == () + + +def test_a_rerun_gives_a_keyed_window_with_no_window_run_its_first_window_run( + public_api_database_url, +) -> None: + with rolled_back_transaction(public_api_database_url) as connection: + economy = insert_economy_catalog(connection) + act_as_the_service(connection) + found = _keyed_window(connection, economy) + _remove_window_runs(connection, found) + definition = in_session(connection, read_report_definition, found.report_id) + assert definition is not None + rerun = NewWindowRerun( + report_id=found.report_id, + window_run_id=uuid4(), + population=economy.population(year=WINDOW_YEARS[0]), + versions=VERSIONS, + recalculate=False, + years=tuple( + WindowRerunYear( + year=year.year, + report_run_id=uuid4(), + baseline=RerunSide( + simulation_id=year.baseline_simulation_id, + simulation_run_id=uuid4(), + ), + reform=RerunSide( + simulation_id=year.reform_simulation_id, + simulation_run_id=uuid4(), + ), + ) + for year in definition.window_years + ), + ) + + created = in_session(connection, insert_window_rerun, rerun) + year_runs = [ + _row(connection, "report_runs", year.report_run_id) + for year in created.years + ] + + assert (created.window_run.id, created.window_run.inserted) == ( + rerun.window_run_id, + True, + ) + assert [year_run["year"] for year_run in year_runs] == list(WINDOW_YEARS) + assert {year_run["budget_window_run_id"] for year_run in year_runs} == { + rerun.window_run_id + } diff --git a/libs/policyengine-simulation-persistence/tests/test_reports_without_run.py b/libs/policyengine-simulation-persistence/tests/test_reports_without_run.py new file mode 100644 index 000000000..99d89da65 --- /dev/null +++ b/libs/policyengine-simulation-persistence/tests/test_reports_without_run.py @@ -0,0 +1,503 @@ +"""Find or create a report and its simulations by key, without a run (D4 · 0). + +API v1's one-time migration creates each saved report's report with no +run: app v3 starts its first run when someone opens it. The create finds or +inserts each side's simulations and the report by their keys, as a create +with a run does (``keyed_economy_records``, ``keyed_window_records``, +``keyed_household_records``), and inserts no run of any kind, so a later +create with a run finds the same rows. These run against a database API +v1's own v2 migration chain built (``PUBLIC_API_SCHEMA_DATABASE_URL``), as +the simulation service's role, in a transaction rolled back afterwards. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING +from uuid import UUID, uuid4 + +import pytest +from conftest import ( + act_as_the_service, + economy_store_on, + in_session, + rolled_back_transaction, + session_factory_on, +) +from economy_rows import ( + CURRENT_LAW, + VERSIONS, + EconomyCatalog, + insert_economy_catalog, +) +from policyengine_simulation_persistence import ( + KEY_VERSION, + EconomyReportDefinition, + FoundBudgetWindowWithoutRun, + FoundReportWithoutRun, + HouseholdReportDefinition, + HouseholdReportStore, + KeyedBudgetWindow, + KeyedBudgetWindowWithoutRun, + KeyedEconomyReport, + KeyedEconomyReportWithoutRun, + KeyedHouseholdReport, + KeyedHouseholdReportWithoutRun, + KeyedWindowYear, + ProposedSide, + SimulationChoice, + WindowYearSimulations, + find_or_create_budget_window, + find_or_create_budget_window_without_run, + find_or_create_economy_report, + find_or_create_economy_report_without_run, + find_or_create_household_report, + find_or_create_household_report_without_run, +) +from public_api_rows import insert_household, insert_policy +from sqlalchemy import text + +if TYPE_CHECKING: + from sqlalchemy import Connection + +pytestmark = pytest.mark.public_api_schema + +FIRST_YEAR = 2026 +WINDOW_YEARS = (2026, 2027, 2028) +STATEMENT_TIMEOUT_MILLISECONDS = 5_000 +RUN_TABLES = ("simulation_runs", "report_runs", "budget_window_runs") +HOUSEHOLD_DOCUMENT = { + "people": [ + { + "id": "you", + "values": {"age": 40}, + "memberships": {"household": "your household"}, + } + ], + "household": [{"id": "your household", "values": {}}], +} + + +def _report_definition( + economy: EconomyCatalog, reform: SimulationChoice, *, window_size: int | None +) -> EconomyReportDefinition: + return EconomyReportDefinition( + country=economy.catalog.country, + baseline=CURRENT_LAW, + reform=reform, + dataset_name="populace_us_2024", + region_code="us", + year=FIRST_YEAR, + budget_window_size=window_size, + spm=None, + ) + + +def _proposed_side() -> ProposedSide: + return ProposedSide(simulation_id=uuid4(), simulation_run_id=uuid4()) + + +def _economy_report( + economy: EconomyCatalog, reform: SimulationChoice +) -> KeyedEconomyReport: + """Return a request's economy report with its run, with fresh IDs to propose.""" + return KeyedEconomyReport( + definition=_report_definition(economy, reform, window_size=None), + report_id=uuid4(), + run_id=uuid4(), + baseline=_proposed_side(), + reform=_proposed_side(), + tax_benefit_model_id=economy.catalog.model_id, + population=economy.population(), + versions=VERSIONS, + inputs={}, + ) + + +def _budget_window( + economy: EconomyCatalog, reform: SimulationChoice +) -> KeyedBudgetWindow: + """Return a request's three-year window with its run, with fresh IDs.""" + return KeyedBudgetWindow( + definition=_report_definition(economy, reform, window_size=len(WINDOW_YEARS)), + report_id=uuid4(), + window_run_id=uuid4(), + tax_benefit_model_id=economy.catalog.model_id, + population=economy.population(), + versions=VERSIONS, + inputs={}, + years=tuple( + KeyedWindowYear( + year=year, + report_run_id=uuid4(), + baseline=_proposed_side(), + reform=_proposed_side(), + ) + for year in WINDOW_YEARS + ), + ) + + +def _household_report( + economy: EconomyCatalog, household_id: UUID, reform: SimulationChoice | None +) -> KeyedHouseholdReport: + """Return a request's household report with its run, with fresh IDs.""" + return KeyedHouseholdReport( + definition=HouseholdReportDefinition( + country="us", + baseline=CURRENT_LAW, + reform=reform, + household_id=household_id, + year=FIRST_YEAR, + ), + report_id=uuid4(), + run_id=uuid4(), + baseline=_proposed_side(), + reform=None if reform is None else _proposed_side(), + tax_benefit_model_id=economy.catalog.model_id, + tax_benefit_model_version_id=economy.catalog.version_id, + versions=VERSIONS, + ) + + +def _reform(connection: Connection, economy: EconomyCatalog) -> SimulationChoice: + return SimulationChoice( + policy_id=insert_policy(connection, economy.catalog), dynamic_id=None + ) + + +def _household(connection: Connection) -> UUID: + return insert_household( + connection, country="us", default_year=FIRST_YEAR, document=HOUSEHOLD_DOCUMENT + ) + + +def _row(connection: Connection, table_name: str, row_id: UUID) -> dict: + row = connection.execute( + text(f"SELECT * FROM public.{table_name} WHERE id = :id"), # noqa: S608 # fixed table names + {"id": row_id}, + ).mappings() + return dict(row.one()) + + +def _count(connection: Connection, table_name: str) -> int: + return connection.execute( + text(f"SELECT count(*) FROM public.{table_name}") # noqa: S608 # fixed table names + ).scalar_one() + + +def _run_counts(connection: Connection) -> dict[str, int]: + return {name: _count(connection, name) for name in RUN_TABLES} + + +def _record_counts(connection: Connection) -> dict[str, int]: + return {name: _count(connection, name) for name in ("simulations", "reports")} + + +def test_an_economy_report_without_a_run_is_created_with_its_simulations_only( + public_api_database_url, +) -> None: + with rolled_back_transaction(public_api_database_url) as connection: + economy = insert_economy_catalog(connection) + request = _economy_report(economy, _reform(connection, economy)).without_run + act_as_the_service(connection) + runs_before = _run_counts(connection) + + found = in_session( + connection, find_or_create_economy_report_without_run, request + ) + report = _row(connection, "reports", found.report_id) + reform_simulation = _row(connection, "simulations", found.reform_simulation_id) + runs_after = _run_counts(connection) + + assert isinstance(request, KeyedEconomyReportWithoutRun) + assert found == FoundReportWithoutRun( + report_id=request.report_id, + report_inserted=True, + baseline_simulation_id=request.baseline_simulation_id, + reform_simulation_id=request.reform_simulation_id, + ) + assert (report["key_version"], report["definition_key"]) == ( + KEY_VERSION, + request.definition.definition_key, + ) + assert report["baseline_simulation_id"] == request.baseline_simulation_id + assert reform_simulation["definition_key"] == ( + request.definition.simulation("reform").definition_key + ) + assert runs_after == runs_before + + +def test_an_economy_report_without_a_run_finds_the_report_a_create_with_one_made( + public_api_database_url, +) -> None: + with rolled_back_transaction(public_api_database_url) as connection: + economy = insert_economy_catalog(connection) + reform = _reform(connection, economy) + act_as_the_service(connection) + created = in_session( + connection, find_or_create_economy_report, _economy_report(economy, reform) + ) + counts = (_record_counts(connection), _run_counts(connection)) + + found = in_session( + connection, + find_or_create_economy_report_without_run, + _economy_report(economy, reform).without_run, + ) + counts_again = (_record_counts(connection), _run_counts(connection)) + + assert found == FoundReportWithoutRun( + report_id=created.report_id, + report_inserted=False, + baseline_simulation_id=created.baseline.simulation_id, + reform_simulation_id=created.reform.simulation_id, + ) + assert counts_again == counts + + +def test_a_create_with_a_run_finds_the_economy_report_created_without_one( + public_api_database_url, +) -> None: + with rolled_back_transaction(public_api_database_url) as connection: + economy = insert_economy_catalog(connection) + reform = _reform(connection, economy) + act_as_the_service(connection) + without_run = in_session( + connection, + find_or_create_economy_report_without_run, + _economy_report(economy, reform).without_run, + ) + + created = in_session( + connection, find_or_create_economy_report, _economy_report(economy, reform) + ) + + assert (created.report_id, created.report_inserted) == ( + without_run.report_id, + False, + ) + assert created.run.inserted is True + assert (created.baseline.simulation_id, created.reform.simulation_id) == ( + without_run.baseline_simulation_id, + without_run.reform_simulation_id, + ) + + +def test_a_budget_window_without_a_run_is_created_with_each_years_simulations_only( + public_api_database_url, +) -> None: + with rolled_back_transaction(public_api_database_url) as connection: + economy = insert_economy_catalog(connection) + request = _budget_window(economy, _reform(connection, economy)).without_run + act_as_the_service(connection) + runs_before = _run_counts(connection) + + found = in_session( + connection, find_or_create_budget_window_without_run, request + ) + report = _row(connection, "reports", found.report_id) + year_simulations = [ + _row(connection, "simulations", year.reform_simulation_id) + for year in found.years + ] + runs_after = _run_counts(connection) + + assert isinstance(request, KeyedBudgetWindowWithoutRun) + assert found == FoundBudgetWindowWithoutRun( + report_id=request.report_id, report_inserted=True, years=request.years + ) + assert [year.year for year in found.years] == list(WINDOW_YEARS) + assert (report["budget_window_size"], report["definition_key"]) == ( + len(WINDOW_YEARS), + request.definition.definition_key, + ) + # The report names its first year's simulations. + assert report["reform_simulation_id"] == found.years[0].reform_simulation_id + for year, simulation in zip(found.years, year_simulations, strict=True): + assert simulation["year"] == year.year + assert simulation["definition_key"] == ( + request.definition.simulation("reform", year=year.year).definition_key + ) + assert runs_after == runs_before + + +def test_a_budget_window_without_a_run_finds_the_window_a_create_with_one_made( + public_api_database_url, +) -> None: + with rolled_back_transaction(public_api_database_url) as connection: + economy = insert_economy_catalog(connection) + reform = _reform(connection, economy) + act_as_the_service(connection) + created = in_session( + connection, find_or_create_budget_window, _budget_window(economy, reform) + ) + counts = (_record_counts(connection), _run_counts(connection)) + + found = in_session( + connection, + find_or_create_budget_window_without_run, + _budget_window(economy, reform).without_run, + ) + counts_again = (_record_counts(connection), _run_counts(connection)) + + assert (found.report_id, found.report_inserted) == (created.report_id, False) + assert found.years == tuple( + WindowYearSimulations( + year=year.year, + baseline_simulation_id=year.baseline.simulation_id, + reform_simulation_id=year.reform.simulation_id, + ) + for year in created.years + ) + assert counts_again == counts + + +def test_a_create_with_a_run_finds_the_budget_window_created_without_one( + public_api_database_url, +) -> None: + with rolled_back_transaction(public_api_database_url) as connection: + economy = insert_economy_catalog(connection) + reform = _reform(connection, economy) + act_as_the_service(connection) + without_run = in_session( + connection, + find_or_create_budget_window_without_run, + _budget_window(economy, reform).without_run, + ) + + created = in_session( + connection, find_or_create_budget_window, _budget_window(economy, reform) + ) + + assert (created.report_id, created.report_inserted) == ( + without_run.report_id, + False, + ) + assert created.window_run.inserted is True + assert [year.reform.simulation_id for year in created.years] == [ + year.reform_simulation_id for year in without_run.years + ] + + +@pytest.mark.parametrize("sides", ["baseline_and_reform", "baseline_alone"]) +def test_a_household_report_without_a_run_is_created_with_its_simulations_only( + public_api_database_url, sides: str +) -> None: + with_reform = sides == "baseline_and_reform" + with rolled_back_transaction(public_api_database_url) as connection: + economy = insert_economy_catalog(connection) + reform = _reform(connection, economy) if with_reform else None + request = _household_report(economy, _household(connection), reform).without_run + act_as_the_service(connection) + runs_before = _run_counts(connection) + + found = in_session( + connection, find_or_create_household_report_without_run, request + ) + report = _row(connection, "reports", found.report_id) + runs_after = _run_counts(connection) + + assert isinstance(request, KeyedHouseholdReportWithoutRun) + assert found == FoundReportWithoutRun( + report_id=request.report_id, + report_inserted=True, + baseline_simulation_id=request.baseline_simulation_id, + reform_simulation_id=request.reform_simulation_id, + ) + assert (found.reform_simulation_id is None) is (not with_reform) + assert (report["household_id"], report["definition_key"]) == ( + request.definition.household_id, + request.definition.definition_key, + ) + assert report["reform_simulation_id"] == request.reform_simulation_id + assert runs_after == runs_before + + +def test_a_household_report_without_a_run_finds_the_report_a_create_with_one_made( + public_api_database_url, +) -> None: + with rolled_back_transaction(public_api_database_url) as connection: + economy = insert_economy_catalog(connection) + reform = _reform(connection, economy) + household_id = _household(connection) + act_as_the_service(connection) + created = in_session( + connection, + find_or_create_household_report, + _household_report(economy, household_id, reform), + ) + counts = (_record_counts(connection), _run_counts(connection)) + + found = in_session( + connection, + find_or_create_household_report_without_run, + _household_report(economy, household_id, reform).without_run, + ) + counts_again = (_record_counts(connection), _run_counts(connection)) + + assert created.reform is not None + assert found == FoundReportWithoutRun( + report_id=created.report_id, + report_inserted=False, + baseline_simulation_id=created.baseline.simulation_id, + reform_simulation_id=created.reform.simulation_id, + ) + assert counts_again == counts + + +def test_a_household_report_without_a_run_names_a_reform_side_with_a_reform() -> None: + definition = HouseholdReportDefinition( + country="us", + baseline=CURRENT_LAW, + reform=None, + household_id=uuid4(), + year=FIRST_YEAR, + ) + + with pytest.raises(ValueError, match="reform side exactly when it has one"): + KeyedHouseholdReportWithoutRun( + definition=definition, + report_id=uuid4(), + baseline_simulation_id=uuid4(), + reform_simulation_id=uuid4(), + tax_benefit_model_id=uuid4(), + tax_benefit_model_version_id=uuid4(), + ) + + +def test_the_stores_create_reports_without_a_run_in_their_own_transactions( + public_api_database_url, +) -> None: + with rolled_back_transaction(public_api_database_url) as connection: + economy = insert_economy_catalog(connection) + reform = _reform(connection, economy) + household_id = _household(connection) + act_as_the_service(connection) + economy_store = economy_store_on(connection) + household_store = HouseholdReportStore.from_session_factory( + session_factory_on(connection), + statement_timeout_milliseconds=STATEMENT_TIMEOUT_MILLISECONDS, + ) + runs_before = _run_counts(connection) + + report = economy_store.find_or_create_report_without_run( + _economy_report(economy, reform).without_run + ) + window = economy_store.find_or_create_budget_window_without_run( + _budget_window(economy, reform).without_run + ) + household_report = household_store.find_or_create_report_without_run( + _household_report(economy, household_id, reform).without_run + ) + stored_report_ids = { + _row(connection, "reports", report_id)["id"] + for report_id in ( + report.report_id, + window.report_id, + household_report.report_id, + ) + } + runs_after = _run_counts(connection) + + assert len(stored_report_ids) == 3 + assert runs_after == runs_before diff --git a/projects/policyengine-simulation-entry/tests/test_openapi.py b/projects/policyengine-simulation-entry/tests/test_openapi.py index 92c97ec1b..127433904 100644 --- a/projects/policyengine-simulation-entry/tests/test_openapi.py +++ b/projects/policyengine-simulation-entry/tests/test_openapi.py @@ -41,6 +41,7 @@ class OpenAPIDocument(TypedDict): ("POST", "/ping"), ("POST", "/reports"), ("POST", "/reports/{report_id}/runs"), + ("POST", "/reports/without-run"), ("POST", "/simulate/economy/budget-window"), ("POST", "/simulate/economy/comparison"), ("POST", "/simulations"), @@ -90,6 +91,7 @@ def operation_ids(spec: OpenAPIDocument) -> dict[tuple[str, str], str]: "/reports", "/reports/{report_id}", "/reports/{report_id}/runs", + "/reports/without-run", "/simulations", "/simulations/{simulation_id}", "/simulations/{simulation_id}/runs", @@ -116,6 +118,8 @@ def operation_ids(spec: OpenAPIDocument) -> dict[tuple[str, str], str]: "ReportRerunRequest", "ReportRunRead", "ReportRunStatus", + "ReportWithoutRunCreated", + "ReportWithoutRunYear", "SimulationRunRead", "SimulationStatus", ) @@ -719,3 +723,61 @@ def test_a_report_create_takes_include_cliffs_and_answers_each_sides_cliffs(): # A create no longer refuses cliffs. create_answers = _responses(spec, "post", "/reports") assert "cliffs_not_available" not in create_answers["422"]["description"] + + +def test_a_report_without_a_run_takes_a_reports_body_and_declares_its_answers(): + """D4 · 0: the one-time migration's reports are created with no run.""" + spec = create_app().openapi() + path = "/reports/without-run" + operation = spec["paths"][path]["post"] + responses = _responses(spec, "post", path) + schemas = spec["components"]["schemas"] + + assert operation_ids(cast("OpenAPIDocument", spec))[("POST", path)] == ( + "create_report_without_run" + ) + assert ( + operation["requestBody"]["content"]["application/json"]["schema"] + == spec["paths"]["/reports"]["post"]["requestBody"]["content"][ + "application/json" + ]["schema"] + ) + assert set(responses) == {"201", "400", "403", "422", "500", "503"} + assert _response_schema(responses["201"]) == { + "$ref": "#/components/schemas/ReportWithoutRunCreated" + } + for status_code in ("400", "500", "503"): + assert _response_schema(responses[status_code]) == { + "$ref": "#/components/schemas/EconomyError" + } + assert _response_schema(responses["422"]) == { + "$ref": "#/components/schemas/EconomyRequestUnprocessable" + } + # Nothing is called, so Modal never refuses a call of this route's. + assert "modal_call_refused" not in responses["503"]["description"] + assert "manifest" in responses["503"]["description"] + assert "cliffs_not_available" in responses["422"]["description"] + created = schemas["ReportWithoutRunCreated"] + assert set(created["properties"]) == { + "report_id", + "report_type", + "baseline_simulation_id", + "reform_simulation_id", + "years", + } + assert set(created["required"]) == { + "report_id", + "report_type", + "baseline_simulation_id", + "reform_simulation_id", + } + assert created["properties"]["report_type"]["enum"] == [ + "economy", + "budget_window", + "household", + ] + assert set(schemas["ReportWithoutRunYear"]["properties"]) == { + "year", + "baseline_simulation_id", + "reform_simulation_id", + } diff --git a/projects/policyengine-simulation-entry/tests/test_reports_without_run.py b/projects/policyengine-simulation-entry/tests/test_reports_without_run.py new file mode 100644 index 000000000..d97267b05 --- /dev/null +++ b/projects/policyengine-simulation-entry/tests/test_reports_without_run.py @@ -0,0 +1,502 @@ +"""Creating a report and its simulations by key without a run (D4 · 0). + +``POST /reports/without-run`` takes ``POST /reports``' body, reads the +version manifest and the catalog as ``POST /reports`` does, and finds or +creates the report and its simulations by the same key, starting nothing: +API v1's one-time migration creates its reports this way, and app v3 +starts a report's first run when someone opens it. The services' stores and +Modal calls are faked here; the stores' writes are tested against +PostgreSQL in the persistence library. +""" + +from __future__ import annotations + +import asyncio +from dataclasses import dataclass, field +from typing import Any, NoReturn +from uuid import UUID + +import pytest +from conftest import FakeBackend, make_settings +from economy_service_fakes import ( + CREATED_AT, + REPORT_BODY, + FakeCaller, + FakeWorkers, + numbered_ids, + report_request, +) +from fastapi.testclient import TestClient +from household_report_fakes import ( + HOUSEHOLD_REPORT_BODY, + FakeHouseholdReportCaller, + FakeHouseholdReportStore, + FakeHouseholdWorkers, + household_report_request, + household_report_service, +) +from policyengine_simulation_entry import app as app_module +from policyengine_simulation_entry.app import create_app +from policyengine_simulation_entry.budget_window_api_models import ( + BudgetWindowReportRequest, +) +from policyengine_simulation_entry.economy_api_models import EconomyReportRequest +from policyengine_simulation_entry.economy_submission_errors import ( + EconomySubmissionOutcomeUnknownError, + EconomySubmissionUnavailableError, + EconomySubmissionUnprocessableError, + UnprocessableReason, +) +from policyengine_simulation_entry.economy_submissions import ServiceSettings +from policyengine_simulation_entry.household_report_api_models import ( + HouseholdReportRequest, +) +from policyengine_simulation_entry.household_workers import ( + VersionManifestUnavailableError, +) +from policyengine_simulation_entry.report_without_run_api_models import ( + ReportWithoutRunCreated, + ReportWithoutRunYear, +) +from policyengine_simulation_entry.reports_without_run import ( + HouseholdReportWithoutRunService, + ReportWithoutRunService, +) +from policyengine_simulation_persistence import ( + FoundBudgetWindowWithoutRun, + FoundReportWithoutRun, + KeyedBudgetWindowWithoutRun, + KeyedEconomyReportWithoutRun, + KeyedHouseholdReportWithoutRun, +) +from test_budget_window_requests import WINDOW_BODY +from test_budget_window_submissions import FakeAdvancer, FakeWindowStore + +PATH = "/reports/without-run" +REPORT_ID = UUID("00000000-0000-4000-8000-0000000000a1") +BASELINE_SIMULATION_ID = UUID("00000000-0000-4000-8000-0000000000a2") +REFORM_SIMULATION_ID = UUID("00000000-0000-4000-8000-0000000000a3") +ECONOMY_ANSWER = ReportWithoutRunCreated( + report_id=REPORT_ID, + report_type="economy", + baseline_simulation_id=BASELINE_SIMULATION_ID, + reform_simulation_id=REFORM_SIMULATION_ID, +) +WINDOW_ANSWER = ReportWithoutRunCreated( + report_id=REPORT_ID, + report_type="budget_window", + baseline_simulation_id=BASELINE_SIMULATION_ID, + reform_simulation_id=REFORM_SIMULATION_ID, + years=[ + ReportWithoutRunYear( + year=2026, + baseline_simulation_id=BASELINE_SIMULATION_ID, + reform_simulation_id=REFORM_SIMULATION_ID, + ) + ], +) +HOUSEHOLD_ANSWER = ReportWithoutRunCreated( + report_id=REPORT_ID, + report_type="household", + baseline_simulation_id=BASELINE_SIMULATION_ID, + reform_simulation_id=None, +) + + +@dataclass +class FakeEconomyStoreWithoutRun(FakeWindowStore): + """Also finds or creates reports and windows by key without a run.""" + + reports_without_run: list[KeyedEconomyReportWithoutRun] = field( + default_factory=list + ) + windows_without_run: list[KeyedBudgetWindowWithoutRun] = field(default_factory=list) + + def find_or_create_report_without_run( + self, report: KeyedEconomyReportWithoutRun + ) -> FoundReportWithoutRun: + if self.create_failure is not None: + raise self.create_failure + self.reports_without_run.append(report) + return FoundReportWithoutRun( + report_id=report.report_id, + report_inserted=True, + baseline_simulation_id=report.baseline_simulation_id, + reform_simulation_id=report.reform_simulation_id, + ) + + def find_or_create_budget_window_without_run( + self, window: KeyedBudgetWindowWithoutRun + ) -> FoundBudgetWindowWithoutRun: + if self.create_failure is not None: + raise self.create_failure + self.windows_without_run.append(window) + return FoundBudgetWindowWithoutRun( + report_id=window.report_id, report_inserted=True, years=window.years + ) + + +@dataclass +class FakeHouseholdStoreWithoutRun(FakeHouseholdReportStore): + """Also finds or creates household reports by key without a run.""" + + reports_without_run: list[KeyedHouseholdReportWithoutRun] = field( + default_factory=list + ) + + def find_or_create_report_without_run( + self, report: KeyedHouseholdReportWithoutRun + ) -> FoundReportWithoutRun: + if self.create_failure is not None: + raise self.create_failure + self.reports_without_run.append(report) + return FoundReportWithoutRun( + report_id=report.report_id, + report_inserted=True, + baseline_simulation_id=report.baseline_simulation_id, + reform_simulation_id=report.reform_simulation_id, + ) + + +def _economy_service( + store: FakeEconomyStoreWithoutRun, + *, + workers: FakeWorkers | None = None, + caller: FakeCaller | None = None, + advancer: FakeAdvancer | None = None, +) -> ReportWithoutRunService: + return ReportWithoutRunService( + windows=advancer or FakeAdvancer(store), + store=store, + workers=workers or FakeWorkers(), + caller=caller or FakeCaller(), + settings=ServiceSettings(environment="staging", modal_environment="staging"), + call_start_timeout_seconds=0.05, + new_id=numbered_ids(), + clock=lambda: CREATED_AT, + ) + + +def _household_service( + store: FakeHouseholdStoreWithoutRun, + *, + caller: FakeHouseholdReportCaller | None = None, +) -> HouseholdReportWithoutRunService: + return HouseholdReportWithoutRunService( + store=store, + workers=FakeHouseholdWorkers(), + caller=caller or FakeHouseholdReportCaller(), + call_start_timeout_seconds=0.05, + new_id=numbered_ids(), + ) + + +def _window_request() -> BudgetWindowReportRequest: + return BudgetWindowReportRequest.model_validate(WINDOW_BODY) + + +def test_an_economy_report_without_a_run_is_keyed_as_a_create_with_one_is() -> None: + store = FakeEconomyStoreWithoutRun() + caller = FakeCaller() + store_with_run = FakeEconomyStoreWithoutRun() + + created = asyncio.run( + _economy_service(store, caller=caller).create_report_without_run( + report_request() + ) + ) + asyncio.run( + _economy_service(store_with_run).submit_report( + report_request(), request_id="request", observability_context=None + ) + ) + + (report,) = store.reports_without_run + (report_with_run,) = store_with_run.reports + expected = report_with_run.without_run + assert ( + report.definition, + report.tax_benefit_model_id, + report.population, + report.inputs, + ) == ( + expected.definition, + expected.tax_benefit_model_id, + expected.population, + expected.inputs, + ) + # The catalog is read for the manifest's default worker, as a create's is. + assert [request for request, _ in store.report_reads] == [ + request for request, _ in store_with_run.report_reads + ] + assert created == ReportWithoutRunCreated( + report_id=report.report_id, + report_type="economy", + baseline_simulation_id=report.baseline_simulation_id, + reform_simulation_id=report.reform_simulation_id, + ) + assert "years" not in created.model_dump(mode="json") + assert store.reports == [] + assert (caller.report_runs, caller.simulation_runs, caller.cliff_calculations) == ( + [], + [], + [], + ) + + +def test_a_report_without_a_run_asking_for_cliffs_is_refused_before_any_read() -> None: + store = FakeEconomyStoreWithoutRun() + workers = FakeWorkers(failure=AssertionError("the manifest was read")) + + with pytest.raises(EconomySubmissionUnprocessableError) as refused: + asyncio.run( + _economy_service(store, workers=workers).create_report_without_run( + report_request(include_cliffs=True) + ) + ) + + assert refused.value.code == "cliffs_not_available" + (reason,) = refused.value.reasons + assert reason.loc == ("body", "include_cliffs") + assert (store.report_reads, store.reports_without_run) == ([], []) + + +def test_a_report_without_a_run_needs_the_version_manifest() -> None: + store = FakeEconomyStoreWithoutRun() + workers = FakeWorkers(failure=VersionManifestUnavailableError("unreadable")) + + with pytest.raises(EconomySubmissionUnavailableError) as unavailable: + asyncio.run( + _economy_service(store, workers=workers).create_report_without_run( + report_request() + ) + ) + + assert unavailable.value.code == "manifest_unavailable" + assert (store.report_reads, store.reports_without_run) == ([], []) + + +def test_a_budget_window_without_a_run_answers_each_years_simulations() -> None: + store = FakeEconomyStoreWithoutRun() + caller = FakeCaller() + advancer = FakeAdvancer(store) + store_with_run = FakeEconomyStoreWithoutRun() + + created = asyncio.run( + _economy_service( + store, caller=caller, advancer=advancer + ).create_report_without_run(_window_request()) + ) + asyncio.run( + _economy_service(store_with_run).submit_budget_window( + _window_request(), request_id="request", observability_context=None + ) + ) + + (window,) = store.windows_without_run + (window_with_run,) = store_with_run.windows + assert window.definition == window_with_run.without_run.definition + assert [year.year for year in window.years] == list(_window_request().years) + first_year = window.years[0] + assert created == ReportWithoutRunCreated( + report_id=window.report_id, + report_type="budget_window", + baseline_simulation_id=first_year.baseline_simulation_id, + reform_simulation_id=first_year.reform_simulation_id, + years=[ + ReportWithoutRunYear( + year=year.year, + baseline_simulation_id=year.baseline_simulation_id, + reform_simulation_id=year.reform_simulation_id, + ) + for year in window.years + ], + ) + assert (store.windows, advancer.advances, caller.report_runs) == ([], [], []) + + +@pytest.mark.parametrize("sides", ["baseline_and_reform", "baseline_alone"]) +def test_a_household_report_without_a_run_is_keyed_as_a_create_with_one_is( + sides: str, +) -> None: + changes: dict[str, Any] = {} if sides == "baseline_and_reform" else {"reform": None} + store = FakeHouseholdStoreWithoutRun() + caller = FakeHouseholdReportCaller() + store_with_run = FakeHouseholdStoreWithoutRun() + + created = asyncio.run( + _household_service(store, caller=caller).create_report_without_run( + household_report_request(**changes) + ) + ) + asyncio.run( + household_report_service(store_with_run).submit_report( + household_report_request(**changes), observability_context=None + ) + ) + + (report,) = store.reports_without_run + (report_with_run,) = store_with_run.keyed_reports + assert report.definition == report_with_run.without_run.definition + assert (report.tax_benefit_model_id, report.tax_benefit_model_version_id) == ( + report_with_run.tax_benefit_model_id, + report_with_run.tax_benefit_model_version_id, + ) + assert created == ReportWithoutRunCreated( + report_id=report.report_id, + report_type="household", + baseline_simulation_id=report.baseline_simulation_id, + reform_simulation_id=report.reform_simulation_id, + ) + assert (created.reform_simulation_id is None) is (sides == "baseline_alone") + assert (store.keyed_reports, caller.calls) == ([], []) + + +def _raise(failure: Exception) -> NoReturn: + raise failure + + +@dataclass +class FakeReportsWithoutRun: + """Records each report created without a run, and answers as told.""" + + answer: ReportWithoutRunCreated + failure: Exception | None = None + requests: list[Any] = field(default_factory=list) + + async def create_report_without_run(self, request: Any) -> ReportWithoutRunCreated: + self.requests.append(request) + if self.failure is not None: + _raise(self.failure) + return self.answer + + +@pytest.fixture +def client_for(monkeypatch): + """Return a function building a client whose app uses these services. + + None leaves that service unconfigured. + """ + + def build( + economy: FakeReportsWithoutRun | None, + household: FakeReportsWithoutRun | None = None, + ) -> TestClient: + monkeypatch.setattr( + app_module, + "economy_submissions_for", + lambda settings, database, **_: economy, + ) + monkeypatch.setattr( + app_module, "household_reports_for", lambda settings, database: household + ) + return TestClient( + create_app( + settings=make_settings(), + backend=FakeBackend(), + auth_dependency=lambda: None, + ) + ) + + return build + + +@pytest.mark.parametrize( + ("body", "request_type", "answer"), + [ + (REPORT_BODY | {"include_cliffs": False}, EconomyReportRequest, ECONOMY_ANSWER), + (WINDOW_BODY, BudgetWindowReportRequest, WINDOW_ANSWER), + ], + ids=["economy", "budget_window"], +) +def test_a_report_without_a_run_answers_201_with_its_simulations( + client_for, + body: dict[str, Any], + request_type: type, + answer: ReportWithoutRunCreated, +) -> None: + economy = FakeReportsWithoutRun(answer=answer) + + with client_for(economy) as client: + result = client.post(PATH, json=body) + + assert result.status_code == 201 + assert result.json() == answer.model_dump(mode="json") + (request,) = economy.requests + assert isinstance(request, request_type) + + +def test_a_household_report_without_a_run_answers_201_with_its_simulations( + client_for, +) -> None: + household = FakeReportsWithoutRun(answer=HOUSEHOLD_ANSWER) + + with client_for(FakeReportsWithoutRun(answer=ECONOMY_ANSWER), household) as client: + result = client.post(PATH, json=HOUSEHOLD_REPORT_BODY) + + assert result.status_code == 201 + assert result.json() == HOUSEHOLD_ANSWER.model_dump(mode="json") + assert result.json()["reform_simulation_id"] is None + (request,) = household.requests + assert isinstance(request, HouseholdReportRequest) + + +@pytest.mark.parametrize( + "body", [REPORT_BODY, HOUSEHOLD_REPORT_BODY], ids=["economy", "household"] +) +def test_a_report_without_a_run_answers_503_when_not_configured( + client_for, body: dict[str, Any] +) -> None: + with client_for(None, None) as client: + result = client.post(PATH, json=body) + + assert result.status_code == 503 + assert result.json()["code"] == "not_configured" + assert result.headers["Retry-After"] + + +@pytest.mark.parametrize( + ("failure", "status_code", "code"), + [ + ( + EconomySubmissionUnprocessableError( + code="cliffs_not_available", + reasons=( + UnprocessableReason( + loc=("body", "include_cliffs"), + msg="A report without a run calculates no cliff impacts.", + type="cliffs_not_available", + ), + ), + ), + 422, + "cliffs_not_available", + ), + ( + EconomySubmissionUnavailableError( + code="manifest_unavailable", + detail="The v2 version manifest could not be read.", + ), + 503, + "manifest_unavailable", + ), + ( + EconomySubmissionOutcomeUnknownError( + "report", error_type="OperationalError" + ), + 500, + "internal_error", + ), + ], + ids=["cliffs", "manifest", "outcome_unknown"], +) +def test_a_report_without_a_run_answers_its_services_refusals( + client_for, failure: Exception, status_code: int, code: str +) -> None: + economy = FakeReportsWithoutRun(answer=ECONOMY_ANSWER, failure=failure) + + with client_for(economy) as client: + result = client.post(PATH, json=REPORT_BODY) + + assert result.status_code == status_code + assert result.json()["code"] == code From 519f3bb201e649b52d915d20680bbb854d733366 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 05:10:09 +0400 Subject: [PATCH 2/8] Add failing generated-client tests for a report without a run API v1's migration sends POST /reports/without-run through the generated policyengine-api-simulation-client. These hermetic tests check the client sends POST /reports' bodies to the new route and reads its answer and errors. A client generated before the route has no create_report_without_run, so they fail on its import. Co-Authored-By: Claude Opus 5.5 --- ...est_report_without_run_generated_client.py | 188 ++++++++++++++++++ 1 file changed, 188 insertions(+) create mode 100644 projects/policyengine-apis-integ/tests/test_report_without_run_generated_client.py diff --git a/projects/policyengine-apis-integ/tests/test_report_without_run_generated_client.py b/projects/policyengine-apis-integ/tests/test_report_without_run_generated_client.py new file mode 100644 index 000000000..d99a46aa6 --- /dev/null +++ b/projects/policyengine-apis-integ/tests/test_report_without_run_generated_client.py @@ -0,0 +1,188 @@ +"""Hermetic wire checks of a report created without a run (D4 · 0). + +API v1's one-time migration sends each saved report's request to +``POST /reports/without-run`` through the generated client, with +``POST /reports``' own body, and reads the 201 naming the report and its +simulations (a budget window's: every year's), or the error answers +``POST /reports`` shares. +""" + +import httpx +import pytest +from policyengine_api_simulation_client import AuthenticatedClient +from policyengine_api_simulation_client.api.default import create_report_without_run +from policyengine_api_simulation_client.models import ( + BudgetWindowReportRequest, + EconomyError, + EconomyReportRequest, + EconomyRequestUnprocessable, + HouseholdReportRequest, + ReportWithoutRunCreated, +) + +REPORT_ID = "00000000-0000-4000-8000-0000000000e1" +SIDE_IDS = [f"00000000-0000-4000-8000-0000000000f{digit}" for digit in "1234"] +POLICY_ID = "00000000-0000-4000-8000-0000000000c5" +HOUSEHOLD_ID = "00000000-0000-4000-8000-0000000000bb" +# The bodies API v1 sends, as it sends them to POST /reports. +ECONOMY_BODY = { + "country": "us", + "report_type": "economy", + "label": "A larger child tax credit", + "description": None, + "year": 2026, + "region_code": "us", + "baseline": {"policy_id": None, "dynamic_id": None}, + "reform": {"policy_id": POLICY_ID, "dynamic_id": None}, + "include_cliffs": False, +} +WINDOW_BODY = { + "country": "us", + "report_type": "budget_window", + "label": "A two-year budget window", + "description": None, + "year": 2026, + "budget_window_size": 2, + "region_code": "us", + "baseline": {"policy_id": None, "dynamic_id": None}, + "reform": {"policy_id": POLICY_ID, "dynamic_id": None}, +} +HOUSEHOLD_BODY = { + "country": "us", + "report_type": "household", + "label": "One family's credit", + "description": None, + "household_id": HOUSEHOLD_ID, + "baseline": {"policy_id": None, "dynamic_id": None}, + "reform": None, +} +CREATED_ECONOMY_REPORT = { + "report_id": REPORT_ID, + "report_type": "economy", + "baseline_simulation_id": SIDE_IDS[0], + "reform_simulation_id": SIDE_IDS[1], +} +CREATED_WINDOW = { + "report_id": REPORT_ID, + "report_type": "budget_window", + "baseline_simulation_id": SIDE_IDS[0], + "reform_simulation_id": SIDE_IDS[1], + "years": [ + { + "year": 2026, + "baseline_simulation_id": SIDE_IDS[0], + "reform_simulation_id": SIDE_IDS[1], + }, + { + "year": 2027, + "baseline_simulation_id": SIDE_IDS[2], + "reform_simulation_id": SIDE_IDS[3], + }, + ], +} +CREATED_HOUSEHOLD_REPORT = { + "report_id": REPORT_ID, + "report_type": "household", + "baseline_simulation_id": SIDE_IDS[0], + "reform_simulation_id": None, +} +REQUEST_MODELS = { + "economy": EconomyReportRequest, + "budget_window": BudgetWindowReportRequest, + "household": HouseholdReportRequest, +} + + +def _create(status_code: int, answer: dict, body: dict = ECONOMY_BODY): + """Send ``body`` through the client; return the response and what was sent.""" + sent: list[httpx.Request] = [] + + def respond(http_request: httpx.Request) -> httpx.Response: + sent.append(http_request) + return httpx.Response(status_code, json=answer) + + client = AuthenticatedClient(base_url="https://simulation.example", token="test") + client.set_httpx_client( + httpx.Client( + base_url="https://simulation.example", + transport=httpx.MockTransport(respond), + ) + ) + request_model = REQUEST_MODELS[body["report_type"]] + response = create_report_without_run.sync_detailed( + client=client, body=request_model.from_dict(body) + ) + return response, sent + + +@pytest.mark.parametrize( + "body", [ECONOMY_BODY, WINDOW_BODY, HOUSEHOLD_BODY], ids=REQUEST_MODELS +) +def test_a_report_without_a_run_is_sent_to_its_route_as_given(body): + _, sent = _create(201, CREATED_ECONOMY_REPORT, body) + + (http_request,) = sent + assert (http_request.method, http_request.url.path) == ( + "POST", + "/reports/without-run", + ) + assert httpx.Response(200, content=http_request.content).json() == body + + +def test_a_created_report_is_read_with_its_simulations_and_no_years(): + response, _ = _create(201, CREATED_ECONOMY_REPORT) + + assert isinstance(response.parsed, ReportWithoutRunCreated) + assert str(response.parsed.report_id) == REPORT_ID + assert response.parsed.to_dict() == CREATED_ECONOMY_REPORT + + +def test_a_created_budget_window_is_read_with_each_years_simulations(): + response, _ = _create(201, CREATED_WINDOW, WINDOW_BODY) + + assert isinstance(response.parsed, ReportWithoutRunCreated) + assert [year.year for year in response.parsed.years] == [2026, 2027] + assert response.parsed.to_dict() == CREATED_WINDOW + + +def test_a_created_household_report_of_the_baseline_alone_has_no_reform(): + response, _ = _create(201, CREATED_HOUSEHOLD_REPORT, HOUSEHOLD_BODY) + + assert isinstance(response.parsed, ReportWithoutRunCreated) + assert response.parsed.reform_simulation_id is None + assert response.parsed.to_dict() == CREATED_HOUSEHOLD_REPORT + + +@pytest.mark.parametrize( + ("status_code", "answer", "model"), + [ + (400, {"code": "unknown_region", "detail": "No region."}, EconomyError), + ( + 422, + { + "detail": [ + { + "loc": ["body", "include_cliffs"], + "msg": "No cliffs without a run.", + "type": "cliffs_not_available", + } + ], + "code": "cliffs_not_available", + }, + EconomyRequestUnprocessable, + ), + ( + 503, + {"code": "manifest_unavailable", "detail": "No manifest."}, + EconomyError, + ), + ], + ids=["refused", "cliffs", "unavailable"], +) +def test_a_refused_report_without_a_run_is_read_with_its_code( + status_code, answer, model +): + response, _ = _create(status_code, answer) + + assert isinstance(response.parsed, model) + assert response.parsed.to_dict()["code"] == answer["code"] From 3046dc6a1a9b5bcc106baf603b628686726eb1a3 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 05:11:34 +0400 Subject: [PATCH 3/8] Find or create a report and its simulations by key without a run MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit POST /reports/without-run takes POST /reports' body and reads the version manifest and the catalog as POST /reports does, then finds or creates the report and its simulations (a budget window's: every year's) by the same keys, creating no run and starting no Modal call. API v1's one-time migration (D4 · 1) creates its reports this way; app v3 starts a report's first run when someone opens it. - The persistence library's find-or-create of each report kind is split into the report part, now a create of its own, and the run part. - The submission services share a step that reads and checks a request before anything is written. - A keyed budget window with no window run has each year's simulations found by key when it is re-run, so POST /reports/{report_id}/runs gives it its first window run instead of answering 409. Fixes #1166 Co-Authored-By: Claude Opus 5.5 --- changelog.d/1166.added.md | 1 + .../__init__.py | 18 ++ .../economy_run_store.py | 31 ++ .../household_report_store.py | 17 ++ .../keyed_economy_records.py | 183 +++++++++--- .../keyed_household_records.py | 107 ++++++- .../keyed_window_records.py | 270 +++++++++++++----- .../rerun_definitions.py | 120 +++++++- ...est_report_without_run_generated_client.py | 7 +- .../src/policyengine_simulation_entry/app.py | 14 +- .../budget_window_submissions.py | 101 ++++--- .../economy_requests.py | 33 +++ .../economy_rerun_routes.py | 12 +- .../economy_reruns.py | 10 +- .../economy_submissions.py | 88 +++--- .../household_report_reruns.py | 10 +- .../household_report_submissions.py | 64 +++-- .../report_without_run_api_models.py | 50 ++++ .../report_without_run_routes.py | 192 +++++++++++++ .../reports_without_run.py | 194 +++++++++++++ .../rerunnable_records.py | 4 +- 21 files changed, 1283 insertions(+), 243 deletions(-) create mode 100644 changelog.d/1166.added.md create mode 100644 projects/policyengine-simulation-entry/src/policyengine_simulation_entry/report_without_run_api_models.py create mode 100644 projects/policyengine-simulation-entry/src/policyengine_simulation_entry/report_without_run_routes.py create mode 100644 projects/policyengine-simulation-entry/src/policyengine_simulation_entry/reports_without_run.py diff --git a/changelog.d/1166.added.md b/changelog.d/1166.added.md new file mode 100644 index 000000000..dbe627d45 --- /dev/null +++ b/changelog.d/1166.added.md @@ -0,0 +1 @@ +Added `POST /reports/without-run`, which finds or creates an economy, budget-window or household report and its simulations by the keys `POST /reports` uses, without creating a run or starting a calculation, for API v1's one-time migration of saved reports. `POST /reports/{report_id}/runs` now gives a budget window created this way its first window run, finding each year's simulations by key. 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 fea15cdbc..cefbde6cd 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/__init__.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/__init__.py @@ -137,25 +137,34 @@ from policyengine_simulation_persistence.keyed_economy_records import ( FoundEconomyReport, FoundEconomySimulation, + FoundReportWithoutRun, FoundSide, KeyedEconomyReport, + KeyedEconomyReportWithoutRun, KeyedEconomySimulation, ProposedSide, find_or_create_economy_report, + find_or_create_economy_report_without_run, find_or_create_economy_simulation, find_or_insert_report_run_cliffs, ) from policyengine_simulation_persistence.keyed_household_records import ( FoundHouseholdReport, KeyedHouseholdReport, + KeyedHouseholdReportWithoutRun, find_or_create_household_report, + find_or_create_household_report_without_run, ) from policyengine_simulation_persistence.keyed_window_records import ( FoundBudgetWindow, + FoundBudgetWindowWithoutRun, FoundWindowYear, KeyedBudgetWindow, + KeyedBudgetWindowWithoutRun, KeyedWindowYear, + WindowYearSimulations, find_or_create_budget_window, + find_or_create_budget_window_without_run, ) from policyengine_simulation_persistence.orm_base import ( InputBase, @@ -265,6 +274,7 @@ "EconomySimulationInputs", "EconomySimulationState", "FoundBudgetWindow", + "FoundBudgetWindowWithoutRun", "FoundCliffCalculation", "FoundCliffs", "FoundEconomyReport", @@ -272,6 +282,7 @@ "FoundHouseholdReport", "FoundReportRerun", "FoundReportRun", + "FoundReportWithoutRun", "FoundRow", "FoundSide", "FoundSimulationRun", @@ -293,9 +304,12 @@ "InputBase", "IntraDecileImpact", "KeyedBudgetWindow", + "KeyedBudgetWindowWithoutRun", "KeyedEconomyReport", + "KeyedEconomyReportWithoutRun", "KeyedEconomySimulation", "KeyedHouseholdReport", + "KeyedHouseholdReportWithoutRun", "KeyedWindowYear", "LaborSupplyDecileResponse", "LaborSupplyResponse", @@ -357,6 +371,7 @@ "WindowSide", "WindowYearDefinition", "WindowYearRuns", + "WindowYearSimulations", "WithheldAreaCode", "bounded_session", "canonical_json", @@ -372,9 +387,12 @@ "fail_unstarted_simulation_run", "find_joinable_report_run", "find_or_create_budget_window", + "find_or_create_budget_window_without_run", "find_or_create_economy_report", + "find_or_create_economy_report_without_run", "find_or_create_economy_simulation", "find_or_create_household_report", + "find_or_create_household_report_without_run", "find_or_insert_cliff_calculations", "find_or_insert_report", "find_or_insert_report_run", 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 7afa261e6..da7eb8a9a 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 @@ -56,10 +56,12 @@ ) from policyengine_simulation_persistence.keyed_economy_records import ( find_or_create_economy_report, + find_or_create_economy_report_without_run, find_or_create_economy_simulation, ) from policyengine_simulation_persistence.keyed_window_records import ( find_or_create_budget_window, + find_or_create_budget_window_without_run, ) from policyengine_simulation_persistence.store_transactions import ( EconomyRecordOutcomeUnknownError, @@ -90,12 +92,16 @@ from policyengine_simulation_persistence.keyed_economy_records import ( FoundEconomyReport, FoundEconomySimulation, + FoundReportWithoutRun, KeyedEconomyReport, + KeyedEconomyReportWithoutRun, KeyedEconomySimulation, ) from policyengine_simulation_persistence.keyed_window_records import ( FoundBudgetWindow, + FoundBudgetWindowWithoutRun, KeyedBudgetWindow, + KeyedBudgetWindowWithoutRun, ) from policyengine_simulation_persistence.shared_rows import ( FoundReportRun, @@ -304,6 +310,31 @@ def find_or_create_budget_window( lambda session: find_or_create_budget_window(session, window) ) + def find_or_create_report_without_run( + self, report: KeyedEconomyReportWithoutRun + ) -> FoundReportWithoutRun: + """Find the report and its simulations by key, or create them, with no run. + + See ``find_or_create_economy_report_without_run``; raise as + ``find_or_create_report`` does. + """ + return self._create( + lambda session: find_or_create_economy_report_without_run(session, report) + ) + + def find_or_create_budget_window_without_run( + self, window: KeyedBudgetWindowWithoutRun + ) -> FoundBudgetWindowWithoutRun: + """Find a window and each year's simulations by key, or create them. + + It creates no window run. See + ``find_or_create_budget_window_without_run``; raise as + ``find_or_create_report`` does. + """ + return self._create( + lambda session: find_or_create_budget_window_without_run(session, window) + ) + def find_or_create_simulation( self, simulation: KeyedEconomySimulation ) -> FoundEconomySimulation: 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 228924ab1..f97a80874 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 @@ -37,6 +37,7 @@ ) from policyengine_simulation_persistence.keyed_household_records import ( find_or_create_household_report, + find_or_create_household_report_without_run, ) from policyengine_simulation_persistence.policy_reform import read_simulation_reform from policyengine_simulation_persistence.store_transactions import ( @@ -61,9 +62,13 @@ from policyengine_simulation_persistence.household_job_records import ( StoredHousehold, ) + from policyengine_simulation_persistence.keyed_economy_records import ( + FoundReportWithoutRun, + ) from policyengine_simulation_persistence.keyed_household_records import ( FoundHouseholdReport, KeyedHouseholdReport, + KeyedHouseholdReportWithoutRun, ) from policyengine_simulation_persistence.policy_reform import SimulationReform from policyengine_simulation_persistence.shared_rows import FoundReportRun @@ -193,6 +198,18 @@ def find_or_create_report( lambda session: find_or_create_household_report(session, report) ) + def find_or_create_report_without_run( + self, report: KeyedHouseholdReportWithoutRun + ) -> FoundReportWithoutRun: + """Find the report and its simulations by key, or create them, with no run. + + See ``find_or_create_household_report_without_run``; raise as + ``find_or_create_report`` does. + """ + return self._create( + lambda session: find_or_create_household_report_without_run(session, report) + ) + def create_report_rerun(self, rerun: NewHouseholdReportRerun) -> FoundReportRun: """Join a stored report's run on the re-run's versions, or create it. diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_economy_records.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_economy_records.py index 852537101..59a976049 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_economy_records.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_economy_records.py @@ -28,6 +28,11 @@ simulation is found or created by its key, with its run, the same way. Rows keep random IDs (answer 1c): the IDs a request proposes are used only for the rows it inserts. + +Steps 1 and 2 are also a create of their own, with no run +(``find_or_create_economy_report_without_run``): API v1's one-time +migration creates its reports this way (D4 · 0), and a report's first run +is created later, by a create with a run or a re-run, on the same rows. """ from __future__ import annotations @@ -73,6 +78,7 @@ ) from policyengine_simulation_persistence.shared_rows import ( FoundCliffs, + FoundRow, ProposedCliffs, ) @@ -89,6 +95,38 @@ class ProposedSide: simulation_run_id: UUID +@dataclass(frozen=True) +class KeyedEconomyReportWithoutRun: + """An economy report and its sides' simulations, found by key or created. + + It is a create with no run (D4 · 0). Each side's simulation ID is the + one its simulation gets if this request inserts it; ``population`` and + ``inputs`` are as ``KeyedEconomyReport`` describes them. + """ + + definition: EconomyReportDefinition + report_id: UUID + baseline_simulation_id: UUID + reform_simulation_id: UUID + tax_benefit_model_id: UUID + population: EconomyPopulation + inputs: dict[str, Any] + + +@dataclass(frozen=True) +class FoundReportWithoutRun: + """The report and its sides' simulations a create without a run ended on. + + ``reform_simulation_id`` is None only for a household report of the + baseline alone. + """ + + report_id: UUID + report_inserted: bool + baseline_simulation_id: UUID + reform_simulation_id: UUID | None + + @dataclass(frozen=True) class KeyedEconomyReport: """An economy report a request names, found by key or created with its run. @@ -112,6 +150,19 @@ class KeyedEconomyReport: inputs: dict[str, Any] cliffs: ProposedCliffs | None = None + @property + def without_run(self) -> KeyedEconomyReportWithoutRun: + """Return the report and its simulations this request names, with no run.""" + return KeyedEconomyReportWithoutRun( + definition=self.definition, + report_id=self.report_id, + baseline_simulation_id=self.baseline.simulation_id, + reform_simulation_id=self.reform.simulation_id, + tax_benefit_model_id=self.tax_benefit_model_id, + population=self.population, + inputs=self.inputs, + ) + @dataclass(frozen=True) class FoundSide: @@ -171,51 +222,94 @@ def find_or_create_economy_report( transaction, or its savepoint. """ with references_checked(): - simulation_ids = _find_or_insert_simulations(session, request) - report = find_or_insert_report( - session, - economy_report_row( - request.definition, - report_id=request.report_id, - tax_benefit_model_id=request.tax_benefit_model_id, - population=request.population, - inputs=request.inputs, - simulation_ids=simulation_ids, - ), + report, simulation_ids = _find_or_insert_report_rows( + session, request.without_run ) - versions = request.versions - joined = find_joinable_report_run( - session, - report_id=report.id, - country_package_version=versions.country_package_version, - policyengine_version=versions.policyengine_version, - ) - if joined is not None: - return _with_cliffs( - session, - _found(report.id, report.inserted, joined, simulation_ids, set()), - request.cliffs, - ) - proposed = {"baseline": request.baseline, "reform": request.reform} - run, runs = find_or_insert_report_run_on_sides( - session, - _report_run_row(request, report.id), - { - side: simulation_run_row( - run_id=proposed[side].simulation_run_id, - simulation_id=simulation_ids[side], - population=request.population, - versions=request.versions, - ) - for side in _SIDES - }, - ) - inserted = {found.id for found in runs.values() if found.inserted} + return _find_or_create_report_run(session, request, report, simulation_ids) + + +def _find_or_create_report_run( + session: Session, + request: KeyedEconomyReport, + report: FoundRow, + simulation_ids: dict[Side, UUID], +) -> FoundEconomyReport: + """Join the report's run on the request's versions, or create it on its sides. + + Steps 3 to 5 of a create (the module's), after its report and + simulations were found or inserted. + """ + versions = request.versions + joined = find_joinable_report_run( + session, + report_id=report.id, + country_package_version=versions.country_package_version, + policyengine_version=versions.policyengine_version, + ) + if joined is not None: return _with_cliffs( session, - _found(report.id, report.inserted, run, simulation_ids, inserted), + _found(report.id, report.inserted, joined, simulation_ids, set()), request.cliffs, ) + proposed = {"baseline": request.baseline, "reform": request.reform} + run, runs = find_or_insert_report_run_on_sides( + session, + _report_run_row(request, report.id), + { + side: simulation_run_row( + run_id=proposed[side].simulation_run_id, + simulation_id=simulation_ids[side], + population=request.population, + versions=request.versions, + ) + for side in _SIDES + }, + ) + inserted = {found.id for found in runs.values() if found.inserted} + return _with_cliffs( + session, + _found(report.id, report.inserted, run, simulation_ids, inserted), + request.cliffs, + ) + + +def find_or_create_economy_report_without_run( + session: Session, request: KeyedEconomyReportWithoutRun +) -> FoundReportWithoutRun: + """Find the report the request names, and its sides' simulations, or create them. + + Steps 1 and 2 of a create (the module's), with no run: a report found + keeps whatever runs it has, and a report created has none. Raise as + ``find_or_create_economy_report`` does. + """ + with references_checked(): + report, simulation_ids = _find_or_insert_report_rows(session, request) + return FoundReportWithoutRun( + report_id=report.id, + report_inserted=report.inserted, + baseline_simulation_id=simulation_ids["baseline"], + reform_simulation_id=simulation_ids["reform"], + ) + + +def _find_or_insert_report_rows( + session: Session, request: KeyedEconomyReportWithoutRun +) -> tuple[FoundRow, dict[Side, UUID]]: + """Return the report and each side's simulation, found by key or inserted.""" + simulation_ids = _find_or_insert_simulations(session, request) + report = find_or_insert_report( + session, + economy_report_row( + request.definition, + report_id=request.report_id, + tax_benefit_model_id=request.tax_benefit_model_id, + population=request.population, + inputs=request.inputs, + simulation_ids=simulation_ids, + ), + ) + return report, simulation_ids def _with_cliffs( @@ -283,10 +377,13 @@ def find_or_create_economy_simulation( def _find_or_insert_simulations( - session: Session, request: KeyedEconomyReport + session: Session, request: KeyedEconomyReportWithoutRun ) -> dict[Side, UUID]: """Return each side's simulation ID, found by key or inserted, in key order.""" - proposed = {"baseline": request.baseline, "reform": request.reform} + proposed = { + "baseline": request.baseline_simulation_id, + "reform": request.reform_simulation_id, + } by_key: dict[str, list[Side]] = {} for side in _SIDES: key = request.definition.simulation(side).definition_key @@ -298,7 +395,7 @@ def _find_or_insert_simulations( session, economy_simulation_row( request.definition.simulation(sides[0]), - proposed[sides[0]].simulation_id, + proposed[sides[0]], request.population, ), ) diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_household_records.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_household_records.py index 8975a8866..673b9101f 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_household_records.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_household_records.py @@ -24,6 +24,10 @@ (C1 · 26). A report of the baseline alone has no reform side. Rows keep random IDs: the IDs a request proposes are used only for the rows it inserts. + +Steps 1 and 2 are also a create of their own, with no run +(``find_or_create_household_report_without_run``, D4 · 0), as an economy +report's are. """ from __future__ import annotations @@ -40,6 +44,7 @@ household_simulation_run_row, ) from policyengine_simulation_persistence.keyed_economy_records import ( + FoundReportWithoutRun, FoundSide, ProposedSide, Side, @@ -65,6 +70,47 @@ HouseholdReportDefinition, ) from policyengine_simulation_persistence.economy_run_records import RunVersions + from policyengine_simulation_persistence.shared_rows import FoundRow + + +def _check_reform_side( + definition: HouseholdReportDefinition, reform_proposed: object +) -> None: + """Refuse a reform side for a report without a reform, or none for one.""" + if (reform_proposed is None) != (definition.reform is None): + msg = "a household report proposes a reform side exactly when it has one" + raise ValueError(msg) + + +@dataclass(frozen=True) +class KeyedHouseholdReportWithoutRun: + """A household report and its sides' simulations, found by key or created. + + It is a create with no run (D4 · 0). Each side's simulation ID is the + one its simulation gets if this request inserts it; + ``reform_simulation_id`` is None exactly when the definition has no + reform. The simulations name the catalog version + ``tax_benefit_model_version_id``. + """ + + definition: HouseholdReportDefinition + report_id: UUID + baseline_simulation_id: UUID + reform_simulation_id: UUID | None + tax_benefit_model_id: UUID + tax_benefit_model_version_id: UUID + + def __post_init__(self) -> None: + """Refuse a reform side for a report without a reform, or none for one.""" + _check_reform_side(self.definition, self.reform_simulation_id) + + @property + def proposed_simulation_ids(self) -> dict[Side, UUID]: + """Return each side the report calculates and the simulation ID it proposes.""" + sides: dict[Side, UUID] = {"baseline": self.baseline_simulation_id} + if self.reform_simulation_id is not None: + sides["reform"] = self.reform_simulation_id + return sides @dataclass(frozen=True) @@ -87,9 +133,21 @@ class KeyedHouseholdReport: def __post_init__(self) -> None: """Refuse a reform side for a report without a reform, or none for one.""" - if (self.reform is None) != (self.definition.reform is None): - msg = "a household report proposes a reform side exactly when it has one" - raise ValueError(msg) + _check_reform_side(self.definition, self.reform) + + @property + def without_run(self) -> KeyedHouseholdReportWithoutRun: + """Return the report and its simulations this request names, with no run.""" + return KeyedHouseholdReportWithoutRun( + definition=self.definition, + report_id=self.report_id, + baseline_simulation_id=self.baseline.simulation_id, + reform_simulation_id=None + if self.reform is None + else self.reform.simulation_id, + tax_benefit_model_id=self.tax_benefit_model_id, + tax_benefit_model_version_id=self.tax_benefit_model_version_id, + ) @property def proposed_sides(self) -> dict[Side, ProposedSide]: @@ -125,8 +183,9 @@ def find_or_create_household_report( transaction, or its savepoint. """ with references_checked(): - simulation_ids = _find_or_insert_simulations(session, request) - report = find_or_insert_report(session, _report_row(request, simulation_ids)) + report, simulation_ids = _find_or_insert_report_rows( + session, request.without_run + ) versions = request.versions joined = find_joinable_report_run( session, @@ -154,12 +213,40 @@ def find_or_create_household_report( return _found(report.id, report.inserted, run, simulation_ids, inserted) +def find_or_create_household_report_without_run( + session: Session, request: KeyedHouseholdReportWithoutRun +) -> FoundReportWithoutRun: + """Find the household report the request names, and its simulations, or create them. + + Steps 1 and 2 of a create (the module's), with no run: a report found + keeps whatever runs it has, and a report created has none. Raise as + ``find_or_create_household_report`` does. + """ + with references_checked(): + report, simulation_ids = _find_or_insert_report_rows(session, request) + return FoundReportWithoutRun( + report_id=report.id, + report_inserted=report.inserted, + baseline_simulation_id=simulation_ids["baseline"], + reform_simulation_id=simulation_ids.get("reform"), + ) + + +def _find_or_insert_report_rows( + session: Session, request: KeyedHouseholdReportWithoutRun +) -> tuple[FoundRow, dict[Side, UUID]]: + """Return the report and each side's simulation, found by key or inserted.""" + simulation_ids = _find_or_insert_simulations(session, request) + report = find_or_insert_report(session, _report_row(request, simulation_ids)) + return report, simulation_ids + + def _find_or_insert_simulations( - session: Session, request: KeyedHouseholdReport + session: Session, request: KeyedHouseholdReportWithoutRun ) -> dict[Side, UUID]: """Return each side's simulation ID, found by key or inserted, in key order.""" definition = request.definition - proposed = request.proposed_sides + proposed = request.proposed_simulation_ids by_key: dict[str, list[Side]] = {} for side in proposed: by_key.setdefault(definition.simulation(side).definition_key, []).append(side) @@ -168,7 +255,7 @@ def _find_or_insert_simulations( sides = by_key[key] found = find_or_insert_simulation( session, - _simulation_row(request, sides[0], proposed[sides[0]].simulation_id), + _simulation_row(request, sides[0], proposed[sides[0]]), ) for side in sides: simulation_ids[side] = found.id @@ -176,7 +263,7 @@ def _find_or_insert_simulations( def _simulation_row( - request: KeyedHouseholdReport, side: Side, simulation_id: UUID + request: KeyedHouseholdReportWithoutRun, side: Side, simulation_id: UUID ) -> dict[str, Any]: """Return a side's keyed household simulation as inserted.""" simulation = request.definition.simulation(side) @@ -196,7 +283,7 @@ def _simulation_row( def _report_row( - request: KeyedHouseholdReport, simulation_ids: dict[Side, UUID] + request: KeyedHouseholdReportWithoutRun, simulation_ids: dict[Side, UUID] ) -> dict[str, Any]: """Return a keyed household report as inserted, naming its sides' simulations.""" definition = request.definition diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_window_records.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_window_records.py index 6368f0ab3..47ad870db 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_window_records.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_window_records.py @@ -25,6 +25,11 @@ A year's simulation run may be a single-year report's, or another window's, pending, running or succeeded (answers 4 and 5). Rows keep random IDs: the IDs a request proposes are used only for the rows it inserts. + +Steps 1 and 2 are also a create of their own, with no window run +(``find_or_create_budget_window_without_run``, D4 · 0): a re-run gives +such a window its first window run, finding each year's simulations by +key (``rerun_definitions``). """ from __future__ import annotations @@ -75,6 +80,7 @@ EconomyPopulation, RunVersions, ) + from policyengine_simulation_persistence.shared_rows import FoundRow # A window year's side: its year and the side's name. type YearSide = tuple[int, Side] @@ -104,6 +110,72 @@ class KeyedWindowYear: reform: ProposedSide +@dataclass(frozen=True) +class WindowYearSimulations: + """A window year's sides' simulations: the IDs proposed, or those found.""" + + year: int + baseline_simulation_id: UUID + reform_simulation_id: UUID + + @property + def simulation_ids(self) -> dict[Side, UUID]: + """Return each side's simulation, the baseline's first.""" + return { + "baseline": self.baseline_simulation_id, + "reform": self.reform_simulation_id, + } + + +def _check_window( + definition: EconomyReportDefinition, population: EconomyPopulation, years: list[int] +) -> None: + """Refuse years that aren't the definition's, 1 to 75 from its first.""" + check_window_years(population.year, years) + if (definition.year, definition.budget_window_size) != ( + population.year, + len(years), + ): + msg = "a window's definition names its first year and its length" + raise ValueError(msg) + + +@dataclass(frozen=True) +class KeyedBudgetWindowWithoutRun: + """A budget window and each year's simulations, found by key or created. + + It is a create with no window run (D4 · 0). ``years`` proposes each + year's simulations' IDs, from the first year, one at a time; the other + fields are as ``KeyedBudgetWindow`` describes them. + """ + + definition: EconomyReportDefinition + report_id: UUID + tax_benefit_model_id: UUID + population: EconomyPopulation + inputs: dict[str, Any] + years: tuple[WindowYearSimulations, ...] + + def __post_init__(self) -> None: + """Refuse years that aren't the definition's, 1 to 75 from its first.""" + _check_window( + self.definition, self.population, [year.year for year in self.years] + ) + + def population_in(self, year: int) -> EconomyPopulation: + """Return what the window's simulations of ``year`` calculate on.""" + return replace(self.population, year=year) + + +@dataclass(frozen=True) +class FoundBudgetWindowWithoutRun: + """The window report and each year's simulations a create without a run ended on.""" + + report_id: UUID + report_inserted: bool + years: tuple[WindowYearSimulations, ...] + + @dataclass(frozen=True) class KeyedBudgetWindow: """A budget window a request names, found by key or created with its run. @@ -127,17 +199,28 @@ class KeyedBudgetWindow: def __post_init__(self) -> None: """Refuse years that aren't the definition's, 1 to 75 from its first.""" - check_window_years(self.population.year, [year.year for year in self.years]) - if (self.definition.year, self.definition.budget_window_size) != ( - self.population.year, - len(self.years), - ): - msg = "a window's definition names its first year and its length" - raise ValueError(msg) + _check_window( + self.definition, self.population, [year.year for year in self.years] + ) - def population_in(self, year: int) -> EconomyPopulation: - """Return what the window's simulations of ``year`` calculate on.""" - return replace(self.population, year=year) + @property + def without_run(self) -> KeyedBudgetWindowWithoutRun: + """Return the window and each year's simulations it names, with no run.""" + return KeyedBudgetWindowWithoutRun( + definition=self.definition, + report_id=self.report_id, + tax_benefit_model_id=self.tax_benefit_model_id, + population=self.population, + inputs=self.inputs, + years=tuple( + WindowYearSimulations( + year=window_year.year, + baseline_simulation_id=window_year.baseline.simulation_id, + reform_simulation_id=window_year.reform.simulation_id, + ) + for window_year in self.years + ), + ) @dataclass(frozen=True) @@ -175,65 +258,116 @@ def find_or_create_budget_window( transaction, or its savepoint. """ with references_checked(): - simulation_ids = _find_or_insert_simulations(session, request) - first_year = request.years[0].year - report = find_or_insert_report( + report, simulation_ids = _find_or_insert_window_rows( + session, request.without_run + ) + return _find_or_create_window_run(session, request, report, simulation_ids) + + +def _find_or_create_window_run( + session: Session, + request: KeyedBudgetWindow, + report: FoundRow, + simulation_ids: dict[YearSide, UUID], +) -> FoundBudgetWindow: + """Join the window's run on the request's versions, or create it with its years. + + Steps 3 and 4 of a create (the module's), after its report and each + year's simulations were found or inserted. + """ + versions = request.versions + joined = find_joinable_window_run( + session, + report_id=report.id, + tax_benefit_model_version_id=request.population.tax_benefit_model_version_id, + policyengine_version=versions.policyengine_version, + ) + if joined is None: + # The window run first: a request inserting one another request + # has inserted waits for it, then joins it with its year runs. + window_run = find_or_insert_window_run( session, - economy_report_row( - request.definition, - report_id=request.report_id, - tax_benefit_model_id=request.tax_benefit_model_id, + window_run_row( + run_id=request.window_run_id, + report_id=report.id, population=request.population, - inputs=request.inputs, - simulation_ids={ - side: simulation_ids[first_year, side] - for side in ("baseline", "reform") - }, + versions=versions, + recalculate=False, ), ) - versions = request.versions - joined = find_joinable_window_run( - session, - report_id=report.id, - tax_benefit_model_version_id=request.population.tax_benefit_model_version_id, - policyengine_version=versions.policyengine_version, - ) - if joined is None: - # The window run first: a request inserting one another request - # has inserted waits for it, then joins it with its year runs. - window_run = find_or_insert_window_run( + if window_run.inserted: + years = insert_window_years( session, - window_run_row( - run_id=request.window_run_id, - report_id=report.id, - population=request.population, - versions=versions, - recalculate=False, - ), + _years_to_insert(request, simulation_ids), + report_id=report.id, + window_run_id=request.window_run_id, + population=request.population, + versions=versions, + forced=False, ) - if window_run.inserted: - years = insert_window_years( - session, - _years_to_insert(request, simulation_ids), - report_id=report.id, - window_run_id=request.window_run_id, - population=request.population, - versions=versions, - forced=False, - ) - return FoundBudgetWindow( - report_id=report.id, - report_inserted=report.inserted, - window_run=window_run, - years=years, - ) - joined = window_run - return FoundBudgetWindow( - report_id=report.id, - report_inserted=report.inserted, - window_run=joined, - years=stored_window_years(session, joined.id, simulation_ids), - ) + return FoundBudgetWindow( + report_id=report.id, + report_inserted=report.inserted, + window_run=window_run, + years=years, + ) + joined = window_run + return FoundBudgetWindow( + report_id=report.id, + report_inserted=report.inserted, + window_run=joined, + years=stored_window_years(session, joined.id, simulation_ids), + ) + + +def find_or_create_budget_window_without_run( + session: Session, request: KeyedBudgetWindowWithoutRun +) -> FoundBudgetWindowWithoutRun: + """Find the window the request names, and each year's simulations, or create them. + + Steps 1 and 2 of a create (the module's), with no window run: a window + found keeps whatever runs it has, and a window created has none. Raise + as ``find_or_create_budget_window`` does. + """ + with references_checked(): + report, simulation_ids = _find_or_insert_window_rows(session, request) + return FoundBudgetWindowWithoutRun( + report_id=report.id, + report_inserted=report.inserted, + years=tuple( + WindowYearSimulations( + year=window_year.year, + baseline_simulation_id=simulation_ids[window_year.year, "baseline"], + reform_simulation_id=simulation_ids[window_year.year, "reform"], + ) + for window_year in request.years + ), + ) + + +def _find_or_insert_window_rows( + session: Session, request: KeyedBudgetWindowWithoutRun +) -> tuple[FoundRow, dict[YearSide, UUID]]: + """Return the window's report and each year's simulations, found or inserted. + + The report names its first year's simulations. + """ + simulation_ids = _find_or_insert_simulations(session, request) + first_year = request.years[0].year + report = find_or_insert_report( + session, + economy_report_row( + request.definition, + report_id=request.report_id, + tax_benefit_model_id=request.tax_benefit_model_id, + population=request.population, + inputs=request.inputs, + simulation_ids={ + side: simulation_ids[first_year, side] for side in _SIDE_NAMES + }, + ), + ) + return report, simulation_ids def window_run_row( @@ -285,19 +419,19 @@ def window_year_run_row( # noqa: PLR0913 # the year's run, then what it calcul def _find_or_insert_simulations( - session: Session, request: KeyedBudgetWindow + session: Session, request: KeyedBudgetWindowWithoutRun ) -> dict[YearSide, UUID]: """Return each year's sides' simulation IDs, found by key or inserted. In key order across every year, so two transactions never wait for each other in opposite orders; two sides with one key name one simulation. """ - proposed: dict[YearSide, ProposedSide] = {} + proposed: dict[YearSide, UUID] = {} by_key: dict[str, list[YearSide]] = {} for window_year in request.years: - for side, side_ids in _sides(window_year, reform_first=False): + for side, simulation_id in window_year.simulation_ids.items(): year_side: YearSide = (window_year.year, side) - proposed[year_side] = side_ids + proposed[year_side] = simulation_id key = request.definition.simulation(side, year=window_year.year) by_key.setdefault(key.definition_key, []).append(year_side) simulation_ids: dict[YearSide, UUID] = {} @@ -308,7 +442,7 @@ def _find_or_insert_simulations( session, economy_simulation_row( request.definition.simulation(side, year=year), - proposed[year, side].simulation_id, + proposed[year, side], request.population_in(year), ), ) diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/rerun_definitions.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/rerun_definitions.py index 113057b60..0fc20159e 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/rerun_definitions.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/rerun_definitions.py @@ -3,17 +3,24 @@ A re-run (``economy_rerun_records``) first reads the stored record's kind, country, year, region code, dataset name and each simulation's policy and dynamic, so the current catalog version's rows with the same code and name -can be found, and, for a budget window, its newest calculation's years. +can be found, and, for a budget window, its newest calculation's years. A +keyed budget window with no calculation yet, as a create without a run +leaves it (D4 · 0), has its years' simulations found by their keys +instead, so its first re-run is its first calculation. """ from __future__ import annotations -from dataclasses import dataclass +from dataclasses import dataclass, replace from typing import TYPE_CHECKING, Any, Literal from sqlalchemy import select from sqlalchemy.orm import aliased +from policyengine_simulation_persistence.definition_keys import ( + KEY_VERSION, + EconomyReportDefinition, +) from policyengine_simulation_persistence.economy_run_records import ( ECONOMY_REPORT_TYPE, SimulationChoice, @@ -48,6 +55,8 @@ # report or simulation, or anything else, such as a simulation of a filtered # population. type RecordKind = Literal["economy", "budget_window", "household", "unsupported"] +# A report's two sides, the baseline first. +_SIDES: tuple[Literal["baseline", "reform"], ...] = ("baseline", "reform") @dataclass(frozen=True) @@ -80,9 +89,12 @@ class ReportDefinition: row it named was deleted). ``baseline`` and ``reform`` are None when the report names no such simulation; a budget window's are its first year's. A budget window's ``window_years`` are the years of its newest - budget-window run whose report run names both sides, earliest first, - empty when it has none. ``household_id`` is a household report's stored - household, None for any other report. + budget-window run whose report run names both sides, earliest first. + A keyed window with no budget-window run, as a create without a run + leaves it, has each year's simulations found by their keys instead, + when its stored key is still its own and every year's simulations + exist; otherwise ``window_years`` is empty. ``household_id`` is a + household report's stored household, None for any other report. """ id: UUID @@ -138,6 +150,7 @@ def read_report_definition( Report.year, Report.inputs, Report.key_version, + Report.definition_key, region.code.label("region_code"), dataset.name.label("dataset_name"), baseline.id.label("baseline_id"), @@ -160,7 +173,7 @@ def read_report_definition( if row is None: return None kind = _report_kind(row["type"], row["household_id"], row["budget_window_size"]) - return ReportDefinition( + definition = ReportDefinition( id=row["id"], country=row["country"], kind=kind, @@ -171,12 +184,101 @@ def read_report_definition( baseline=_side(row, "baseline"), reform=_side(row, "reform"), budget_window_size=row["budget_window_size"], - window_years=( - _window_years(session, report_id) if kind == "budget_window" else () - ), household_id=row["household_id"], keyed=row["key_version"] is not None, ) + if kind != "budget_window": + return definition + window_years = _window_years(session, report_id) + if not window_years and not _has_window_run(session, report_id): + window_years = _window_years_by_key(session, definition, row) + return replace(definition, window_years=window_years) + + +def _has_window_run(session: Session, report_id: UUID) -> bool: + """Return whether the report has any budget-window run.""" + return ( + session.execute( + select(BudgetWindowRun.id).where(BudgetWindowRun.report_id == report_id) + ).first() + is not None + ) + + +def _window_years_by_key( + session: Session, definition: ReportDefinition, row: RowMapping +) -> tuple[WindowYearDefinition, ...]: + """Return a keyed window's years, each year's simulations found by key. + + Empty unless the report's stored key is the key its stored fields give, + on this release's key version, and every year's simulations exist. + """ + key_definition = _window_key_definition(definition) + if ( + key_definition is None + or row["key_version"] != KEY_VERSION + or row["definition_key"] != key_definition.definition_key + or key_definition.budget_window_size is None + ): + return () + years = range( + key_definition.year, key_definition.year + key_definition.budget_window_size + ) + keys = { + (year, side): key_definition.simulation(side, year=year).definition_key + for year in years + for side in _SIDES + } + # Each row is a (definition key, simulation ID) pair. + found = dict( + session.execute( + select(Simulation.definition_key, Simulation.id).where( + Simulation.key_version == KEY_VERSION, + Simulation.definition_key.in_(set(keys.values())), + ) + ) + .tuples() + .all() + ) + if not set(keys.values()) <= set(found): + return () + return tuple( + WindowYearDefinition( + year=year, + baseline_simulation_id=found[keys[year, "baseline"]], + reform_simulation_id=found[keys[year, "reform"]], + ) + for year in years + ) + + +def _window_key_definition( + definition: ReportDefinition, +) -> EconomyReportDefinition | None: + """Return the key definition a window's stored fields give, or None. + + None when a field the key names is missing. The SPM selection is the + one the report stores (``reports.inputs``). + """ + if ( + definition.year is None + or definition.budget_window_size is None + or definition.region_code is None + or definition.dataset_name is None + or definition.baseline is None + or definition.reform is None + ): + return None + return EconomyReportDefinition( + country=definition.country, + baseline=definition.baseline.choice, + reform=definition.reform.choice, + dataset_name=definition.dataset_name, + region_code=definition.region_code, + year=definition.year, + budget_window_size=definition.budget_window_size, + spm=(definition.inputs or {}).get("spm"), + ) def _window_years( diff --git a/projects/policyengine-apis-integ/tests/test_report_without_run_generated_client.py b/projects/policyengine-apis-integ/tests/test_report_without_run_generated_client.py index d99a46aa6..60f53bbdd 100644 --- a/projects/policyengine-apis-integ/tests/test_report_without_run_generated_client.py +++ b/projects/policyengine-apis-integ/tests/test_report_without_run_generated_client.py @@ -141,6 +141,7 @@ def test_a_created_budget_window_is_read_with_each_years_simulations(): response, _ = _create(201, CREATED_WINDOW, WINDOW_BODY) assert isinstance(response.parsed, ReportWithoutRunCreated) + assert isinstance(response.parsed.years, list) assert [year.year for year in response.parsed.years] == [2026, 2027] assert response.parsed.to_dict() == CREATED_WINDOW @@ -184,5 +185,7 @@ def test_a_refused_report_without_a_run_is_read_with_its_code( ): response, _ = _create(status_code, answer) - assert isinstance(response.parsed, model) - assert response.parsed.to_dict()["code"] == answer["code"] + parsed = response.parsed + assert isinstance(parsed, (EconomyError, EconomyRequestUnprocessable)) + assert isinstance(parsed, model) + assert parsed.to_dict()["code"] == answer["code"] diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/app.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/app.py index 17ecdc911..40633fc00 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/app.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/app.py @@ -59,10 +59,7 @@ add_economy_rerun_routes, ) from policyengine_simulation_entry.economy_reruns import EconomyRerunService -from policyengine_simulation_entry.economy_routes import ( - HouseholdReportSubmissions, - add_economy_routes, -) +from policyengine_simulation_entry.economy_routes import add_economy_routes from policyengine_simulation_entry.economy_submissions import ServiceSettings from policyengine_simulation_entry.economy_workers import ( ManifestEconomyWorkers, @@ -96,6 +93,10 @@ ManifestHouseholdWorkers, ModalHouseholdFunctionCaller, ) +from policyengine_simulation_entry.report_without_run_routes import ( + HouseholdReportService, + add_report_without_run_routes, +) from policyengine_simulation_entry.schemas import ( SimulationEntrypointReadinessResponse, TemporaryStage12ReportResponse, @@ -551,7 +552,7 @@ def _register_economy_routes( # noqa: PLR0913 # the app, its services and perm app: FastAPI, entry: EntryRuntime, submissions: EconomyService | None, - household_reports: HouseholdReportSubmissions | None, + household_reports: HouseholdReportService | None, *, submitter: AuthorizationDependency, reader: AuthorizationDependency, @@ -566,6 +567,9 @@ def _register_economy_routes( # noqa: PLR0913 # the app, its services and perm household_reports=household_reports, ) add_economy_rerun_routes(app, entry, submissions, submitter=submitter) + add_report_without_run_routes( + app, entry, submissions, household_reports, submitter=submitter + ) def economy_submissions_for( diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/budget_window_submissions.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/budget_window_submissions.py index e62752f6c..5248908e8 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/budget_window_submissions.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/budget_window_submissions.py @@ -59,7 +59,10 @@ from policyengine_simulation_entry.economy_calculation_inputs import ( report_run_calculation, ) -from policyengine_simulation_entry.economy_requests import stored_options +from policyengine_simulation_entry.economy_requests import ( + PreparedBudgetWindow, + stored_options, +) from policyengine_simulation_entry.economy_submission_errors import call_refused from policyengine_simulation_entry.economy_submissions import ( CALL_START_TIMEOUT_SECONDS, @@ -181,6 +184,60 @@ async def submit_budget_window( call. Raise the errors ``submit_report`` raises; the 503 after a write names the report, whose window was failed. """ + prepared = await self._prepare_budget_window(request) + worker, inputs, scope = prepared.worker, prepared.inputs, prepared.scope + window = prepared.window + proposed_first_year = window.years[0] + + def first_year_calculation(run_ids: ReportRunIds) -> RunCalculation: + return report_run_calculation( + worker, + scope, + self._origin(request_id), + run_ids=run_ids, + baseline_policy=inputs.baseline.reform, + reform_policy=inputs.reform.reform, + ) + + # Refused before anything is written, on the run IDs it proposes. + first_year_calculation( + ReportRunIds( + report_run_id=proposed_first_year.report_run_id, + baseline_simulation_run_id=proposed_first_year.baseline.simulation_run_id, + reform_simulation_run_id=proposed_first_year.reform.simulation_run_id, + ) + ) + found = await self._create( + "report", lambda: self._store.find_or_create_budget_window(window) + ) + first_year = found.years[0] + status = found.window_run.status + if found.window_run.inserted: + status = await self._start_first_years( + worker, + first_year_calculation(year_run_ids(first_year)), + report_id=found.report_id, + window_run_id=found.window_run.id, + first_year=first_year.year, + observability_context=observability_context, + ) + return BudgetWindowReportCreated( + report_id=found.report_id, + report_run_id=first_year.report_run_id, + budget_window_run_id=found.window_run.id, + status=status, + years=[year_created(window_year) for window_year in found.years], + ) + + async def _prepare_budget_window( + self, request: BudgetWindowReportRequest + ) -> PreparedBudgetWindow: + """Read and check what the window request names, writing nothing. + + Return the window the request names, keyed, with the IDs it + proposes, and what its years are calculated from. Raise as + ``submit_budget_window`` does before writing anything. + """ worker = await self._default_worker(request.country) options = request.options() spm = options.get("spm") @@ -222,46 +279,8 @@ async def submit_budget_window( ), ) scope = calculation_scope(request, worker, catalog, spm=spm) - proposed_first_year = window.years[0] - - def first_year_calculation(run_ids: ReportRunIds) -> RunCalculation: - return report_run_calculation( - worker, - scope, - self._origin(request_id), - run_ids=run_ids, - baseline_policy=inputs.baseline.reform, - reform_policy=inputs.reform.reform, - ) - - # Refused before anything is written, on the run IDs it proposes. - first_year_calculation( - ReportRunIds( - report_run_id=proposed_first_year.report_run_id, - baseline_simulation_run_id=proposed_first_year.baseline.simulation_run_id, - reform_simulation_run_id=proposed_first_year.reform.simulation_run_id, - ) - ) - found = await self._create( - "report", lambda: self._store.find_or_create_budget_window(window) - ) - first_year = found.years[0] - status = found.window_run.status - if found.window_run.inserted: - status = await self._start_first_years( - worker, - first_year_calculation(year_run_ids(first_year)), - report_id=found.report_id, - window_run_id=found.window_run.id, - first_year=first_year.year, - observability_context=observability_context, - ) - return BudgetWindowReportCreated( - report_id=found.report_id, - report_run_id=first_year.report_run_id, - budget_window_run_id=found.window_run.id, - status=status, - years=[year_created(window_year) for window_year in found.years], + return PreparedBudgetWindow( + worker=worker, inputs=inputs, scope=scope, window=window ) async def _start_first_years( # noqa: PLR0913 # the call, then the window it starts diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_requests.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_requests.py index 74e24dd67..0ad5e0524 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_requests.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_requests.py @@ -10,6 +10,7 @@ from __future__ import annotations +from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Final from policyengine_simulation_persistence import EconomyRequest @@ -31,8 +32,12 @@ from collections.abc import Mapping from policyengine_simulation_persistence import ( + BudgetWindowInputs, EconomyCatalogRows, + EconomyReportInputs, FoundEconomyReport, + KeyedBudgetWindow, + KeyedEconomyReport, RecordKind, ReportRunStatus, ) @@ -47,6 +52,34 @@ from policyengine_simulation_entry.economy_workers import EconomyWorker +@dataclass(frozen=True) +class PreparedEconomyReport: + """A report request read and checked, before any row is written. + + ``keyed`` is the report it names, with the IDs it proposes; ``worker``, + ``inputs`` and ``scope`` are what its run's calculation is built from. + """ + + worker: EconomyWorker + inputs: EconomyReportInputs + scope: CalculationScope + keyed: KeyedEconomyReport + + +@dataclass(frozen=True) +class PreparedBudgetWindow: + """A budget-window request read and checked, before any row is written. + + ``window`` is the window it names, with the IDs it proposes; the other + fields are what its years' calculations are built from. + """ + + worker: EconomyWorker + inputs: BudgetWindowInputs + scope: CalculationScope + window: KeyedBudgetWindow + + # The reports whose re-run calculates no cliffs, as their answers name them. _REPORTS_WITHOUT_CLIFFS: Final[dict[RecordKind, str]] = { "budget_window": "A budget-window report", 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 7c43818b7..d31b88ebe 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 @@ -78,6 +78,9 @@ from policyengine_simulation_entry.household_report_api_models import ( HouseholdReportCreated, ) +from policyengine_simulation_entry.report_without_run_routes import ( + EconomyReportsWithoutRunService, +) from policyengine_simulation_entry.route_support import observability_context if TYPE_CHECKING: @@ -119,8 +122,13 @@ async def rerun_simulation( ... -class EconomyService(EconomySubmissions, EconomyReruns, Protocol): - """Create, read and re-run economy reports and simulations.""" +class EconomyService( + EconomySubmissions, EconomyReruns, EconomyReportsWithoutRunService, Protocol +): + """Create, read and re-run economy reports and simulations. + + It also creates economy and budget-window reports without a run. + """ # Why a re-run answers 409; no run under way refuses one. diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_reruns.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_reruns.py index 7ffe75c84..9ad284fd4 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_reruns.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_reruns.py @@ -70,8 +70,6 @@ BudgetWindowReportCreated, ) from policyengine_simulation_entry.budget_window_submissions import ( - BudgetWindowRuns, - ReportSubmissionService, year_created, year_run_ids, ) @@ -97,6 +95,10 @@ from policyengine_simulation_entry.economy_submissions import ( CALL_START_TIMEOUT_SECONDS, ) +from policyengine_simulation_entry.reports_without_run import ( + ReportsWithoutRunRuns, + ReportWithoutRunService, +) from policyengine_simulation_entry.rerunnable_records import ( StoredReportRows, complete_window_years, @@ -153,7 +155,7 @@ _SIMULATION: Final[RecordName] = "simulation" -class EconomyRerunRuns(BudgetWindowRuns, Protocol): +class EconomyRerunRuns(ReportsWithoutRunRuns, Protocol): """The economy store's reads and writes, with budget windows' and re-runs'. ``EconomyRunStore`` is one. @@ -208,7 +210,7 @@ def create_simulation_rerun(self, rerun: NewSimulationRerun) -> FoundSimulationR ... -class EconomyRerunService(ReportSubmissionService[EconomyRerunRuns]): +class EconomyRerunService(ReportWithoutRunService[EconomyRerunRuns]): """Create and re-run economy and budget-window reports and simulations. A household report's re-run goes to ``household_reports``; without it, diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_submissions.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_submissions.py index 2a8eba0bc..aa0f3a6ae 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_submissions.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_submissions.py @@ -90,6 +90,7 @@ simulation_run_calculation, ) from policyengine_simulation_entry.economy_requests import ( + PreparedEconomyReport, calculation_scope, economy_request_for, report_created, @@ -296,6 +297,55 @@ async def submit_report( writes its runs' cliff calculations with them, and starts the new ones before the coordinator. """ + prepared = await self._prepare_report(request) + worker, inputs, scope = prepared.worker, prepared.inputs, prepared.scope + found = await self._create( + "report", lambda: self._store.find_or_create_report(prepared.keyed) + ) + cliffs = None + if found.cliffs is not None: + cliffs = await self._start_cliffs( + worker, + scope, + request_id, + found=found.cliffs, + baseline_policy=inputs.baseline.reform, + reform_policy=inputs.reform.reform, + observability_context=observability_context, + ) + status = found.run.status + if found.run.inserted: + calculation = report_run_calculation( + worker, + scope, + self._origin(request_id), + run_ids=ReportRunIds( + report_run_id=found.run.id, + baseline_simulation_run_id=found.baseline.simulation_run_id, + reform_simulation_run_id=found.reform.simulation_run_id, + ), + baseline_policy=inputs.baseline.reform, + reform_policy=inputs.reform.reform, + ) + status = await self._start_report_run( + worker, + calculation, + report_id=found.report_id, + run_id=found.run.id, + new_simulation_run_ids=(), + observability_context=observability_context, + ) + return report_created(found, status).model_copy(update={"cliffs": cliffs}) + + async def _prepare_report( + self, request: EconomyReportRequest + ) -> PreparedEconomyReport: + """Read and check what the report request names, writing nothing. + + Steps 1 and 2 (the module's): return the report the request names, + keyed, with the IDs it proposes, and what its run is calculated + from. Raise as ``submit_report`` does before writing anything. + """ worker = await self._default_worker(request.country) area_dataset_name = local_area_dataset_name(request, worker) options = request.options() @@ -333,43 +383,9 @@ async def submit_report( inputs=stored_options(options), cliffs=self._proposed_cliffs() if request.include_cliffs else None, ) - found = await self._create( - "report", lambda: self._store.find_or_create_report(keyed) + return PreparedEconomyReport( + worker=worker, inputs=inputs, scope=scope, keyed=keyed ) - cliffs = None - if found.cliffs is not None: - cliffs = await self._start_cliffs( - worker, - scope, - request_id, - found=found.cliffs, - baseline_policy=inputs.baseline.reform, - reform_policy=inputs.reform.reform, - observability_context=observability_context, - ) - status = found.run.status - if found.run.inserted: - calculation = report_run_calculation( - worker, - scope, - self._origin(request_id), - run_ids=ReportRunIds( - report_run_id=found.run.id, - baseline_simulation_run_id=found.baseline.simulation_run_id, - reform_simulation_run_id=found.reform.simulation_run_id, - ), - baseline_policy=inputs.baseline.reform, - reform_policy=inputs.reform.reform, - ) - status = await self._start_report_run( - worker, - calculation, - report_id=found.report_id, - run_id=found.run.id, - new_simulation_run_ids=(), - observability_context=observability_context, - ) - return report_created(found, status).model_copy(update={"cliffs": cliffs}) async def submit_simulation( self, diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_report_reruns.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_report_reruns.py index b6bee72e9..c5229af5a 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_report_reruns.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_report_reruns.py @@ -56,14 +56,16 @@ side_runs_calculation, ) from policyengine_simulation_entry.household_report_submissions import ( - HouseholdReports, - HouseholdReportSubmissionService, household_report_created, ) from policyengine_simulation_entry.household_workers import ( ManifestHouseholdWorkers, ModalHouseholdFunctionCaller, ) +from policyengine_simulation_entry.reports_without_run import ( + HouseholdReportsWithoutRun, + HouseholdReportWithoutRunService, +) from policyengine_simulation_entry.simulation_database import SimulationDatabase if TYPE_CHECKING: @@ -124,7 +126,7 @@ def sides(self) -> dict[ReportSide, SideDefinition]: return sides -class HouseholdReportRerunRows(HouseholdReports, Protocol): +class HouseholdReportRerunRows(HouseholdReportsWithoutRun, Protocol): """The household report reads and writes, with a stored report's re-run. ``HouseholdReportStore`` is one. @@ -150,7 +152,7 @@ async def rerun_report( class HouseholdReportRerunService( - HouseholdReportSubmissionService[HouseholdReportRerunRows] + HouseholdReportWithoutRunService[HouseholdReportRerunRows] ): """Create and re-run household reports; each run is one household function call.""" diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_report_submissions.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_report_submissions.py index af68f9864..fce81e8f9 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_report_submissions.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_report_submissions.py @@ -44,6 +44,7 @@ import asyncio import logging +from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Protocol from uuid import UUID, uuid4 @@ -163,6 +164,19 @@ def fail_unstarted_report( ... +@dataclass(frozen=True) +class PreparedHouseholdReport: + """A household report request read and checked, before any row is written. + + ``report`` is the report it names, with the IDs it proposes; ``worker`` + and ``inputs`` are what its run's call is built from. + """ + + worker: HouseholdWorker + inputs: HouseholdReportInputs + report: KeyedHouseholdReport + + class HouseholdReportSideRuns(Protocol): """A report side's simulation and the simulation run its report run names.""" @@ -313,25 +327,9 @@ async def submit_report( failed after its rows were inserted; and HouseholdReportBuildError (500) when the service built a request the contract refuses. """ - worker = await self._default_worker(request.country) - inputs = await self._read_inputs( - country=request.country, - household_id=request.household_id, - choices=_side_choices(request), - worker=worker, - ) - report = self._keyed_report(request, worker, inputs) + prepared = await self._prepare_report(request) + worker, inputs, report = prepared.worker, prepared.inputs, prepared.report year = report.definition.year - # Refused before anything is written, on the run IDs it proposes. - side_runs_calculation( - inputs, - year=year, - run_ids={ - side: proposed.simulation_run_id - for side, proposed in report.proposed_sides.items() - }, - worker=worker, - ) found = await self._create(lambda: self._store.find_or_create_report(report)) status = found.run.status if found.run.inserted: @@ -360,6 +358,36 @@ async def submit_report( reform=found.reform, ) + async def _prepare_report( + self, request: HouseholdReportRequest + ) -> PreparedHouseholdReport: + """Read and check what the report request names, writing nothing. + + Steps 1 and 2 (the module's): return the report the request names, + keyed, with the IDs it proposes, and what its run is calculated + from. Each side's household contract request is checked on the run + IDs it proposes. Raise as ``submit_report`` does before writing + anything. + """ + worker = await self._default_worker(request.country) + inputs = await self._read_inputs( + country=request.country, + household_id=request.household_id, + choices=_side_choices(request), + worker=worker, + ) + report = self._keyed_report(request, worker, inputs) + side_runs_calculation( + inputs, + year=report.definition.year, + run_ids={ + side: proposed.simulation_run_id + for side, proposed in report.proposed_sides.items() + }, + worker=worker, + ) + return PreparedHouseholdReport(worker=worker, inputs=inputs, report=report) + async def _default_worker(self, country: str) -> HouseholdWorker: try: return await asyncio.to_thread(self._workers.default_worker, country) diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/report_without_run_api_models.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/report_without_run_api_models.py new file mode 100644 index 000000000..b4877eb55 --- /dev/null +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/report_without_run_api_models.py @@ -0,0 +1,50 @@ +"""The answer of ``POST /reports/without-run``: a report and its simulations. + +API v1's one-time migration (D4 · 0) creates each saved report's report +this way, with no run; app v3 starts a report's first run when someone +opens it (``POST /reports/{report_id}/runs``). The request is +``POST /reports``' own body (``report_api_models.ReportRequest``). +""" + +from __future__ import annotations + +from typing import Literal +from uuid import UUID + +from pydantic import BaseModel, ConfigDict, Field + +# The kinds of report ``POST /reports`` takes, as its bodies name them. +ReportType = Literal["economy", "budget_window", "household"] + + +class _Answer(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + +class ReportWithoutRunYear(_Answer): + """A budget window's year and its sides' simulations.""" + + year: int + baseline_simulation_id: UUID + reform_simulation_id: UUID + + +class ReportWithoutRunCreated(_Answer): + """The report a create without a run ended on, and its simulations. + + The report and its simulations are found by the key ``POST /reports`` + uses, or created; a report found keeps whatever runs it has, and nothing + is started either way. ``reform_simulation_id`` is null only for a + household report of the baseline alone. A budget window's sides are its + first year's, and ``years`` names every year's, earliest first; other + reports leave ``years`` out. + """ + + report_id: UUID + report_type: ReportType + baseline_simulation_id: UUID + reform_simulation_id: UUID | None + # Left out of the answer for a report that isn't a budget window. + years: list[ReportWithoutRunYear] | None = Field( + default=None, exclude_if=lambda value: value is None + ) diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/report_without_run_routes.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/report_without_run_routes.py new file mode 100644 index 000000000..74bac55c6 --- /dev/null +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/report_without_run_routes.py @@ -0,0 +1,192 @@ +"""``POST /reports/without-run``: find or create a report by key, with no run. + +API v1's one-time migration (D4 · 0) creates each saved report's report +this way: the migration starts no calculation, and app v3 starts a +report's first run when someone opens it (``POST /reports/{report_id}/runs``). +The route takes ``POST /reports``' body (permission ``simulation:submit``) +and finds or creates the economy, budget-window or household report and its +simulations by the keys ``POST /reports`` uses, answering 201 with the +report's ID, its type and its simulations' IDs (a budget window's: every +year's). It creates no run and starts no Modal call; a report found keeps +whatever runs it has (``reports_without_run``). + +It refuses what ``POST /reports`` refuses, with the same codes, before +writing anything: 400 for a row the request names, or a function it needs, +that is missing; 422 for fields or stored values that cannot be calculated, +and for ``include_cliffs: true`` (``cliffs_not_available``); 503 with +``Retry-After`` when the service is not configured or the v2 version +manifest or the database cannot be read. A 500 (``internal_error``) may +follow a write, as ``POST /reports``' does. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Protocol + +from fastapi import APIRouter, Depends, Request, status +from fastapi.responses import JSONResponse + +from policyengine_simulation_entry.economy_api_models import ( + EconomyError, + EconomyRequestUnprocessable, +) +from policyengine_simulation_entry.economy_routes import ( + FORBIDDEN_ANSWER, + RETRY_AFTER_HEADER, + SUBMISSION_FAILURES, + HouseholdReportSubmissions, + not_configured_response, + submission_failure_response, + unexpected_failure_response, +) +from policyengine_simulation_entry.household_report_api_models import ( + HouseholdReportRequest, +) +from policyengine_simulation_entry.report_api_models import ReportRequest +from policyengine_simulation_entry.report_request_errors import ReportRequestRoute +from policyengine_simulation_entry.report_without_run_api_models import ( + ReportWithoutRunCreated, +) + +if TYPE_CHECKING: + from fastapi import FastAPI + + from policyengine_simulation_entry.auth import AuthorizationDependency + from policyengine_simulation_entry.budget_window_api_models import ( + BudgetWindowReportRequest, + ) + from policyengine_simulation_entry.economy_api_models import EconomyReportRequest + from policyengine_simulation_entry.entry_runtime import EntryRuntime + +REPORTS_WITHOUT_RUN_PATH = "/reports/without-run" + +_ERROR_ANSWER = {"model": EconomyError} +_RESPONSES: dict[int | str, dict[str, Any]] = { + 201: { + "description": ( + "The report and its simulations, found by the key POST /reports " + "uses or created, with no run created and nothing started; a " + "budget window's every year's simulations" + ) + }, + 400: { + "description": ( + "A row the request names, or a function it needs, is missing, or " + "the catalog disagrees with the default worker; nothing was " + "written. The codes are POST /reports' own" + ), + **_ERROR_ANSWER, + }, + 403: FORBIDDEN_ANSWER, + 422: { + "description": ( + "The request's fields, or the stored policies and dynamics it " + "names, cannot be calculated; nothing was written. Stored values " + "carry POST /reports' codes, and include_cliffs: true is refused " + "with cliffs_not_available" + ), + "model": EconomyRequestUnprocessable, + }, + 500: { + "description": ( + "The service failed unexpectedly, or could not confirm its rows " + "were written (internal_error), possibly after creating the report" + ), + **_ERROR_ANSWER, + }, + 503: { + "description": ( + "Economy or household reports are not configured, or the v2 " + "version manifest or the database cannot be read; nothing was " + "written. Retry after Retry-After seconds" + ), + "headers": RETRY_AFTER_HEADER, + **_ERROR_ANSWER, + }, +} + + +class EconomyReportsWithoutRunService(Protocol): + """Create economy and budget-window reports without a run.""" + + async def create_report_without_run( + self, request: EconomyReportRequest | BudgetWindowReportRequest + ) -> ReportWithoutRunCreated: + """Find or create the report and its simulations by key, starting nothing.""" + ... + + +class HouseholdReportsWithoutRunService(Protocol): + """Create household reports without a run.""" + + async def create_report_without_run( + self, request: HouseholdReportRequest + ) -> ReportWithoutRunCreated: + """Find or create the report and its simulations by key, starting nothing.""" + ... + + +class HouseholdReportService( + HouseholdReportSubmissions, HouseholdReportsWithoutRunService, Protocol +): + """Create household reports, with a run or without one.""" + + +def add_report_without_run_routes( + app: FastAPI, + entry: EntryRuntime, + economy_reports: EconomyReportsWithoutRunService | None, + household_reports: HouseholdReportsWithoutRunService | None, + *, + submitter: AuthorizationDependency, +) -> None: + """Add ``POST /reports/without-run``; without a service it answers 503.""" + log_string_limit = entry.runtime.config.limits.max_string_length + router = APIRouter(route_class=ReportRequestRoute) + + @router.post( + REPORTS_WITHOUT_RUN_PATH, + summary="Create an economy, budget-window or household report without a run", + description=( + "Find or create a report and its simulations by the key POST " + "/reports uses, on the v2 version manifest's default worker's " + "catalog, with no run and no calculation started: a report found " + "keeps whatever runs it has. The body is POST /reports' own. A " + "report created this way gets its first run from POST /reports " + "with the same body or from POST /reports/{report_id}/runs. " + "include_cliffs: true is refused, since no run is created." + ), + operation_id="create_report_without_run", + status_code=status.HTTP_201_CREATED, + response_model=ReportWithoutRunCreated, + responses=_RESPONSES, + dependencies=[Depends(submitter)], + ) + async def create_report_without_run( + body: ReportRequest, request: Request + ) -> JSONResponse: + # The create isn't awaited until the try below, which answers its failures. + if isinstance(body, HouseholdReportRequest): + if household_reports is None: + return not_configured_response("Household reports are not configured.") + entry.start_workflow_observability(request) + creating = household_reports.create_report_without_run(body) + else: + if economy_reports is None: + return not_configured_response() + entry.start_workflow_observability(request) + creating = economy_reports.create_report_without_run(body) + try: + created = await creating + except SUBMISSION_FAILURES as error: + return submission_failure_response(error, "report") + # Every other failure is still answered as the JSON 500 declared. + except Exception as error: # noqa: BLE001 # answered as internal_error + return unexpected_failure_response( + REPORTS_WITHOUT_RUN_PATH, error, max_characters=log_string_limit + ) + return JSONResponse( + created.model_dump(mode="json"), status_code=status.HTTP_201_CREATED + ) + + app.include_router(router) diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/reports_without_run.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/reports_without_run.py new file mode 100644 index 000000000..6d6b02e42 --- /dev/null +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/reports_without_run.py @@ -0,0 +1,194 @@ +"""Find or create a report and its simulations by key, without a run (D4 · 0). + +API v1's one-time migration creates each saved report's report this way: +the migration starts no calculation, and app v3 starts a report's first run +when someone opens it (``POST /reports/{report_id}/runs``). A create +without a run takes ``POST /reports``' steps up to its write: it reads the +v2 version manifest's default worker, then the catalog rows for that +worker's .py version and each side's values, so it refuses what +``POST /reports`` refuses, with the same codes, before anything is written. +It then finds or creates, in one transaction, the report and its +simulations (a budget window's: every year's) by the keys ``POST /reports`` +uses, and nothing else: no run, no cliff calculation and no Modal call. A +report found keeps whatever runs it has. A later ``POST /reports`` or +re-run of the same report finds the same rows and creates its run. + +A request asking for cliffs is refused (422 ``cliffs_not_available``) +before anything is read: cliffs are a simulation run's calculation, and +there is none. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Literal, Protocol + +from policyengine_simulation_entry.budget_window_api_models import ( + BudgetWindowReportRequest, +) +from policyengine_simulation_entry.budget_window_submissions import ( + BudgetWindowRuns, + ReportSubmissionService, +) +from policyengine_simulation_entry.economy_submission_errors import ( + EconomySubmissionUnprocessableError, + UnprocessableReason, +) +from policyengine_simulation_entry.household_report_submissions import ( + HouseholdReports, + HouseholdReportSubmissionService, +) +from policyengine_simulation_entry.report_without_run_api_models import ( + ReportWithoutRunCreated, + ReportWithoutRunYear, +) + +if TYPE_CHECKING: + from policyengine_simulation_persistence import ( + FoundBudgetWindowWithoutRun, + FoundReportWithoutRun, + KeyedBudgetWindowWithoutRun, + KeyedEconomyReportWithoutRun, + KeyedHouseholdReportWithoutRun, + ) + + from policyengine_simulation_entry.economy_api_models import EconomyReportRequest + from policyengine_simulation_entry.household_report_api_models import ( + HouseholdReportRequest, + ) + + +class ReportsWithoutRunRuns(BudgetWindowRuns, Protocol): + """The economy store's reads and writes, with creates without a run.""" + + def find_or_create_report_without_run( + self, report: KeyedEconomyReportWithoutRun + ) -> FoundReportWithoutRun: + """Find the report and its simulations by key, or create them, with no run.""" + ... + + def find_or_create_budget_window_without_run( + self, window: KeyedBudgetWindowWithoutRun + ) -> FoundBudgetWindowWithoutRun: + """Find a window and each year's simulations by key, or create them.""" + ... + + +class HouseholdReportsWithoutRun(HouseholdReports, Protocol): + """The household report reads and writes, with a create without a run.""" + + def find_or_create_report_without_run( + self, report: KeyedHouseholdReportWithoutRun + ) -> FoundReportWithoutRun: + """Find the report and its simulations by key, or create them, with no run.""" + ... + + +def refuse_cliffs_without_run(request: EconomyReportRequest) -> None: + """Refuse a report without a run that asks for cliffs (422).""" + if not request.include_cliffs: + return + raise EconomySubmissionUnprocessableError( + code="cliffs_not_available", + reasons=( + UnprocessableReason( + loc=("body", "include_cliffs"), + msg=( + "A report created without a run calculates no cliff " + "impacts. Send include_cliffs: false." + ), + type="cliffs_not_available", + ), + ), + ) + + +def report_without_run_created( + found: FoundReportWithoutRun, + report_type: Literal["economy", "household"], +) -> ReportWithoutRunCreated: + """Answer the report and simulations a create without a run ended on.""" + return ReportWithoutRunCreated( + report_id=found.report_id, + report_type=report_type, + baseline_simulation_id=found.baseline_simulation_id, + reform_simulation_id=found.reform_simulation_id, + ) + + +def window_without_run_created( + found: FoundBudgetWindowWithoutRun, +) -> ReportWithoutRunCreated: + """Answer the window and each year's simulations a create ended on.""" + first_year = found.years[0] + return ReportWithoutRunCreated( + report_id=found.report_id, + report_type="budget_window", + baseline_simulation_id=first_year.baseline_simulation_id, + reform_simulation_id=first_year.reform_simulation_id, + years=[ + ReportWithoutRunYear( + year=year.year, + baseline_simulation_id=year.baseline_simulation_id, + reform_simulation_id=year.reform_simulation_id, + ) + for year in found.years + ], + ) + + +class ReportWithoutRunService[Store: ReportsWithoutRunRuns = ReportsWithoutRunRuns]( + ReportSubmissionService[Store] +): + """Create economy and budget-window reports, with or without a run. + + ``Store`` is the store's type, as for ``EconomySubmissionService``. + """ + + async def create_report_without_run( + self, request: EconomyReportRequest | BudgetWindowReportRequest + ) -> ReportWithoutRunCreated: + """Find or create the report and its simulations by key, starting nothing. + + Raise EconomySubmissionUnprocessableError (422) for a request asking + for cliffs, before anything is read; otherwise the errors + ``submit_report`` raises before writing anything, and + EconomySubmissionOutcomeUnknownError (500) when the create's commit + failed after its rows were inserted. + """ + if isinstance(request, BudgetWindowReportRequest): + window = (await self._prepare_budget_window(request)).window + found_window = await self._create( + "report", + lambda: self._store.find_or_create_budget_window_without_run( + window.without_run + ), + ) + return window_without_run_created(found_window) + refuse_cliffs_without_run(request) + report = (await self._prepare_report(request)).keyed + found = await self._create( + "report", + lambda: self._store.find_or_create_report_without_run(report.without_run), + ) + return report_without_run_created(found, "economy") + + +class HouseholdReportWithoutRunService[ + Store: HouseholdReportsWithoutRun = HouseholdReportsWithoutRun +](HouseholdReportSubmissionService[Store]): + """Create household reports, with or without a run.""" + + async def create_report_without_run( + self, request: HouseholdReportRequest + ) -> ReportWithoutRunCreated: + """Find or create the report and its simulations by key, starting nothing. + + Raise the errors ``submit_report`` raises before writing anything, + and EconomySubmissionOutcomeUnknownError (500) when the create's + commit failed after its rows were inserted. + """ + report = (await self._prepare_report(request)).report + found = await self._create( + lambda: self._store.find_or_create_report_without_run(report.without_run) + ) + return report_without_run_created(found, "household") diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/rerunnable_records.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/rerunnable_records.py index 74d05c93f..2792b53ba 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/rerunnable_records.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/rerunnable_records.py @@ -175,7 +175,9 @@ def complete_window_years( Its newest calculation must have a report run naming both sides in each year of its window, from the report's first year; the definition leaves - out a year naming no reform. + out a year naming no reform. A keyed window with no calculation, as a + create without a run leaves it, has every year's simulations found by + key instead (``read_report_definition``), so this re-run is its first. """ expected = ( () From 2767ada52891ec714c68fbe42ad56b6459543547 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 05:23:33 +0400 Subject: [PATCH 4/8] Add a failing test for a window run landing mid-definition read Review round 1's bug 1: a re-run's definition read looked for a runless window's years, then for any window run, then for its years by key, each in its own statement. A window run another request commits between the first two reads leaves the window with no years, and the re-run answers 409. Co-Authored-By: Claude Opus 5.5 --- .../tests/test_economy_window_reruns.py | 51 ++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/libs/policyengine-simulation-persistence/tests/test_economy_window_reruns.py b/libs/policyengine-simulation-persistence/tests/test_economy_window_reruns.py index 05257b4c3..906671e50 100644 --- a/libs/policyengine-simulation-persistence/tests/test_economy_window_reruns.py +++ b/libs/policyengine-simulation-persistence/tests/test_economy_window_reruns.py @@ -57,7 +57,7 @@ insert_window_rerun, read_report_definition, ) -from sqlalchemy import insert, text +from sqlalchemy import event, insert, text if TYPE_CHECKING: from sqlalchemy import Connection @@ -791,3 +791,52 @@ def test_a_rerun_gives_a_keyed_window_with_no_window_run_its_first_window_run( assert {year_run["budget_window_run_id"] for year_run in year_runs} == { rerun.window_run_id } + + +def test_a_window_run_landing_while_a_runless_windows_definition_is_read_keeps_years( + public_api_database_url, +) -> None: + """Review round 1's bug 1: another request's window run lands mid-read. + + The read's statements each see what has been committed when they run, so + a window run another request commits between them is seen by the later + ones only. Inserted after the read's first statement naming window runs, + it stands in for that commit. + """ + with rolled_back_transaction(public_api_database_url) as connection: + economy = insert_economy_catalog(connection) + act_as_the_service(connection) + found = _keyed_window(connection, economy) + _remove_window_runs(connection, found) + landed: list[UUID] = [] + + def land_a_window_run( + statement_connection, _cursor, statement, _parameters, _context, _many + ) -> None: + if landed or "budget_window_runs" not in statement: + return + window_run_id = uuid4() + dbapi_connection = statement_connection.connection.dbapi_connection + with dbapi_connection.cursor() as other_cursor: + other_cursor.execute( + "INSERT INTO public.budget_window_runs (id, report_id, " + "tax_benefit_model_version_id, policyengine_version, " + "recalculate, status) VALUES (%s, %s, %s, %s, false, 'pending')", + ( + window_run_id, + found.report_id, + economy.catalog.version_id, + VERSIONS.policyengine_version, + ), + ) + landed.append(window_run_id) + + event.listen(connection, "after_cursor_execute", land_a_window_run) + try: + definition = in_session(connection, read_report_definition, found.report_id) + finally: + event.remove(connection, "after_cursor_execute", land_a_window_run) + + assert len(landed) == 1 + assert definition is not None + assert definition.window_years == _year_simulations(found) From 5b66cef70f3fd32031283d6cf5cd87d7b3cea788 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 05:23:39 +0400 Subject: [PATCH 5/8] Read whether a window has a window run before its years A re-run's definition read now decides first whether the window has any window run: with one, its years come from its newest; with none, by key. A window run another request commits after that read is joined by the re-run's write, which finds it on the same years, so the re-run no longer answers 409 (review round 1's bug 1). Co-Authored-By: Claude Opus 5.5 --- .../rerun_definitions.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/rerun_definitions.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/rerun_definitions.py index 0fc20159e..ee9d8ccd9 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/rerun_definitions.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/rerun_definitions.py @@ -189,9 +189,13 @@ def read_report_definition( ) if kind != "budget_window": return definition - window_years = _window_years(session, report_id) - if not window_years and not _has_window_run(session, report_id): - window_years = _window_years_by_key(session, definition, row) + # Whether it has a window run is read first: a window run another request + # commits after this read is joined by the re-run, on the same years. + window_years = ( + _window_years(session, report_id) + if _has_window_run(session, report_id) + else _window_years_by_key(session, definition, row) + ) return replace(definition, window_years=window_years) From 5ae7dafbbf026b65303184a8528529592a179898 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 05:26:08 +0400 Subject: [PATCH 6/8] Add failing tests for review round 1's quality findings - The services that create reports without a run are built apart from the services that create runs, by their own factories, and the route uses those (removing the route later then touches only its own modules). - A budget window without a run is refused before writing when its first year's calculation input cannot be built, as POST /reports refuses it; the economy service gets the call's request ID for that check. - A window's proposed and found years use the re-run read's WindowYearDefinition. - The by-key window read is tested on a window created without a run, with and without an SPM selection; the route's permission is in the authorization table (those two cases pass already). Co-Authored-By: Claude Opus 5.5 --- .../tests/test_economy_window_reruns.py | 56 +++++++++- .../tests/test_reports_without_run.py | 4 +- .../tests/test_auth.py | 20 ++++ .../tests/test_reports_without_run.py | 105 ++++++++++++++++-- 4 files changed, 170 insertions(+), 15 deletions(-) diff --git a/libs/policyengine-simulation-persistence/tests/test_economy_window_reruns.py b/libs/policyengine-simulation-persistence/tests/test_economy_window_reruns.py index 906671e50..0f2d89b14 100644 --- a/libs/policyengine-simulation-persistence/tests/test_economy_window_reruns.py +++ b/libs/policyengine-simulation-persistence/tests/test_economy_window_reruns.py @@ -42,7 +42,9 @@ EconomyReportDefinition, EconomyRequest, FoundBudgetWindow, + FoundBudgetWindowWithoutRun, KeyedBudgetWindow, + KeyedBudgetWindowWithoutRun, KeyedWindowYear, NewWindowRerun, ProposedSide, @@ -54,6 +56,7 @@ WindowRerunYear, WindowYearDefinition, find_or_create_budget_window, + find_or_create_budget_window_without_run, insert_window_rerun, read_report_definition, ) @@ -703,21 +706,64 @@ def _year_simulations(found: FoundBudgetWindow) -> tuple[WindowYearDefinition, . ) +def _runless_window( + connection: Connection, economy: EconomyCatalog, *, spm: dict | None = None +) -> FoundBudgetWindowWithoutRun: + """Create a keyed window of current law against current law, with no run.""" + definition = EconomyReportDefinition( + country="us", + baseline=CURRENT_LAW, + reform=CURRENT_LAW, + dataset_name="populace_us_2024", + region_code="us", + year=WINDOW_YEARS[0], + budget_window_size=len(WINDOW_YEARS), + spm=spm, + ) + return in_session( + connection, + find_or_create_budget_window_without_run, + KeyedBudgetWindowWithoutRun( + definition=definition, + report_id=uuid4(), + tax_benefit_model_id=economy.catalog.model_id, + population=economy.population(year=WINDOW_YEARS[0]), + inputs={} if spm is None else {"spm": spm}, + years=tuple( + WindowYearDefinition( + year=year, + baseline_simulation_id=uuid4(), + reform_simulation_id=uuid4(), + ) + for year in WINDOW_YEARS + ), + ), + ) + + +@pytest.mark.parametrize( + "spm", + [None, {"geography_kind": "national"}], + ids=["no_spm_selection", "spm_selection"], +) def test_a_keyed_window_with_no_window_run_names_each_years_simulations_by_key( - public_api_database_url, + public_api_database_url, spm: dict | None ) -> None: - """D4 · 0: a window created without a run can be re-run for its first run.""" + """D4 · 0: a window created without a run can be re-run for its first run. + + The SPM selection is the one key field read back from the report's + stored options. + """ with rolled_back_transaction(public_api_database_url) as connection: economy = insert_economy_catalog(connection) act_as_the_service(connection) - found = _keyed_window(connection, economy) - _remove_window_runs(connection, found) + found = _runless_window(connection, economy, spm=spm) definition = in_session(connection, read_report_definition, found.report_id) assert definition is not None assert (definition.kind, definition.keyed) == ("budget_window", True) - assert definition.window_years == _year_simulations(found) + assert definition.window_years == found.years def test_a_keyed_window_with_no_window_run_whose_row_lost_its_key_has_no_years( diff --git a/libs/policyengine-simulation-persistence/tests/test_reports_without_run.py b/libs/policyengine-simulation-persistence/tests/test_reports_without_run.py index 99d89da65..116f2fa92 100644 --- a/libs/policyengine-simulation-persistence/tests/test_reports_without_run.py +++ b/libs/policyengine-simulation-persistence/tests/test_reports_without_run.py @@ -45,7 +45,7 @@ KeyedWindowYear, ProposedSide, SimulationChoice, - WindowYearSimulations, + WindowYearDefinition, find_or_create_budget_window, find_or_create_budget_window_without_run, find_or_create_economy_report, @@ -342,7 +342,7 @@ def test_a_budget_window_without_a_run_finds_the_window_a_create_with_one_made( assert (found.report_id, found.report_inserted) == (created.report_id, False) assert found.years == tuple( - WindowYearSimulations( + WindowYearDefinition( year=year.year, baseline_simulation_id=year.baseline.simulation_id, reform_simulation_id=year.reform.simulation_id, diff --git a/projects/policyengine-simulation-entry/tests/test_auth.py b/projects/policyengine-simulation-entry/tests/test_auth.py index 893ca2648..ebe96ebf6 100644 --- a/projects/policyengine-simulation-entry/tests/test_auth.py +++ b/projects/policyengine-simulation-entry/tests/test_auth.py @@ -225,6 +225,16 @@ class ProtectedRoute(NamedTuple): # returns once authorized. Stage 12 and household calculations are # unconfigured in these tests, so an authorized request to either reaches the # handler's 503 response. +# An economy report's body, as POST /reports takes it; an unconfigured +# service answers it 503 once the caller is authorized. +REPORT_WITHOUT_RUN_PAYLOAD = { + "country": "us", + "report_type": "economy", + "year": 2026, + "region_code": "us", + "baseline": {"policy_id": None, "dynamic_id": None}, + "reform": {"policy_id": None, "dynamic_id": None}, +} PROTECTED_ROUTES = [ pytest.param( ProtectedRoute( @@ -306,6 +316,16 @@ class ProtectedRoute(NamedTuple): ), id="read-household-calculation", ), + pytest.param( + ProtectedRoute( + "post", + "/reports/without-run", + REPORT_WITHOUT_RUN_PAYLOAD, + "simulation:submit", + 503, + ), + id="create-report-without-run", + ), ] diff --git a/projects/policyengine-simulation-entry/tests/test_reports_without_run.py b/projects/policyengine-simulation-entry/tests/test_reports_without_run.py index d97267b05..676f0a3df 100644 --- a/projects/policyengine-simulation-entry/tests/test_reports_without_run.py +++ b/projects/policyengine-simulation-entry/tests/test_reports_without_run.py @@ -36,6 +36,7 @@ household_report_service, ) from policyengine_simulation_entry import app as app_module +from policyengine_simulation_entry import budget_window_submissions from policyengine_simulation_entry.app import create_app from policyengine_simulation_entry.budget_window_api_models import ( BudgetWindowReportRequest, @@ -61,7 +62,10 @@ from policyengine_simulation_entry.reports_without_run import ( HouseholdReportWithoutRunService, ReportWithoutRunService, + economy_reports_without_run_for, + household_reports_without_run_for, ) +from policyengine_simulation_entry.simulation_database import SimulationDatabase from policyengine_simulation_persistence import ( FoundBudgetWindowWithoutRun, FoundReportWithoutRun, @@ -202,7 +206,7 @@ def test_an_economy_report_without_a_run_is_keyed_as_a_create_with_one_is() -> N created = asyncio.run( _economy_service(store, caller=caller).create_report_without_run( - report_request() + report_request(), request_id="request" ) ) asyncio.run( @@ -251,7 +255,7 @@ def test_a_report_without_a_run_asking_for_cliffs_is_refused_before_any_read() - with pytest.raises(EconomySubmissionUnprocessableError) as refused: asyncio.run( _economy_service(store, workers=workers).create_report_without_run( - report_request(include_cliffs=True) + report_request(include_cliffs=True), request_id="request" ) ) @@ -268,7 +272,7 @@ def test_a_report_without_a_run_needs_the_version_manifest() -> None: with pytest.raises(EconomySubmissionUnavailableError) as unavailable: asyncio.run( _economy_service(store, workers=workers).create_report_without_run( - report_request() + report_request(), request_id="request" ) ) @@ -285,7 +289,7 @@ def test_a_budget_window_without_a_run_answers_each_years_simulations() -> None: created = asyncio.run( _economy_service( store, caller=caller, advancer=advancer - ).create_report_without_run(_window_request()) + ).create_report_without_run(_window_request(), request_id="request") ) asyncio.run( _economy_service(store_with_run).submit_budget_window( @@ -315,6 +319,30 @@ def test_a_budget_window_without_a_run_answers_each_years_simulations() -> None: assert (store.windows, advancer.advances, caller.report_runs) == ([], [], []) +def test_a_budget_window_without_a_run_checks_its_first_years_calculation( + monkeypatch, +) -> None: + """Review round 1: refused before writing, as POST /reports refuses it.""" + store = FakeEconomyStoreWithoutRun() + + def refuse_the_calculation(*_arguments: Any, **_keywords: Any) -> NoReturn: + message = "the first year's calculation cannot be built" + raise ValueError(message) + + monkeypatch.setattr( + budget_window_submissions, "report_run_calculation", refuse_the_calculation + ) + + with pytest.raises(ValueError, match="cannot be built"): + asyncio.run( + _economy_service(store).create_report_without_run( + _window_request(), request_id="request" + ) + ) + + assert store.windows_without_run == [] + + @pytest.mark.parametrize("sides", ["baseline_and_reform", "baseline_alone"]) def test_a_household_report_without_a_run_is_keyed_as_a_create_with_one_is( sides: str, @@ -363,9 +391,13 @@ class FakeReportsWithoutRun: answer: ReportWithoutRunCreated failure: Exception | None = None requests: list[Any] = field(default_factory=list) + request_ids: list[str | None] = field(default_factory=list) - async def create_report_without_run(self, request: Any) -> ReportWithoutRunCreated: + async def create_report_without_run( + self, request: Any, *, request_id: str | None = None + ) -> ReportWithoutRunCreated: self.requests.append(request) + self.request_ids.append(request_id) if self.failure is not None: _raise(self.failure) return self.answer @@ -384,11 +416,13 @@ def build( ) -> TestClient: monkeypatch.setattr( app_module, - "economy_submissions_for", - lambda settings, database, **_: economy, + "economy_reports_without_run_for", + lambda settings, database: economy, ) monkeypatch.setattr( - app_module, "household_reports_for", lambda settings, database: household + app_module, + "household_reports_without_run_for", + lambda settings, database: household, ) return TestClient( create_app( @@ -424,6 +458,10 @@ def test_a_report_without_a_run_answers_201_with_its_simulations( assert result.json() == answer.model_dump(mode="json") (request,) = economy.requests assert isinstance(request, request_type) + # The window's first year's calculation is checked with the call's + # request ID, as POST /reports checks it. + (request_id,) = economy.request_ids + assert isinstance(request_id, str) def test_a_household_report_without_a_run_answers_201_with_its_simulations( @@ -500,3 +538,54 @@ def test_a_report_without_a_run_answers_its_services_refusals( assert result.status_code == status_code assert result.json()["code"] == code + + +DATABASE_URL = "postgresql://simulation_service:secret@db.example:5432/postgres" + + +def test_a_configured_service_builds_its_services_without_a_run_apart() -> None: + """Review round 1: built apart from the services that create runs. + + Nothing reaches the database or Modal until the first request. + """ + settings = make_settings( + simulation_database_url=DATABASE_URL, v2_modal_environment="staging" + ) + database = SimulationDatabase.from_url(DATABASE_URL) + try: + economy = economy_reports_without_run_for(settings, database) + household = household_reports_without_run_for(settings, database) + economy_with_runs = app_module.economy_submissions_for(settings, database) + household_with_runs = app_module.household_reports_for(settings, database) + finally: + database.dispose() + + assert isinstance(economy, ReportWithoutRunService) + assert isinstance(household, HouseholdReportWithoutRunService) + assert not isinstance(economy_with_runs, ReportWithoutRunService) + assert not isinstance(household_with_runs, HouseholdReportWithoutRunService) + + +@pytest.mark.parametrize( + "settings_changes", + [ + {}, + {"simulation_database_url": DATABASE_URL}, + {"v2_modal_environment": "staging"}, + ], + ids=["neither", "database_only", "environment_only"], +) +def test_without_its_database_and_v2_environment_no_service_without_a_run_is_built( + settings_changes: dict[str, str], +) -> None: + settings = make_settings(**settings_changes) + database = SimulationDatabase.from_url(DATABASE_URL) + try: + built = ( + economy_reports_without_run_for(settings, database), + household_reports_without_run_for(settings, database), + ) + finally: + database.dispose() + + assert built == (None, None) From 4a1a59eae69a41e9ff57ceebce2d33414b600d95 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 05:29:49 +0400 Subject: [PATCH 7/8] Fix review round 1's quality findings for reports without a run - The services that create reports without a run are built by their own factories (economy_reports_without_run_for and household_reports_without_run_for) and registered by one call in create_app; the re-run services, their protocols and the economy routes' wiring are as they were on main, so removing the route later touches only its own modules. - A budget window's shared preparation builds its first year's calculation input on the proposed run IDs, so both POST /reports and POST /reports/without-run refuse a window that cannot be calculated before writing; the route passes the call's request ID for it. - WindowYearDefinition is the one window-year type for proposed, found and re-run years, and REPORT_SIDES the one side-name tuple. - The entrypoint README documents the route and the by-key re-run, and the re-run docstrings name the by-key years. Co-Authored-By: Claude Opus 5.5 --- .../__init__.py | 2 - .../keyed_economy_records.py | 10 +- .../keyed_household_records.py | 2 +- .../keyed_window_records.py | 52 +++----- .../rerun_definitions.py | 14 +- .../policyengine-simulation-entry/README.md | 30 ++++- .../src/policyengine_simulation_entry/app.py | 23 +++- .../budget_window_submissions.py | 54 ++++---- .../economy_requests.py | 16 ++- .../economy_rerun_routes.py | 12 +- .../economy_reruns.py | 19 +-- .../household_report_reruns.py | 10 +- .../report_without_run_routes.py | 23 ++-- .../reports_without_run.py | 120 ++++++++++++++++-- 14 files changed, 254 insertions(+), 133 deletions(-) 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 cefbde6cd..2878c52cc 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/__init__.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/__init__.py @@ -162,7 +162,6 @@ KeyedBudgetWindow, KeyedBudgetWindowWithoutRun, KeyedWindowYear, - WindowYearSimulations, find_or_create_budget_window, find_or_create_budget_window_without_run, ) @@ -371,7 +370,6 @@ "WindowSide", "WindowYearDefinition", "WindowYearRuns", - "WindowYearSimulations", "WithheldAreaCode", "bounded_session", "canonical_json", diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_economy_records.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_economy_records.py index 59a976049..1cec6f359 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_economy_records.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_economy_records.py @@ -84,7 +84,7 @@ # A report's two sides, the baseline first. type Side = Literal["baseline", "reform"] -_SIDES: Final[tuple[Side, Side]] = ("baseline", "reform") +REPORT_SIDES: Final[tuple[Side, Side]] = ("baseline", "reform") @dataclass(frozen=True) @@ -263,7 +263,7 @@ def _find_or_create_report_run( population=request.population, versions=request.versions, ) - for side in _SIDES + for side in REPORT_SIDES }, ) inserted = {found.id for found in runs.values() if found.inserted} @@ -385,7 +385,7 @@ def _find_or_insert_simulations( "reform": request.reform_simulation_id, } by_key: dict[str, list[Side]] = {} - for side in _SIDES: + for side in REPORT_SIDES: key = request.definition.simulation(side).definition_key by_key.setdefault(key, []).append(side) simulation_ids: dict[Side, UUID] = {} @@ -461,7 +461,7 @@ def find_or_insert_side_runs( side_rows[side]["simulation_id"]: side_rows[side] # The reform first, so one simulation on both sides keeps the # baseline's proposed ID. - for side in reversed(_SIDES) + for side in reversed(REPORT_SIDES) if side in side_rows } found = find_or_insert_simulation_runs(session, rows) @@ -556,7 +556,7 @@ def _found( simulation_run_id=run_ids[side], run_inserted=run_ids[side] in inserted_run_ids, ) - for side in _SIDES + for side in REPORT_SIDES } return FoundEconomyReport( report_id=report_id, diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_household_records.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_household_records.py index 673b9101f..93e5338c5 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_household_records.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_household_records.py @@ -74,7 +74,7 @@ def _check_reform_side( - definition: HouseholdReportDefinition, reform_proposed: object + definition: HouseholdReportDefinition, reform_proposed: ProposedSide | UUID | None ) -> None: """Refuse a reform side for a report without a reform, or none for one.""" if (reform_proposed is None) != (definition.reform is None): diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_window_records.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_window_records.py index 47ad870db..f402d682d 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_window_records.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_window_records.py @@ -48,12 +48,16 @@ simulation_run_row, ) from policyengine_simulation_persistence.keyed_economy_records import ( + REPORT_SIDES, FoundSide, ProposedSide, Side, economy_report_row, economy_simulation_row, ) +from policyengine_simulation_persistence.rerun_definitions import ( + WindowYearDefinition, +) from policyengine_simulation_persistence.shared_rows import ( FoundWindowRun, find_joinable_window_run, @@ -84,7 +88,6 @@ # A window year's side: its year and the side's name. type YearSide = tuple[int, Side] -_SIDE_NAMES: tuple[Side, Side] = ("baseline", "reform") @dataclass(frozen=True) @@ -110,23 +113,6 @@ class KeyedWindowYear: reform: ProposedSide -@dataclass(frozen=True) -class WindowYearSimulations: - """A window year's sides' simulations: the IDs proposed, or those found.""" - - year: int - baseline_simulation_id: UUID - reform_simulation_id: UUID - - @property - def simulation_ids(self) -> dict[Side, UUID]: - """Return each side's simulation, the baseline's first.""" - return { - "baseline": self.baseline_simulation_id, - "reform": self.reform_simulation_id, - } - - def _check_window( definition: EconomyReportDefinition, population: EconomyPopulation, years: list[int] ) -> None: @@ -154,7 +140,7 @@ class KeyedBudgetWindowWithoutRun: tax_benefit_model_id: UUID population: EconomyPopulation inputs: dict[str, Any] - years: tuple[WindowYearSimulations, ...] + years: tuple[WindowYearDefinition, ...] def __post_init__(self) -> None: """Refuse years that aren't the definition's, 1 to 75 from its first.""" @@ -173,7 +159,7 @@ class FoundBudgetWindowWithoutRun: report_id: UUID report_inserted: bool - years: tuple[WindowYearSimulations, ...] + years: tuple[WindowYearDefinition, ...] @dataclass(frozen=True) @@ -213,7 +199,7 @@ def without_run(self) -> KeyedBudgetWindowWithoutRun: population=self.population, inputs=self.inputs, years=tuple( - WindowYearSimulations( + WindowYearDefinition( year=window_year.year, baseline_simulation_id=window_year.baseline.simulation_id, reform_simulation_id=window_year.reform.simulation_id, @@ -335,7 +321,7 @@ def find_or_create_budget_window_without_run( report_id=report.id, report_inserted=report.inserted, years=tuple( - WindowYearSimulations( + WindowYearDefinition( year=window_year.year, baseline_simulation_id=simulation_ids[window_year.year, "baseline"], reform_simulation_id=simulation_ids[window_year.year, "reform"], @@ -363,7 +349,7 @@ def _find_or_insert_window_rows( population=request.population, inputs=request.inputs, simulation_ids={ - side: simulation_ids[first_year, side] for side in _SIDE_NAMES + side: simulation_ids[first_year, side] for side in REPORT_SIDES }, ), ) @@ -429,9 +415,13 @@ def _find_or_insert_simulations( proposed: dict[YearSide, UUID] = {} by_key: dict[str, list[YearSide]] = {} for window_year in request.years: - for side, simulation_id in window_year.simulation_ids.items(): + proposed_ids: dict[Side, UUID] = { + "baseline": window_year.baseline_simulation_id, + "reform": window_year.reform_simulation_id, + } + for side in REPORT_SIDES: year_side: YearSide = (window_year.year, side) - proposed[year_side] = simulation_id + proposed[year_side] = proposed_ids[side] key = request.definition.simulation(side, year=window_year.year) by_key.setdefault(key.definition_key, []).append(year_side) simulation_ids: dict[YearSide, UUID] = {} @@ -472,7 +462,7 @@ def insert_window_years( # noqa: PLR0913 # the years, then the window they bel """ if forced: for window_year in years: - for side in _SIDE_NAMES: + for side in REPORT_SIDES: insert_simulation_run( session, run_id=window_year.proposed_run_ids[side], @@ -486,7 +476,7 @@ def insert_window_years( # noqa: PLR0913 # the years, then the window they bel window_year, { side: (window_year.proposed_run_ids[side], True) - for side in _SIDE_NAMES + for side in REPORT_SIDES }, ) for window_year in years @@ -496,7 +486,7 @@ def insert_window_years( # noqa: PLR0913 # the years, then the window they bel for window_year in years: # The reform first, so one simulation on both sides keeps the # baseline's proposed ID. - for side in reversed(_SIDE_NAMES): + for side in reversed(REPORT_SIDES): simulation_id = window_year.simulation_ids[side] rows[simulation_id] = simulation_run_row( run_id=window_year.proposed_run_ids[side], @@ -513,7 +503,7 @@ def insert_window_years( # noqa: PLR0913 # the years, then the window they bel runs[window_year.simulation_ids[side]].id, runs[window_year.simulation_ids[side]].inserted, ) - for side in _SIDE_NAMES + for side in REPORT_SIDES }, ) for window_year in years @@ -550,7 +540,7 @@ def _found_year( simulation_run_id=side_runs[side][0], run_inserted=side_runs[side][1], ) - for side in _SIDE_NAMES + for side in REPORT_SIDES } return FoundWindowYear( year=window_year.year, @@ -580,7 +570,7 @@ def _years_to_insert( year=window_year.year, report_run_id=window_year.report_run_id, simulation_ids={ - side: simulation_ids[window_year.year, side] for side in _SIDE_NAMES + side: simulation_ids[window_year.year, side] for side in REPORT_SIDES }, proposed_run_ids={ side: side_ids.simulation_run_id diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/rerun_definitions.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/rerun_definitions.py index ee9d8ccd9..1d719e8dc 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/rerun_definitions.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/rerun_definitions.py @@ -35,6 +35,7 @@ TaxBenefitModel, TaxBenefitModelVersion, ) +from policyengine_simulation_persistence.keyed_economy_records import REPORT_SIDES from policyengine_simulation_persistence.tables import ( BudgetWindowRun, Report, @@ -55,8 +56,6 @@ # report or simulation, or anything else, such as a simulation of a filtered # population. type RecordKind = Literal["economy", "budget_window", "household", "unsupported"] -# A report's two sides, the baseline first. -_SIDES: tuple[Literal["baseline", "reform"], ...] = ("baseline", "reform") @dataclass(frozen=True) @@ -69,10 +68,13 @@ class SideDefinition: @dataclass(frozen=True) class WindowYearDefinition: - """One year of a budget window's newest calculation, and its sides' simulations. + """One year of a budget window, and its sides' simulations. - They are the simulations of the runs that year's report run names: a - year that joined another report's run names that run's simulation. + In a re-run's read they are the simulations of the runs that year's + report run of the newest calculation names (a year that joined another + report's run names that run's simulation), or, for a keyed window with + no calculation, those found by key. A create without a run proposes + them, and answers those it found or inserted. """ year: int @@ -231,7 +233,7 @@ def _window_years_by_key( keys = { (year, side): key_definition.simulation(side, year=year).definition_key for year in years - for side in _SIDES + for side in REPORT_SIDES } # Each row is a (definition key, simulation ID) pair. found = dict( diff --git a/projects/policyengine-simulation-entry/README.md b/projects/policyengine-simulation-entry/README.md index 7b2c2e7b4..bbb29b7a8 100644 --- a/projects/policyengine-simulation-entry/README.md +++ b/projects/policyengine-simulation-entry/README.md @@ -45,6 +45,7 @@ Auth0 permission: | `POST /reports` | `simulation:submit` | | `GET /reports/{report_id}` | `simulation:read` | | `POST /reports/{report_id}/runs` | `simulation:submit` | +| `POST /reports/without-run` | `simulation:submit` | | `POST /simulations` | `simulation:submit` | | `GET /simulations/{simulation_id}` | `simulation:read` | | `POST /simulations/{simulation_id}/runs` | `simulation:submit` | @@ -355,6 +356,28 @@ dynamic setting a parameter its side's policy also sets is 422 `unknown_dynamic`; and a dynamic with no parameter values this release reads is 400 `dynamic_without_values`. +## Creating a report without a run + +`POST /reports/without-run` takes `POST /reports`' body (an economy, +budget-window or household report) and finds or creates the report and its +simulations by the keys `POST /reports` uses, with no run and no Modal call. +API v1's one-time migration of saved reports uses it; app v3 starts a +migrated report's first run when someone opens it, through +`POST /reports/{report_id}/runs`, and a later `POST /reports` of the same +body finds the same report and simulations. It reads the default worker +from the v2 version manifest and the catalog version for its .py version, +and checks what `POST /reports` checks before writing, so it refuses with +the same 400 and 422 codes before anything is written; `include_cliffs: +true` is refused with 422 `cliffs_not_available`. A report found keeps +whatever runs it has, and nothing is started either way. It answers 201 +with `report_id`, `report_type`, `baseline_simulation_id` and +`reform_simulation_id` (null only for a household report of the baseline +alone); a budget window's sides are its first year's, and `years` names +every year's. It answers 503 with `Retry-After` when the service is not +configured or the manifest or database cannot be read, and a 500 +`internal_error` may follow a write, as `POST /reports`' does. The route is +temporary: it is removed once the migration has finished. + ## Re-running a report or simulation `POST /reports/{report_id}/runs` calculates a stored economy report again, @@ -398,6 +421,10 @@ recalculates it: `recalculate` is set, and its year runs and new simulation runs are marked `forced`. Each year's sides are runs of the simulations that year's report run of the report's newest window run names (a year that named another report's run names that report's simulation). +A window created by key with no window run, as `POST /reports/without-run` +creates one, has each year's simulations found by their keys instead, when +the report's stored key is still the key its stored fields give, so its +first re-run is its first calculation. Only a window run the re-run created has its first years started. Up to five years start at once, as a new window's do (a later year Modal doesn't confirm in time waits for an earlier year's coordinator); it answers 201 with the budget-window create's fields, naming the window run @@ -424,7 +451,8 @@ A re-run is refused before anything is written: 404 (`unknown_report`, `unknown_simulation`) for a record that doesn't exist; 409 `rerun_not_supported` for a household simulation (re-run only through its report), a budget window whose newest window run -lacks a year, or a record that names no region, dataset, year, simulation, +lacks a year, or that has no window run and no simulation for each year +under its key, or a record that names no region, dataset, year, simulation, household or country the service calculates (a household report names no region or dataset); and the create's 400 and 422 codes when the stored rows can't be calculated on the current catalog version, worded for the stored diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/app.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/app.py index 40633fc00..fefc4a83e 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/app.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/app.py @@ -59,7 +59,10 @@ add_economy_rerun_routes, ) from policyengine_simulation_entry.economy_reruns import EconomyRerunService -from policyengine_simulation_entry.economy_routes import add_economy_routes +from policyengine_simulation_entry.economy_routes import ( + HouseholdReportSubmissions, + add_economy_routes, +) from policyengine_simulation_entry.economy_submissions import ServiceSettings from policyengine_simulation_entry.economy_workers import ( ManifestEconomyWorkers, @@ -94,9 +97,12 @@ ModalHouseholdFunctionCaller, ) from policyengine_simulation_entry.report_without_run_routes import ( - HouseholdReportService, add_report_without_run_routes, ) +from policyengine_simulation_entry.reports_without_run import ( + economy_reports_without_run_for, + household_reports_without_run_for, +) from policyengine_simulation_entry.schemas import ( SimulationEntrypointReadinessResponse, TemporaryStage12ReportResponse, @@ -552,7 +558,7 @@ def _register_economy_routes( # noqa: PLR0913 # the app, its services and perm app: FastAPI, entry: EntryRuntime, submissions: EconomyService | None, - household_reports: HouseholdReportService | None, + household_reports: HouseholdReportSubmissions | None, *, submitter: AuthorizationDependency, reader: AuthorizationDependency, @@ -567,9 +573,6 @@ def _register_economy_routes( # noqa: PLR0913 # the app, its services and perm household_reports=household_reports, ) add_economy_rerun_routes(app, entry, submissions, submitter=submitter) - add_report_without_run_routes( - app, entry, submissions, household_reports, submitter=submitter - ) def economy_submissions_for( @@ -780,6 +783,14 @@ async def lifespan(_: FastAPI) -> AsyncIterator[None]: submitter=simulation_submitter, reader=simulation_reader, ) + # Kept apart from the services above, so removing it touches nothing else. + add_report_without_run_routes( + app, + entry, + economy_reports_without_run_for(runtime_settings, runtime_database), + household_reports_without_run_for(runtime_settings, runtime_database), + submitter=simulation_submitter, + ) _register_service_routes(app, entry) return app diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/budget_window_submissions.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/budget_window_submissions.py index 5248908e8..59e42ebb3 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/budget_window_submissions.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/budget_window_submissions.py @@ -184,29 +184,9 @@ async def submit_budget_window( call. Raise the errors ``submit_report`` raises; the 503 after a write names the report, whose window was failed. """ - prepared = await self._prepare_budget_window(request) - worker, inputs, scope = prepared.worker, prepared.inputs, prepared.scope - window = prepared.window - proposed_first_year = window.years[0] - - def first_year_calculation(run_ids: ReportRunIds) -> RunCalculation: - return report_run_calculation( - worker, - scope, - self._origin(request_id), - run_ids=run_ids, - baseline_policy=inputs.baseline.reform, - reform_policy=inputs.reform.reform, - ) - - # Refused before anything is written, on the run IDs it proposes. - first_year_calculation( - ReportRunIds( - report_run_id=proposed_first_year.report_run_id, - baseline_simulation_run_id=proposed_first_year.baseline.simulation_run_id, - reform_simulation_run_id=proposed_first_year.reform.simulation_run_id, - ) - ) + prepared = await self._prepare_budget_window(request, request_id=request_id) + worker, window = prepared.worker, prepared.window + first_year_calculation = prepared.first_year_calculation found = await self._create( "report", lambda: self._store.find_or_create_budget_window(window) ) @@ -230,12 +210,15 @@ def first_year_calculation(run_ids: ReportRunIds) -> RunCalculation: ) async def _prepare_budget_window( - self, request: BudgetWindowReportRequest + self, request: BudgetWindowReportRequest, *, request_id: str ) -> PreparedBudgetWindow: """Read and check what the window request names, writing nothing. Return the window the request names, keyed, with the IDs it - proposes, and what its years are calculated from. Raise as + proposes, and how its first year's calculation input is built for + the call ``request_id`` names. That input is built once here, on the + run IDs the window proposes, so a window whose first year cannot be + calculated is refused before anything is written. Raise as ``submit_budget_window`` does before writing anything. """ worker = await self._default_worker(request.country) @@ -279,8 +262,27 @@ async def _prepare_budget_window( ), ) scope = calculation_scope(request, worker, catalog, spm=spm) + + def first_year_calculation(run_ids: ReportRunIds) -> RunCalculation: + return report_run_calculation( + worker, + scope, + self._origin(request_id), + run_ids=run_ids, + baseline_policy=inputs.baseline.reform, + reform_policy=inputs.reform.reform, + ) + + proposed_first_year = window.years[0] + first_year_calculation( + ReportRunIds( + report_run_id=proposed_first_year.report_run_id, + baseline_simulation_run_id=proposed_first_year.baseline.simulation_run_id, + reform_simulation_run_id=proposed_first_year.reform.simulation_run_id, + ) + ) return PreparedBudgetWindow( - worker=worker, inputs=inputs, scope=scope, window=window + worker=worker, window=window, first_year_calculation=first_year_calculation ) async def _start_first_years( # noqa: PLR0913 # the call, then the window it starts diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_requests.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_requests.py index 0ad5e0524..a57be06c4 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_requests.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_requests.py @@ -29,10 +29,10 @@ ) if TYPE_CHECKING: - from collections.abc import Mapping + from collections.abc import Callable, Mapping + from policyengine_simulation_contract.stage12_execution import ReportRunIds from policyengine_simulation_persistence import ( - BudgetWindowInputs, EconomyCatalogRows, EconomyReportInputs, FoundEconomyReport, @@ -49,6 +49,9 @@ EconomyReportRequest, EconomySimulationRequest, ) + from policyengine_simulation_entry.economy_calculation_inputs import ( + RunCalculation, + ) from policyengine_simulation_entry.economy_workers import EconomyWorker @@ -70,14 +73,15 @@ class PreparedEconomyReport: class PreparedBudgetWindow: """A budget-window request read and checked, before any row is written. - ``window`` is the window it names, with the IDs it proposes; the other - fields are what its years' calculations are built from. + ``window`` is the window it names, with the IDs it proposes; + ``first_year_calculation`` builds its first year's calculation input + for the report run IDs it is given, from which every later year's is + derived. """ worker: EconomyWorker - inputs: BudgetWindowInputs - scope: CalculationScope window: KeyedBudgetWindow + first_year_calculation: Callable[[ReportRunIds], RunCalculation] # The reports whose re-run calculates no cliffs, as their answers name them. 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 d31b88ebe..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 @@ -78,9 +78,6 @@ from policyengine_simulation_entry.household_report_api_models import ( HouseholdReportCreated, ) -from policyengine_simulation_entry.report_without_run_routes import ( - EconomyReportsWithoutRunService, -) from policyengine_simulation_entry.route_support import observability_context if TYPE_CHECKING: @@ -122,13 +119,8 @@ async def rerun_simulation( ... -class EconomyService( - EconomySubmissions, EconomyReruns, EconomyReportsWithoutRunService, Protocol -): - """Create, read and re-run economy reports and simulations. - - It also creates economy and budget-window reports without a run. - """ +class EconomyService(EconomySubmissions, EconomyReruns, Protocol): + """Create, read and re-run economy reports and simulations.""" # Why a re-run answers 409; no run under way refuses one. diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_reruns.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_reruns.py index 9ad284fd4..2f60b0461 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_reruns.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_reruns.py @@ -40,8 +40,10 @@ A budget-window report's re-run joins or creates a budget-window run with a report run per year, each year on the simulations that year's report -run of the report's newest window run names; a window run it created has -its first years started as a new window's do. A household report's re-run +run of the report's newest window run names, or, for a window created by +key with no window run (``reports_without_run``), on each year's +simulations found by key; a window run it created has its first years +started as a new window's do. A household report's re-run is the household report service's (``household_report_reruns``), which joins or creates its run as an economy report's re-run does, a run it created started by one household function call. A household simulation is @@ -70,6 +72,8 @@ BudgetWindowReportCreated, ) from policyengine_simulation_entry.budget_window_submissions import ( + BudgetWindowRuns, + ReportSubmissionService, year_created, year_run_ids, ) @@ -95,10 +99,6 @@ from policyengine_simulation_entry.economy_submissions import ( CALL_START_TIMEOUT_SECONDS, ) -from policyengine_simulation_entry.reports_without_run import ( - ReportsWithoutRunRuns, - ReportWithoutRunService, -) from policyengine_simulation_entry.rerunnable_records import ( StoredReportRows, complete_window_years, @@ -155,7 +155,7 @@ _SIMULATION: Final[RecordName] = "simulation" -class EconomyRerunRuns(ReportsWithoutRunRuns, Protocol): +class EconomyRerunRuns(BudgetWindowRuns, Protocol): """The economy store's reads and writes, with budget windows' and re-runs'. ``EconomyRunStore`` is one. @@ -210,7 +210,7 @@ def create_simulation_rerun(self, rerun: NewSimulationRerun) -> FoundSimulationR ... -class EconomyRerunService(ReportWithoutRunService[EconomyRerunRuns]): +class EconomyRerunService(ReportSubmissionService[EconomyRerunRuns]): """Create and re-run economy and budget-window reports and simulations. A household report's re-run goes to ``household_reports``; without it, @@ -503,7 +503,8 @@ async def _rerun_window( """Join or create the window's run on the current versions. Each year's sides are runs of that year's own simulations, as its - report run in the report's newest window run names them. A keyed + report run in the report's newest window run names them, or, for a + keyed window with no window run, as their keys find them. A keyed window's unforced re-run joins its window run, or each year's sides join their simulations' runs; a forced one, or one of a window created before keys (interim answer B), recalculates every year as diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_report_reruns.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_report_reruns.py index c5229af5a..b6bee72e9 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_report_reruns.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_report_reruns.py @@ -56,16 +56,14 @@ side_runs_calculation, ) from policyengine_simulation_entry.household_report_submissions import ( + HouseholdReports, + HouseholdReportSubmissionService, household_report_created, ) from policyengine_simulation_entry.household_workers import ( ManifestHouseholdWorkers, ModalHouseholdFunctionCaller, ) -from policyengine_simulation_entry.reports_without_run import ( - HouseholdReportsWithoutRun, - HouseholdReportWithoutRunService, -) from policyengine_simulation_entry.simulation_database import SimulationDatabase if TYPE_CHECKING: @@ -126,7 +124,7 @@ def sides(self) -> dict[ReportSide, SideDefinition]: return sides -class HouseholdReportRerunRows(HouseholdReportsWithoutRun, Protocol): +class HouseholdReportRerunRows(HouseholdReports, Protocol): """The household report reads and writes, with a stored report's re-run. ``HouseholdReportStore`` is one. @@ -152,7 +150,7 @@ async def rerun_report( class HouseholdReportRerunService( - HouseholdReportWithoutRunService[HouseholdReportRerunRows] + HouseholdReportSubmissionService[HouseholdReportRerunRows] ): """Create and re-run household reports; each run is one household function call.""" diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/report_without_run_routes.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/report_without_run_routes.py index 74bac55c6..a6457208f 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/report_without_run_routes.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/report_without_run_routes.py @@ -34,7 +34,7 @@ FORBIDDEN_ANSWER, RETRY_AFTER_HEADER, SUBMISSION_FAILURES, - HouseholdReportSubmissions, + call_request_id_for, not_configured_response, submission_failure_response, unexpected_failure_response, @@ -110,9 +110,16 @@ class EconomyReportsWithoutRunService(Protocol): """Create economy and budget-window reports without a run.""" async def create_report_without_run( - self, request: EconomyReportRequest | BudgetWindowReportRequest + self, + request: EconomyReportRequest | BudgetWindowReportRequest, + *, + request_id: str, ) -> ReportWithoutRunCreated: - """Find or create the report and its simulations by key, starting nothing.""" + """Find or create the report and its simulations by key, starting nothing. + + ``request_id`` is the call's, with which a budget window's first + year's calculation input is checked. + """ ... @@ -126,12 +133,6 @@ async def create_report_without_run( ... -class HouseholdReportService( - HouseholdReportSubmissions, HouseholdReportsWithoutRunService, Protocol -): - """Create household reports, with a run or without one.""" - - def add_report_without_run_routes( app: FastAPI, entry: EntryRuntime, @@ -175,7 +176,9 @@ async def create_report_without_run( if economy_reports is None: return not_configured_response() entry.start_workflow_observability(request) - creating = economy_reports.create_report_without_run(body) + creating = economy_reports.create_report_without_run( + body, request_id=call_request_id_for(request) + ) try: created = await creating except SUBMISSION_FAILURES as error: diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/reports_without_run.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/reports_without_run.py index 6d6b02e42..63f010038 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/reports_without_run.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/reports_without_run.py @@ -3,25 +3,36 @@ API v1's one-time migration creates each saved report's report this way: the migration starts no calculation, and app v3 starts a report's first run when someone opens it (``POST /reports/{report_id}/runs``). A create -without a run takes ``POST /reports``' steps up to its write: it reads the -v2 version manifest's default worker, then the catalog rows for that -worker's .py version and each side's values, so it refuses what -``POST /reports`` refuses, with the same codes, before anything is written. -It then finds or creates, in one transaction, the report and its -simulations (a budget window's: every year's) by the keys ``POST /reports`` -uses, and nothing else: no run, no cliff calculation and no Modal call. A -report found keeps whatever runs it has. A later ``POST /reports`` or -re-run of the same report finds the same rows and creates its run. +without a run takes ``POST /reports``' steps up to its write, through the +same code: it reads the v2 version manifest's default worker, then the +catalog rows for that worker's .py version and each side's values, and +checks what ``POST /reports`` checks before writing (a budget window's +first year's calculation input, a household report's household contract +requests), so it refuses what ``POST /reports`` refuses, with the same +codes, before anything is written. It then finds or creates, in one +transaction, the report and its simulations (a budget window's: every +year's) by the keys ``POST /reports`` uses, and nothing else: no run, no +cliff calculation and no Modal call. A report found keeps whatever runs it +has. A later ``POST /reports`` or re-run of the same report finds the same +rows and creates its run. A request asking for cliffs is refused (422 ``cliffs_not_available``) before anything is read: cliffs are a simulation run's calculation, and there is none. + +The services are built apart from those that create runs +(``economy_reports_without_run_for``, ``household_reports_without_run_for``), +so the route and this module can be removed without touching them once the +migration has finished. """ from __future__ import annotations from typing import TYPE_CHECKING, Literal, Protocol +from policyengine_simulation_persistence import EconomyRunStore, HouseholdReportStore +from policyengine_stage12_persistence import BudgetWindowStore + from policyengine_simulation_entry.budget_window_api_models import ( BudgetWindowReportRequest, ) @@ -33,14 +44,24 @@ EconomySubmissionUnprocessableError, UnprocessableReason, ) +from policyengine_simulation_entry.economy_submissions import ServiceSettings +from policyengine_simulation_entry.economy_workers import ( + ManifestEconomyWorkers, + ModalEconomyRunCaller, +) from policyengine_simulation_entry.household_report_submissions import ( HouseholdReports, HouseholdReportSubmissionService, ) +from policyengine_simulation_entry.household_workers import ( + ManifestHouseholdWorkers, + ModalHouseholdFunctionCaller, +) from policyengine_simulation_entry.report_without_run_api_models import ( ReportWithoutRunCreated, ReportWithoutRunYear, ) +from policyengine_simulation_entry.simulation_database import SimulationDatabase if TYPE_CHECKING: from policyengine_simulation_persistence import ( @@ -51,10 +72,17 @@ KeyedHouseholdReportWithoutRun, ) + from policyengine_simulation_entry.config import Settings from policyengine_simulation_entry.economy_api_models import EconomyReportRequest from policyengine_simulation_entry.household_report_api_models import ( HouseholdReportRequest, ) + from policyengine_simulation_entry.simulation_database import ( + SimulationDatabaseConnection, + ) + +# Each statement's limit, as the services that create runs set it. +STATEMENT_TIMEOUT_MILLISECONDS = 5_000 class ReportsWithoutRunRuns(BudgetWindowRuns, Protocol): @@ -145,18 +173,24 @@ class ReportWithoutRunService[Store: ReportsWithoutRunRuns = ReportsWithoutRunRu """ async def create_report_without_run( - self, request: EconomyReportRequest | BudgetWindowReportRequest + self, + request: EconomyReportRequest | BudgetWindowReportRequest, + *, + request_id: str, ) -> ReportWithoutRunCreated: """Find or create the report and its simulations by key, starting nothing. + ``request_id`` is the call's, with which a budget window's first + year's calculation input is checked, as ``POST /reports`` checks it. Raise EconomySubmissionUnprocessableError (422) for a request asking for cliffs, before anything is read; otherwise the errors - ``submit_report`` raises before writing anything, and - EconomySubmissionOutcomeUnknownError (500) when the create's commit - failed after its rows were inserted. + ``submit_report`` and ``submit_budget_window`` raise before writing + anything, and EconomySubmissionOutcomeUnknownError (500) when the + create's commit failed after its rows were inserted. """ if isinstance(request, BudgetWindowReportRequest): - window = (await self._prepare_budget_window(request)).window + prepared = await self._prepare_budget_window(request, request_id=request_id) + window = prepared.window found_window = await self._create( "report", lambda: self._store.find_or_create_budget_window_without_run( @@ -192,3 +226,61 @@ async def create_report_without_run( lambda: self._store.find_or_create_report_without_run(report.without_run) ) return report_without_run_created(found, "household") + + +def economy_reports_without_run_for( + settings: Settings, database: SimulationDatabaseConnection | None +) -> ReportWithoutRunService | None: + """Build the economy and budget-window service without a run, when configured. + + It needs what the economy submission service does, the simulation + database and the v2 Modal environment, whose version manifest names the + default worker; without them the route answers 503. It starts no Modal + call, though it takes the caller and window store its base service + does. Nothing is read until the first request. + """ + if not settings.economy_runs_configured or not isinstance( + database, SimulationDatabase + ): + return None + return ReportWithoutRunService( + windows=BudgetWindowStore(session_factory=database.session_factory), + store=EconomyRunStore.from_session_factory( + database.session_factory, + statement_timeout_milliseconds=STATEMENT_TIMEOUT_MILLISECONDS, + ), + workers=ManifestEconomyWorkers.from_modal( + manifest_name=settings.v2_manifest_name, + environment=settings.v2_modal_environment, + ), + caller=ModalEconomyRunCaller(settings.v2_modal_environment), + settings=ServiceSettings( + environment=settings.environment, + modal_environment=settings.v2_modal_environment, + ), + ) + + +def household_reports_without_run_for( + settings: Settings, database: SimulationDatabaseConnection | None +) -> HouseholdReportWithoutRunService | None: + """Build the household report service without a run, when configured. + + It needs what the household report service does; without it household + reports answer 503. Nothing is read until the first request. + """ + if not settings.household_calculations_configured or not isinstance( + database, SimulationDatabase + ): + return None + return HouseholdReportWithoutRunService( + store=HouseholdReportStore.from_session_factory( + database.session_factory, + statement_timeout_milliseconds=STATEMENT_TIMEOUT_MILLISECONDS, + ), + workers=ManifestHouseholdWorkers.from_modal( + manifest_name=settings.v2_manifest_name, + environment=settings.v2_modal_environment, + ), + caller=ModalHouseholdFunctionCaller(settings.v2_modal_environment), + ) From 49949324a360373ff73b408ae2dfee97a93c7793 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 05:41:13 +0400 Subject: [PATCH 8/8] Fix review round 2's quality findings for reports without a run - WindowYearDefinition is defined with the window creates (keyed_window_records) and imported by the re-run read, so re-runs depend on creates and not the other way round. - Every by-key re-run test builds its window with find_or_create_budget_window_without_run, and a new test shows a re-run whose definition was read before another request's window run joins that window run. - The authorization table's comment is back above the table, and the economy_requests docstring names the prepared request types. Co-Authored-By: Claude Opus 5.5 --- .../__init__.py | 2 +- .../economy_rerun_records.py | 2 +- .../keyed_window_records.py | 19 +++- .../rerun_definitions.py | 19 +--- .../tests/test_economy_window_reruns.py | 99 ++++++++++--------- .../economy_requests.py | 8 +- .../tests/test_auth.py | 13 +-- 7 files changed, 88 insertions(+), 74 deletions(-) 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 2878c52cc..a75546191 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/__init__.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/__init__.py @@ -35,7 +35,6 @@ SideDefinition, SimulationDefinition, WindowRerunYear, - WindowYearDefinition, insert_household_report_rerun, insert_report_rerun, insert_report_rerun_with_cliffs, @@ -162,6 +161,7 @@ KeyedBudgetWindow, KeyedBudgetWindowWithoutRun, KeyedWindowYear, + WindowYearDefinition, find_or_create_budget_window, find_or_create_budget_window_without_run, ) diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/economy_rerun_records.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/economy_rerun_records.py index 0abd7f938..926127238 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/economy_rerun_records.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/economy_rerun_records.py @@ -72,6 +72,7 @@ ) from policyengine_simulation_persistence.keyed_window_records import ( FoundBudgetWindow, + WindowYearDefinition, WindowYearToInsert, insert_window_years, stored_window_years, @@ -82,7 +83,6 @@ ReportDefinition, SideDefinition, SimulationDefinition, - WindowYearDefinition, read_report_definition, read_simulation_definition, ) diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_window_records.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_window_records.py index f402d682d..7260ea645 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_window_records.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/keyed_window_records.py @@ -55,9 +55,6 @@ economy_report_row, economy_simulation_row, ) -from policyengine_simulation_persistence.rerun_definitions import ( - WindowYearDefinition, -) from policyengine_simulation_persistence.shared_rows import ( FoundWindowRun, find_joinable_window_run, @@ -113,6 +110,22 @@ class KeyedWindowYear: reform: ProposedSide +@dataclass(frozen=True) +class WindowYearDefinition: + """One year of a budget window, and its sides' simulations. + + In a re-run's read they are the simulations of the runs that year's + report run of the newest calculation names (a year that joined another + report's run names that run's simulation), or, for a keyed window with + no calculation, those found by key. A create without a run proposes + them, and answers those it found or inserted. + """ + + year: int + baseline_simulation_id: UUID + reform_simulation_id: UUID + + def _check_window( definition: EconomyReportDefinition, population: EconomyPopulation, years: list[int] ) -> None: diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/rerun_definitions.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/rerun_definitions.py index 1d719e8dc..d3e979ade 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/rerun_definitions.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/rerun_definitions.py @@ -36,6 +36,9 @@ TaxBenefitModelVersion, ) from policyengine_simulation_persistence.keyed_economy_records import REPORT_SIDES +from policyengine_simulation_persistence.keyed_window_records import ( + WindowYearDefinition, +) from policyengine_simulation_persistence.tables import ( BudgetWindowRun, Report, @@ -66,22 +69,6 @@ class SideDefinition: choice: SimulationChoice -@dataclass(frozen=True) -class WindowYearDefinition: - """One year of a budget window, and its sides' simulations. - - In a re-run's read they are the simulations of the runs that year's - report run of the newest calculation names (a year that joined another - report's run names that run's simulation), or, for a keyed window with - no calculation, those found by key. A create without a run proposes - them, and answers those it found or inserted. - """ - - year: int - baseline_simulation_id: UUID - reform_simulation_id: UUID - - @dataclass(frozen=True) class ReportDefinition: """What a stored report calculates, as a re-run reads it. diff --git a/libs/policyengine-simulation-persistence/tests/test_economy_window_reruns.py b/libs/policyengine-simulation-persistence/tests/test_economy_window_reruns.py index 0f2d89b14..14ae2408e 100644 --- a/libs/policyengine-simulation-persistence/tests/test_economy_window_reruns.py +++ b/libs/policyengine-simulation-persistence/tests/test_economy_window_reruns.py @@ -668,44 +668,6 @@ def test_a_forced_window_rerun_is_an_extra_run_beside_any_run_on_its_versions( assert all(run["forced"] for run in simulation_runs) -def _remove_window_runs(connection: Connection, found: FoundBudgetWindow) -> None: - """Delete a keyed window's runs as the superuser, leaving a window with none. - - What is left is what a create without a run stores: the report and each - year's simulations, found by their keys. - """ - connection.execute(text("RESET ROLE")) - simulation_run_ids = [ - side.simulation_run_id - for year in found.years - for side in (year.baseline, year.reform) - ] - connection.execute( - text("DELETE FROM public.report_runs WHERE budget_window_run_id = :id"), - {"id": found.window_run.id}, - ) - connection.execute( - text("DELETE FROM public.budget_window_runs WHERE id = :id"), - {"id": found.window_run.id}, - ) - connection.execute( - text("DELETE FROM public.simulation_runs WHERE id = ANY(:ids)"), - {"ids": simulation_run_ids}, - ) - act_as_the_service(connection) - - -def _year_simulations(found: FoundBudgetWindow) -> tuple[WindowYearDefinition, ...]: - return tuple( - WindowYearDefinition( - year=year.year, - baseline_simulation_id=year.baseline.simulation_id, - reform_simulation_id=year.reform.simulation_id, - ) - for year in found.years - ) - - def _runless_window( connection: Connection, economy: EconomyCatalog, *, spm: dict | None = None ) -> FoundBudgetWindowWithoutRun: @@ -773,8 +735,7 @@ def test_a_keyed_window_with_no_window_run_whose_row_lost_its_key_has_no_years( with rolled_back_transaction(public_api_database_url) as connection: economy = insert_economy_catalog(connection) act_as_the_service(connection) - found = _keyed_window(connection, economy) - _remove_window_runs(connection, found) + found = _runless_window(connection, economy) connection.execute(text("RESET ROLE")) # Its window's first two years' simulations still exist under their # keys, so only the report's own key tells this window apart. @@ -796,8 +757,7 @@ def test_a_rerun_gives_a_keyed_window_with_no_window_run_its_first_window_run( with rolled_back_transaction(public_api_database_url) as connection: economy = insert_economy_catalog(connection) act_as_the_service(connection) - found = _keyed_window(connection, economy) - _remove_window_runs(connection, found) + found = _runless_window(connection, economy) definition = in_session(connection, read_report_definition, found.report_id) assert definition is not None rerun = NewWindowRerun( @@ -852,8 +812,7 @@ def test_a_window_run_landing_while_a_runless_windows_definition_is_read_keeps_y with rolled_back_transaction(public_api_database_url) as connection: economy = insert_economy_catalog(connection) act_as_the_service(connection) - found = _keyed_window(connection, economy) - _remove_window_runs(connection, found) + found = _runless_window(connection, economy) landed: list[UUID] = [] def land_a_window_run( @@ -885,4 +844,54 @@ def land_a_window_run( assert len(landed) == 1 assert definition is not None - assert definition.window_years == _year_simulations(found) + assert definition.window_years == found.years + + +def test_a_rerun_read_before_another_requests_window_run_joins_that_window_run( + public_api_database_url, +) -> None: + """Review round 2: years read by key, then another request's window run. + + A window run created after the re-run's definition read names the + simulations the read found by key, so the re-run's write joins it. + """ + with rolled_back_transaction(public_api_database_url) as connection: + economy = insert_economy_catalog(connection) + act_as_the_service(connection) + runless = _runless_window(connection, economy) + definition = in_session(connection, read_report_definition, runless.report_id) + assert definition is not None + created_after_the_read = _keyed_window(connection, economy) + rerun = NewWindowRerun( + report_id=runless.report_id, + window_run_id=uuid4(), + population=economy.population(year=WINDOW_YEARS[0]), + versions=VERSIONS, + recalculate=False, + years=tuple( + WindowRerunYear( + year=year.year, + report_run_id=uuid4(), + baseline=RerunSide( + simulation_id=year.baseline_simulation_id, + simulation_run_id=uuid4(), + ), + reform=RerunSide( + simulation_id=year.reform_simulation_id, + simulation_run_id=uuid4(), + ), + ) + for year in definition.window_years + ), + ) + + joined = in_session(connection, insert_window_rerun, rerun) + + assert created_after_the_read.report_id == runless.report_id + assert (joined.window_run.id, joined.window_run.inserted) == ( + created_after_the_read.window_run.id, + False, + ) + assert [year.report_run_id for year in joined.years] == [ + year.report_run_id for year in created_after_the_read.years + ] diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_requests.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_requests.py index a57be06c4..ced446bdf 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_requests.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_requests.py @@ -4,8 +4,12 @@ turn a request into the persistence library's ``EconomyRequest``, choose what a report stores of the request's options, the calculation's scope on the default worker's bundle, and the answer for the report and run a -request ended on. The re-run service refuses cliffs for a report that -calculates none. +request ended on. A report or budget-window request read and checked +before anything is written is a ``PreparedEconomyReport`` or +``PreparedBudgetWindow``, which ``POST /reports`` and the create without a +run (``reports_without_run``) share; the household report service keeps +its own (``household_report_submissions.PreparedHouseholdReport``). The +re-run service refuses cliffs for a report that calculates none. """ from __future__ import annotations diff --git a/projects/policyengine-simulation-entry/tests/test_auth.py b/projects/policyengine-simulation-entry/tests/test_auth.py index ebe96ebf6..fcb5b810a 100644 --- a/projects/policyengine-simulation-entry/tests/test_auth.py +++ b/projects/policyengine-simulation-entry/tests/test_auth.py @@ -221,12 +221,7 @@ class ProtectedRoute(NamedTuple): authorized_status: int -# Each protected route, the permission it requires, and the status its handler -# returns once authorized. Stage 12 and household calculations are -# unconfigured in these tests, so an authorized request to either reaches the -# handler's 503 response. -# An economy report's body, as POST /reports takes it; an unconfigured -# service answers it 503 once the caller is authorized. +# An economy report's body, as POST /reports takes it. REPORT_WITHOUT_RUN_PAYLOAD = { "country": "us", "report_type": "economy", @@ -235,6 +230,12 @@ class ProtectedRoute(NamedTuple): "baseline": {"policy_id": None, "dynamic_id": None}, "reform": {"policy_id": None, "dynamic_id": None}, } + + +# Each protected route, the permission it requires, and the status its handler +# returns once authorized. Stage 12, household calculations and economy +# reports are unconfigured in these tests, so an authorized request to any of +# them reaches the handler's 503 response. PROTECTED_ROUTES = [ pytest.param( ProtectedRoute(