diff --git a/changelog.d/household-run-calculations.added.md b/changelog.d/household-run-calculations.added.md new file mode 100644 index 000000000..f7aedb2ad --- /dev/null +++ b/changelog.d/household-run-calculations.added.md @@ -0,0 +1 @@ +A household report's create and re-run may list the `variables` its runs calculate; each new simulation run records the list, sorted, in `household_run_variables`, and the household function calculates each side with its run's list. `POST /reports/{report_id}/runs/{report_run_id}/household-calculations` finds or starts an extra calculation of other variables, or across axes, of each side's run on the current versions, in `household_run_calculations`; identical requests share one, the stuck-run sweep covers them, and a failed run's is refused with 409 until the report is re-run. A `variables` list that is empty, repeats a name or has a name with a NUL character is refused with 422, as is a `variables` list on `POST /reports/without-run`, which creates no run to record it. `policyengine-api-simulation-client` gains the route and the `variables` fields. diff --git a/docs/engineering/skills/database-access.md b/docs/engineering/skills/database-access.md index 97a561ef8..ffbf06acf 100644 --- a/docs/engineering/skills/database-access.md +++ b/docs/engineering/skills/database-access.md @@ -170,8 +170,10 @@ and this repository has no migration chain of its own - the Stage 12 comparison tables, whose live schema deployment validation compares with the Stage 12 library's SQLAlchemy mappings. - the tables the simulation service writes (`simulations`, `reports`, - `simulation_runs`, `report_runs`, `budget_window_runs`, `household_jobs` - and `cliff_impacts`), modelled in `libs/policyengine-simulation-persistence`. + `simulation_runs`, `report_runs`, `budget_window_runs`, `household_jobs`, + `cliff_impacts`, `household_run_variables` and + `household_run_calculations`), modelled in + `libs/policyengine-simulation-persistence`. The service connects as its own role, which policyengine-api's privilege manifest grants. - the policyengine-api tables a calculation is read from (`households`, @@ -185,12 +187,14 @@ and this repository has no migration chain of its own - the run tables the v2 Modal coordinator, workers, household functions and stuck-run sweep write as the Modal worker role: `report_runs`, `simulation_runs`, `budget_window_runs`, the result tables, - `household_jobs` and `cliff_impacts`. The role also deletes finished - `household_jobs` rows of households given in the request whose versions a - deployment replaced. They use the same models, in - `libs/policyengine-simulation-persistence` (`tables.py` and - `result_tables.py`, which `sim.persistence.models-match-public-api` - compares with the Public API's tables), through the stores in + `household_jobs`, `cliff_impacts` and `household_run_calculations`; a + household function also reads `household_run_variables`. The role also + deletes finished `household_jobs` rows of households given in the request + whose versions a deployment replaced. They use the same models, in + `libs/policyengine-simulation-persistence` (`tables.py`, + `household_run_tables.py` and `result_tables.py`, which + `sim.persistence.models-match-public-api` compares with API v1's tables), + through the stores in `libs/policyengine-stage12-persistence`. The v1 `run_simulation` code imports neither library. diff --git a/docs/engineering/skills/observability.md b/docs/engineering/skills/observability.md index 97a7725ca..210349241 100644 --- a/docs/engineering/skills/observability.md +++ b/docs/engineering/skills/observability.md @@ -16,7 +16,7 @@ Use each identifier for its defined scope: | `evaluation_id` | One Stage 12 report | Stage 12 report construction | Yes, as functional report state | | `simulation_execution_id` | One Stage 12 baseline or reform simulation | Stage 12 coordinator | Yes, as functional simulation state | | `submission_claim_id` | One API v1 attempt to acquire ownership of a simulation submission | API v1 | Only where the simulation request is stored | -| `database_table` | The API v1 table holding the row a v2 Modal function call, or a Simulation Entrypoint log record, is about: `household_jobs`, `report_runs` (a report run or a household report run), `simulation_runs`, `cliff_impacts`, `reports` or `simulations` | The code writing the record, as a fixed name | No: telemetry only | +| `database_table` | The API v1 table holding the row a v2 Modal function call, or a Simulation Entrypoint log record, is about: `household_jobs`, `report_runs` (a report run or a household report run), `simulation_runs`, `cliff_impacts`, `household_run_calculations` (a household run's extra calculation), `reports` or `simulations` | The code writing the record, as a fixed name | No: telemetry only | | `database_row_id` | That row's UUID | The simulation service, which creates the row | Yes, as the row's ID | | `modal_call_id` | One Modal function call of a v2 Modal function | Modal | Only where the row records the call that claimed it; a segment worker's call is recorded nowhere, and its `database_row_id` names the simulation run its simulation worker's call claimed | diff --git a/docs/migration/stage-12-modal-worker-foundation.md b/docs/migration/stage-12-modal-worker-foundation.md index 2df74e587..d91dfee3d 100644 --- a/docs/migration/stage-12-modal-worker-foundation.md +++ b/docs/migration/stage-12-modal-worker-foundation.md @@ -977,15 +977,17 @@ A call can instead name a household report run, with the `HouseholdReportRunCalculation` (`policyengine_simulation_contract.household_report_execution`): the baseline's `HouseholdExecutionRequest` and, optionally, the reform's, each -request's calculation ID naming its simulation run. A call names a job or a -report run, never both. The function then: +request's calculation ID naming its simulation run. A call names at most +one of a job, a report run and an extra calculation. The function then: 1. claims the report run under its own Modal call ID, as a report run's coordinator does, and reads which baseline and reform simulation runs it names; 2. validates the payload and checks that its runs are those; -3. for each side, claims the side's simulation run, calculates it, and - writes its `HouseholdExecutionResult`, or its `HouseholdExecutionFailure` +3. for each side, claims the side's simulation run, calculates it with the + variables its run records in `household_run_variables` (every variable + without a row, whatever the payload lists, since identical requests + share runs), and writes its `HouseholdExecutionResult`, or its `HouseholdExecutionFailure` and one-line summary, to the run's `household_result` and `error_message`; 4. marks the report run succeeded only if every side's run did, or fails it @@ -1025,6 +1027,31 @@ year. The service starts one call for a run it created, as for a new household report, and the function claims and calculates it as it would a new report's run. +A call can instead name an extra calculation of a household report run's +simulation run, with the `household_run_calculation_id` keyword argument, +and then takes that calculation's `HouseholdExecutionRequest`, whose +calculation ID is the calculation's. The service inserts the +`household_run_calculations` row pending, starts the call, and records its +ID (`POST /reports/{report_id}/runs/{report_run_id}/household-calculations`). +The function claims the row under its own Modal call ID, calculates the +request, and records the `HouseholdExecutionResult` as its `result`, or the +failure's one-line summary as its `error_message`, as for a household job: a +row another call holds, or one already finished, returns `deduplicated`, the +calculation's ID and its status, without calculating; any other error or +Modal's cancellation fails it with a summary naming only the error's type; +a pre-emption records nothing. + +API v1's revision that adds `household_run_variables` and +`household_run_calculations` must be applied in an environment before this +release deploys there: the service's `/ready` privilege check names both, +every household report side reads `household_run_variables`, and the +stuck-run sweep lists `household_run_calculations` on every pass. Between the +promotion of the Simulation Entrypoint and the move of the v2 default, the +entry may start the previous default's household function with the new +keyword, which that function does not take: the call fails before any claim +and the stuck-run sweep fails the row once it is ten minutes old. Nothing calls the +route until API v1 does. + The stuck-run sweep (`src/modal/run_sweep_app.py`) fails household jobs nothing will finish by the rule it applies to report runs and simulation runs (a household report run and its simulation runs are judged as any @@ -1033,8 +1060,8 @@ creation: a pending job with no call recorded ten minutes after its creation, a pending or running job once Modal reports its recorded call ended, and any job still unfinished 24 hours after its creation, whatever Modal reports. It judges simulation runs' cliff -results last, by the same rule, counting from a result's first claim or, -while it is pending, its creation. +results, then household runs' extra calculations, last, by the same rule, +counting from a row's first claim or, while it is pending, its creation. - Image: the CA store, the frozen `modal-simulation-image` dependency group and the source packages, without the bundle's datasets or the Stage 12 diff --git a/libs/policyengine-simulation-observability/src/policyengine_simulation_observability/log_records.py b/libs/policyengine-simulation-observability/src/policyengine_simulation_observability/log_records.py index 734f2e54a..d7f342664 100644 --- a/libs/policyengine-simulation-observability/src/policyengine_simulation_observability/log_records.py +++ b/libs/policyengine-simulation-observability/src/policyengine_simulation_observability/log_records.py @@ -25,6 +25,7 @@ DatabaseTable = Literal[ "cliff_impacts", "household_jobs", + "household_run_calculations", "report_runs", "reports", "simulation_runs", diff --git a/libs/policyengine-simulation-persistence/README.md b/libs/policyengine-simulation-persistence/README.md index 2cb3c3f86..d468109a6 100644 --- a/libs/policyengine-simulation-persistence/README.md +++ b/libs/policyengine-simulation-persistence/README.md @@ -51,7 +51,14 @@ referenced row before adding the row that names it. service creates rows in: `Simulation`, `Report`, `SimulationRun`, `ReportRun`, `BudgetWindowRun`, `HouseholdJob` and `CliffImpact`, for `simulations`, `reports`, `simulation_runs`, `report_runs`, `budget_window_runs`, -`household_jobs` and `cliff_impacts`. +`household_jobs` and `cliff_impacts`. `household_run_tables.py` models the +two tables of household runs, `HouseholdRunVariables` and +`HouseholdRunCalculation`, for `household_run_variables` (the variables a +household report's simulation run calculates) and +`household_run_calculations` (a run's extra calculations of other variables, +or across axes). `table_values.py` holds the column limits and run states the +models use, such as `MODAL_CALL_ID_LENGTH` and `SimulationStatus`; +`tables.py` re-exports them. They derive from `ServiceBase` in `orm_base.py`, and their tables are in `service_metadata`, which names the `public` schema so writes reach those tables whatever the role's `search_path`. @@ -435,7 +442,9 @@ the read-only input models' tables in another disposable database and requires every column they name to exist in the Public API's table with the same type and nullability; their other columns, defaults, constraints and indexes are the Public API's alone. `test_service_writes` creates a row in every table -the service writes, as the service's role; `test_modal_worker_writes`, as the +the service writes but the two household run tables, as the service's role, +and `test_household_run_records` writes those two as that role; +`test_modal_worker_writes`, as the Modal worker role, checks the role's privileges, records a run's state in each run table, inserts a row in every result table and reads back that a `None` JSON result is SQL `NULL`. Another test, outside the rule, requires the modelled @@ -489,11 +498,12 @@ uv run pytest tests/ -m public_api_schema `SERVICE_TABLE_PRIVILEGES` lists the table privileges the service's role needs: `SELECT` and `INSERT` on the tables it creates rows in (`simulations`, `reports`, `simulation_runs`, `report_runs`, -`budget_window_runs`, `household_jobs` and `cliff_impacts`, a simulation -run's cliff calculations), and `SELECT` on the policy, dynamic, household and -catalog tables a run reads. `SERVICE_UPDATABLE_COLUMNS` lists the columns it -may `UPDATE` on `simulation_runs`, `report_runs`, `household_jobs` and -`cliff_impacts`: `status`, `modal_call_id`, `error_message`, `completed_at` +`budget_window_runs`, `household_jobs`, `cliff_impacts`, a simulation +run's cliff calculations, `household_run_variables` and +`household_run_calculations`), and `SELECT` on the policy, dynamic, household +and catalog tables a run reads. `SERVICE_UPDATABLE_COLUMNS` lists the columns +it may `UPDATE` on `simulation_runs`, `report_runs`, `household_jobs`, +`cliff_impacts` and `household_run_calculations`: `status`, `modal_call_id`, `error_message`, `completed_at` and `updated_at`, to record a Modal call's ID once Modal accepts the call, or to fail the run when Modal refuses it. On `budget_window_runs` it lists `status`, `error_message`, `completed_at` and `updated_at`, to fail a window @@ -503,15 +513,16 @@ refuses any other change to a run. The Public API's privilege manifest grants them all. `MODAL_WORKER_TABLE_PRIVILEGES` and `MODAL_WORKER_UPDATABLE_COLUMNS` list what -the Modal worker role needs: `SELECT` on the four run tables and -`cliff_impacts`, `SELECT` and `INSERT` on every result table, because a +the Modal worker role needs: `SELECT` on the four run tables, +`cliff_impacts`, `household_run_variables` and `household_run_calculations`, +`SELECT` and `INSERT` on every result table, because a session's insert reads the row's server defaults back, and `UPDATE` of each -run's and cliff calculation's state (`status`, `modal_call_id`, +run's, cliff calculation's and extra calculation's state (`status`, `modal_call_id`, `error_message`, `started_at`, `completed_at` and `updated_at`; a budget-window run has no call of its own) and of the results its own row holds: a report run's `spm_provenance` and `data_version`, a simulation run's output file and -`household_result`, a household job's `result`, and a cliff calculation's -`cliff_gap` and `cliff_share`. A report run's cliff impact is its two +`household_result`, a household job's `result`, a cliff calculation's +`cliff_gap` and `cliff_share`, and an extra calculation's `result`. A report run's cliff impact is its two simulation runs' cliff results. API v1's manifest grants these privileges; `test_modal_worker_writes` checks that in CI. @@ -545,8 +556,10 @@ rule's proof among them needs no database, and the others need one the Public API's own v2 migration chain built, with the privileges its manifest declares granted: set `PUBLIC_API_SCHEMA_DATABASE_URL` to that database's superuser URL. -`test_service_writes` creates a row in every table the service writes as the -service's role, and `test_modal_worker_writes` writes the Modal worker role's +`test_service_writes` creates a row in every table the service writes but the +two household run tables as the service's role, `test_household_run_records` +writes those two as that role, and `test_modal_worker_writes` writes the Modal +worker role's runs and results as that role, each rolling its transaction back; neither role needs a login there, since the superuser takes each role for the transaction. The comparison in `test_public_api_schema` also needs diff --git a/libs/policyengine-simulation-persistence/public-api-commit b/libs/policyengine-simulation-persistence/public-api-commit index b46e921b9..6ad454b46 100644 --- a/libs/policyengine-simulation-persistence/public-api-commit +++ b/libs/policyengine-simulation-persistence/public-api-commit @@ -1 +1 @@ -57202c04991ec4239ef135dc80d1e223a9e6b076 +cb8200d2e8279a5116957c3532d6392071a0e723 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 a75546191..dfde5c85f 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/__init__.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/__init__.py @@ -59,6 +59,7 @@ EconomyRecordReferenceError, RunVersions, SimulationChoice, + fail_unstarted_household_run_calculation, fail_unstarted_report_run, fail_unstarted_simulation_run, read_dataset, @@ -66,6 +67,7 @@ read_local_area_dataset, read_model_id, read_region, + record_household_run_calculation_call, record_report_run_call, record_simulation_run_call, ) @@ -119,6 +121,26 @@ HouseholdReportInputs, HouseholdReportStore, ) +from policyengine_simulation_persistence.household_run_calculation_store import ( + HouseholdRunCalculationStore, + ReportWithRun, +) +from policyengine_simulation_persistence.household_run_records import ( + HOUSEHOLD_CALCULATION_KEY_VERSION, + FoundHouseholdRunCalculation, + NewHouseholdRunCalculation, + SideRun, + StoredReportRun, + find_or_insert_household_run_calculations, + household_calculation_key, + read_report_run, + record_household_run_variables, + recorded_variables, +) +from policyengine_simulation_persistence.household_run_tables import ( + HouseholdRunCalculation, + HouseholdRunVariables, +) from policyengine_simulation_persistence.input_tables import ( Dataset, Dynamic, @@ -237,6 +259,7 @@ ) __all__ = [ + "HOUSEHOLD_CALCULATION_KEY_VERSION", "HOUSEHOLD_REPORT_TYPE", "KEY_VERSION", "LATEST_YEAR", @@ -279,6 +302,7 @@ "FoundEconomyReport", "FoundEconomySimulation", "FoundHouseholdReport", + "FoundHouseholdRunCalculation", "FoundReportRerun", "FoundReportRun", "FoundReportWithoutRun", @@ -298,6 +322,9 @@ "HouseholdReportInputs", "HouseholdReportStore", "HouseholdRerunSide", + "HouseholdRunCalculation", + "HouseholdRunCalculationStore", + "HouseholdRunVariables", "HouseholdSimulationDefinition", "Inequality", "InputBase", @@ -317,6 +344,7 @@ "MissingPolicyParametersError", "NewHouseholdJob", "NewHouseholdReportRerun", + "NewHouseholdRunCalculation", "NewReportRerun", "NewSimulationRerun", "NewWindowRerun", @@ -339,6 +367,7 @@ "ReportRunStatus", "ReportSide", "ReportSideError", + "ReportWithRun", "RerunRecordDeletedError", "RerunSide", "ResultBase", @@ -347,6 +376,7 @@ "SharedRowNotSettledError", "SideDefinition", "SideRefusal", + "SideRun", "Simulation", "SimulationChoice", "SimulationDefinition", @@ -357,6 +387,7 @@ "SimulationStatus", "SimulationType", "StoredHousehold", + "StoredReportRun", "TaxBenefitModel", "TaxBenefitModelVersion", "UKAreaType", @@ -381,6 +412,7 @@ "definition_key", "dispose_session_factory", "fail_unstarted_household_job", + "fail_unstarted_household_run_calculation", "fail_unstarted_report_run", "fail_unstarted_simulation_run", "find_joinable_report_run", @@ -392,12 +424,14 @@ "find_or_create_household_report", "find_or_create_household_report_without_run", "find_or_insert_cliff_calculations", + "find_or_insert_household_run_calculations", "find_or_insert_report", "find_or_insert_report_run", "find_or_insert_report_run_cliffs", "find_or_insert_simulation", "find_or_insert_simulation_run", "find_or_insert_simulation_runs", + "household_calculation_key", "input_metadata", "insert_household_job", "insert_household_report_rerun", @@ -421,12 +455,16 @@ "read_policy_reform", "read_region", "read_report_definition", + "read_report_run", "read_simulation_definition", "read_simulation_reform", "read_stored_household", "record_household_call", + "record_household_run_calculation_call", + "record_household_run_variables", "record_report_run_call", "record_simulation_run_call", + "recorded_variables", "referenced_metadata", "result_metadata", "service_metadata", diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/access.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/access.py index b8015b1d8..dd47a1640 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/access.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/access.py @@ -35,8 +35,9 @@ _READ: Final = frozenset({"SELECT"}) # The service creates simulations, reports, their runs, budget windows' -# calculations, household jobs and simulation runs' cliff calculations, and -# reads the policy, dynamic, household and catalog rows a run needs. +# calculations, household jobs, simulation runs' cliff calculations, and +# household runs' variable lists and extra calculations, and reads the +# policy, dynamic, household and catalog rows a run needs. SERVICE_TABLE_PRIVILEGES: Final[Mapping[str, frozenset[str]]] = MappingProxyType( { "simulations": _CREATE, @@ -46,6 +47,8 @@ "budget_window_runs": _CREATE, "household_jobs": _CREATE, "cliff_impacts": _CREATE, + "household_run_variables": _CREATE, + "household_run_calculations": _CREATE, "policies": _READ, "households": _READ, "tax_benefit_models": _READ, @@ -79,6 +82,7 @@ "household_jobs": _CALL_START, "budget_window_runs": _WINDOW_FAILURE, "cliff_impacts": _CALL_START, + "household_run_calculations": _CALL_START, } ) @@ -95,11 +99,12 @@ } ) # The v2 Modal coordinators, workers, household functions and stuck-run sweep -# read the runs and cliff calculations they were given and insert their results, -# once each. A session's insert of a result also reads the row's server defaults -# back. A cliff calculation's result is in its own row. Each deploy also -# deletes the finished jobs of households given in the request whose versions -# it replaced. +# read the runs, cliff calculations and household runs' extra calculations they +# were given and insert their results, once each. A session's insert of a +# result also reads the row's server defaults back. A cliff calculation's or +# extra calculation's result is in its own row. A household function reads the +# variables each run it calculates records. Each deploy also deletes the +# finished jobs of households given in the request whose versions it replaced. MODAL_WORKER_TABLE_PRIVILEGES: Final[Mapping[str, frozenset[str]]] = MappingProxyType( { "report_runs": _READ, @@ -107,11 +112,14 @@ "household_jobs": _READ | {"DELETE"}, "budget_window_runs": _READ, "cliff_impacts": _READ, + "household_run_variables": _READ, + "household_run_calculations": _READ, **dict.fromkeys(RESULT_TABLE_NAMES, _CREATE), } ) -# The columns the Modal worker role may UPDATE, by table: each run's and cliff -# calculation's state and the results its own row holds. A budget-window run +# The columns the Modal worker role may UPDATE, by table: each run's, cliff +# calculation's and extra calculation's state and the results its own row +# holds. A budget-window run # has no Modal call of its own; its years' coordinators record its status, # failure and times. MODAL_WORKER_UPDATABLE_COLUMNS: Final[Mapping[str, frozenset[str]]] = MappingProxyType( @@ -122,6 +130,7 @@ "household_jobs": _RUN_STATE | {"result"}, "budget_window_runs": _RUN_STATE - {"modal_call_id"}, "cliff_impacts": _RUN_STATE | {"cliff_gap", "cliff_share"}, + "household_run_calculations": _RUN_STATE | {"result"}, } ) 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 926127238..c94731b39 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 @@ -66,6 +66,9 @@ household_simulation_run_row, insert_household_simulation_run, ) +from policyengine_simulation_persistence.household_run_records import ( + record_household_run_variables, +) from policyengine_simulation_persistence.keyed_economy_records import ( find_or_insert_report_run_cliffs, find_or_insert_report_run_on_sides, @@ -102,7 +105,7 @@ ) if TYPE_CHECKING: - from collections.abc import Iterator, Mapping + from collections.abc import Iterable, Iterator, Mapping from uuid import UUID from sqlalchemy.orm import InstrumentedAttribute, Session @@ -224,7 +227,9 @@ class NewHouseholdReportRerun: simulation's run in the report's ``year`` on the re-run's versions, or inserts one with the ID it proposes. ``forced`` makes it an extra run, on a new run of each side, all marked forced. ``reform`` is None for a - report of the baseline alone. + report of the baseline alone. ``variables`` lists the variables each + simulation run the re-run inserts calculates, or is None for every + variable. """ report_id: UUID @@ -235,6 +240,7 @@ class NewHouseholdReportRerun: baseline: HouseholdRerunSide reform: HouseholdRerunSide | None forced: bool = False + variables: tuple[str, ...] | None = None @property def named_sides(self) -> dict[Side, HouseholdRerunSide]: @@ -535,9 +541,10 @@ def insert_household_report_rerun( every re-run of a household report without keys is (interim answer B), takes no lock and is never refused: its report run and a new run of each side are marked forced, which nothing joins and the - one-unfailed-run indexes leave out. Return the run and whether this call - created it, which only then needs its call. Raise as - ``insert_report_rerun`` does. + one-unfailed-run indexes leave out. Each simulation run it inserted + records the re-run's ``variables``, when it lists them. Return the run + and whether this call created it, which only then needs its call. Raise + as ``insert_report_rerun`` does. """ versions = rerun.versions row = _rerun_report_run_row( @@ -566,8 +573,10 @@ def insert_household_report_rerun( versions=versions, forced=True, ) - return _insert_forced_report_run(session, row, sides) - found, _ = find_or_insert_report_run_on_sides( + forced_run = _insert_forced_report_run(session, row, sides) + _record_variables(session, rerun, sides.values()) + return forced_run + found, side_runs = find_or_insert_report_run_on_sides( session, row, { @@ -581,9 +590,35 @@ def insert_household_report_rerun( for name, side in sides.items() }, ) + _record_variables( + session, + rerun, + [ + HouseholdRerunSide( + simulation_id=sides[name].simulation_id, simulation_run_id=run.id + ) + for name, run in side_runs.items() + if run.inserted + ], + ) return found +def _record_variables( + session: Session, + rerun: NewHouseholdReportRerun, + inserted: Iterable[HouseholdRerunSide], +) -> None: + """Record the re-run's list on each simulation run it inserted, if it lists one.""" + if rerun.variables is None: + return + record_household_run_variables( + session, + {side.simulation_run_id: side.simulation_id for side in inserted}, + rerun.variables, + ) + + def insert_simulation_rerun( session: Session, rerun: NewSimulationRerun ) -> FoundSimulationRun: diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/economy_run_records.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/economy_run_records.py index 8a01069a3..4e062c837 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/economy_run_records.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/economy_run_records.py @@ -44,6 +44,10 @@ ) from sqlalchemy.exc import IntegrityError +from policyengine_simulation_persistence.household_run_tables import ( + HouseholdRunCalculation, + HouseholdRunVariables, +) from policyengine_simulation_persistence.input_tables import ( MODEL_NAME_PREFIX, UK_AREA_REGION_TYPES, @@ -69,8 +73,9 @@ from sqlalchemy import ColumnElement from sqlalchemy.orm import Session -# The classes whose rows a Modal call calculates: runs and cliff calculations. -type RunModel = type[SimulationRun | ReportRun | CliffImpact] +# The classes whose rows a Modal call calculates: runs, cliff calculations and +# household runs' extra calculations. +type RunModel = type[SimulationRun | ReportRun | CliffImpact | HouseholdRunCalculation] # PostgreSQL's SQLSTATE for a row naming one that does not exist. FOREIGN_KEY_VIOLATION: Final = "23503" @@ -92,6 +97,8 @@ ReportRun, BudgetWindowRun, CliffImpact, + HouseholdRunVariables, + HouseholdRunCalculation, ) for constraint in model.__table_args__ if isinstance(constraint, ForeignKeyConstraint) @@ -373,6 +380,20 @@ def record_cliff_calculation_call( return None if status is None else SimulationStatus(status) +def record_household_run_calculation_call( + session: Session, *, household_run_calculation_id: UUID, modal_call_id: str +) -> SimulationStatus | None: + """Record an extra calculation's Modal call ID while it is pending with none. + + Return its status afterwards, or None when there is no such row. One + the household function has claimed already keeps its claim. + """ + status = _record_call( + session, HouseholdRunCalculation, household_run_calculation_id, modal_call_id + ) + return None if status is None else SimulationStatus(status) + + def _record_call( session: Session, model: RunModel, run_id: UUID, modal_call_id: str ) -> str | None: @@ -435,6 +456,20 @@ def fail_unstarted_cliff_calculation( return _fail_unstarted(session, CliffImpact, cliff_result_id, error_message) +def fail_unstarted_household_run_calculation( + session: Session, *, household_run_calculation_id: UUID, error_message: str +) -> bool: + """Fail an extra calculation at once while it is pending with no Modal call ID. + + Return whether it was failed: one a call has been recorded for, or one + the household function has claimed, is left as it is. A failed one never + counts, so the next identical request inserts another. + """ + return _fail_unstarted( + session, HouseholdRunCalculation, household_run_calculation_id, error_message + ) + + def _fail_unstarted( session: Session, model: RunModel, run_id: UUID, error_message: str ) -> bool: 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 f97a80874..7b16969ef 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 @@ -15,7 +15,7 @@ from __future__ import annotations from dataclasses import dataclass -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Self from policyengine_simulation_persistence.economy_inputs import SIDE_ERRORS from policyengine_simulation_persistence.economy_rerun_records import ( @@ -125,7 +125,7 @@ def from_session_factory( session_factory: sessionmaker[Session], *, statement_timeout_milliseconds: int, - ) -> HouseholdReportStore: + ) -> Self: """Use ``session_factory``, bounding each statement to the given time.""" return cls( bounded_transactions( diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/household_run_calculation_store.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/household_run_calculation_store.py new file mode 100644 index 000000000..3272740f5 --- /dev/null +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/household_run_calculation_store.py @@ -0,0 +1,119 @@ +"""The store of household runs' extra calculations, each operation its own transaction. + +The Simulation Entrypoint starts an extra calculation of a household report +run in three steps, each its own transaction, with the household function's +calls started between them: it reads the report and the run together, finds +or inserts each side's calculation, then records the call on each it +inserted or fails it. ``HouseholdRunCalculationStore`` runs the reads and +writes of ``household_run_records`` and ``economy_run_records``' calculation +writes that way, as ``HouseholdReportStore`` does a household report's. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from policyengine_simulation_persistence.economy_run_records import ( + fail_unstarted_household_run_calculation, + record_household_run_calculation_call, + references_checked, +) +from policyengine_simulation_persistence.household_report_store import ( + HouseholdReportStore, +) +from policyengine_simulation_persistence.household_run_records import ( + find_or_insert_household_run_calculations, + read_report_run, +) +from policyengine_simulation_persistence.rerun_definitions import ( + read_report_definition, +) + +if TYPE_CHECKING: + from collections.abc import Sequence + from uuid import UUID + + from sqlalchemy.orm import Session + + from policyengine_simulation_persistence.household_run_records import ( + FoundHouseholdRunCalculation, + NewHouseholdRunCalculation, + StoredReportRun, + ) + from policyengine_simulation_persistence.rerun_definitions import ( + ReportDefinition, + ) + from policyengine_simulation_persistence.tables import SimulationStatus + + +@dataclass(frozen=True) +class ReportWithRun: + """A stored report and one of its runs, read in one transaction. + + ``definition`` is None when there is no such report, and ``run`` is None + then too, or when the report has no run of that ID. + """ + + definition: ReportDefinition | None + run: StoredReportRun | None + + +class HouseholdRunCalculationStore(HouseholdReportStore): + """Read household report runs and write their extra calculations.""" + + def read_report_with_run( + self, report_id: UUID, report_run_id: UUID + ) -> ReportWithRun: + """Return the stored report and its run ``report_run_id``, read together.""" + with self._transaction() as session: + definition = read_report_definition(session, report_id) + if definition is None: + return ReportWithRun(definition=None, run=None) + return ReportWithRun( + definition=definition, + run=read_report_run( + session, report_id=report_id, report_run_id=report_run_id + ), + ) + + def find_or_create_calculations( + self, proposed: Sequence[NewHouseholdRunCalculation] + ) -> dict[UUID, FoundHouseholdRunCalculation]: + """Find each run's calculation of its request, or insert it pending. + + See ``find_or_insert_household_run_calculations``. Raise + EconomyRecordReferenceError when a run or its simulation was deleted + since the read, SharedRowNotSettledError when a calculation keeps + failing between a lookup's insert and its read, and + EconomyRecordOutcomeUnknownError when the commit fails after the rows + were inserted. + """ + + def insert_rows(session: Session) -> dict[UUID, FoundHouseholdRunCalculation]: + with references_checked(): + return find_or_insert_household_run_calculations(session, proposed) + + return self._create(insert_rows) + + def record_calculation_call( + self, calculation_id: UUID, modal_call_id: str + ) -> SimulationStatus | None: + """Record the calculation's call ID while it is pending with none.""" + with self._transaction() as session: + return record_household_run_calculation_call( + session, + household_run_calculation_id=calculation_id, + modal_call_id=modal_call_id, + ) + + def fail_unstarted_calculation( + self, calculation_id: UUID, error_message: str + ) -> bool: + """Fail the calculation while it is pending with no call ID.""" + with self._transaction() as session: + return fail_unstarted_household_run_calculation( + session, + household_run_calculation_id=calculation_id, + error_message=error_message, + ) diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/household_run_records.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/household_run_records.py new file mode 100644 index 000000000..001a3c09a --- /dev/null +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/household_run_records.py @@ -0,0 +1,250 @@ +"""The variables a household report's runs calculate, and their extra calculations. + +A household report's create or re-run may list the variables its runs +calculate. Each simulation run it inserts records the list, sorted, in +``household_run_variables`` (``record_household_run_variables``), in the +transaction that inserted the run; a run it joins keeps its own list, and a +run with none calculates every variable. Identical requests share runs, so +the household function calculates a run with the list it records. + +An extra calculation of a household run calculates other variables, or the +household across axes, under the run's household, policy, dynamic, year and +versions (``household_run_calculations``). A request finds each run's +calculation of the same variables and axes that hasn't failed, or inserts +one pending with no Modal call (``find_or_insert_household_run_calculations``), +by a key of the two (``household_calculation_key``); the service then starts +one household function call for each it inserted. ``read_report_run`` reads +the report run the calculations are of. +""" + +from __future__ import annotations + +import hashlib +import json +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Final + +from sqlalchemy import insert, select +from sqlalchemy.orm import aliased + +from policyengine_simulation_persistence.economy_run_records import RunVersions +from policyengine_simulation_persistence.household_run_tables import ( + HouseholdRunVariables, +) +from policyengine_simulation_persistence.shared_rows import ( + find_or_insert_household_run_calculation, +) +from policyengine_simulation_persistence.tables import ( + ReportRun, + ReportRunStatus, + SimulationRun, + SimulationStatus, + SimulationType, +) + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + from uuid import UUID + + from sqlalchemy.orm import Session + +# The format of ``household_calculation_key``; a new format gets a new number. +HOUSEHOLD_CALCULATION_KEY_VERSION: Final = 1 + + +def recorded_variables(variables: Sequence[str]) -> list[str]: + """Return a list of variables as a row records it: sorted, each name once.""" + return sorted(set(variables)) + + +def record_household_run_variables( + session: Session, runs: Mapping[UUID, UUID], variables: Sequence[str] +) -> None: + """Record ``variables``, sorted, as what each run in ``runs`` calculates. + + ``runs`` maps each household simulation run this transaction inserted to + its simulation. The rows are inserted in run ID order. + """ + if not runs: + return + listed = recorded_variables(variables) + session.execute( + insert(HouseholdRunVariables), + [ + { + "simulation_run_id": run_id, + "simulation_id": runs[run_id], + "simulation_type": SimulationType.HOUSEHOLD, + "variables": listed, + } + for run_id in sorted(runs) + ], + ) + + +def household_calculation_key( + variables: Sequence[str], axes: Sequence[Any] | None +) -> str: + """Return the key of an extra calculation of these variables and axes. + + It is the SHA-256, in lowercase hexadecimal, of the two as canonical + JSON, the variables sorted and each named once (format + ``HOUSEHOLD_CALCULATION_KEY_VERSION``). + """ + canonical = json.dumps( + {"axes": axes, "variables": recorded_variables(variables)}, + sort_keys=True, + separators=(",", ":"), + ) + return hashlib.sha256(canonical.encode()).hexdigest() + + +@dataclass(frozen=True) +class NewHouseholdRunCalculation: + """An extra calculation of a household run a request proposes. + + ``id`` is used only if the request inserts it. ``axes`` is the + household contract's axes as JSON, or None for the household as stored. + """ + + id: UUID + simulation_run_id: UUID + simulation_id: UUID + variables: Sequence[str] + axes: list[Any] | None + + +@dataclass(frozen=True) +class FoundHouseholdRunCalculation: + """A household run's extra calculation a lookup found or inserted.""" + + id: UUID + simulation_run_id: UUID + inserted: bool + status: SimulationStatus + + +def find_or_insert_household_run_calculations( + session: Session, proposed: Sequence[NewHouseholdRunCalculation] +) -> dict[UUID, FoundHouseholdRunCalculation]: + """Return each run's extra calculation of its request, inserting those it lacks. + + A run's calculation of the same variables and axes that hasn't failed, + pending, running or succeeded, is found; otherwise the proposed one is + inserted pending with no Modal call. A failed one never counts. The + lookups go in simulation run ID order, so two transactions never wait + for each other in opposite orders. Return the calculations by simulation + run ID; ``proposed`` names each run once. + """ + by_run = {calculation.simulation_run_id: calculation for calculation in proposed} + if len(by_run) != len(proposed): + msg = "a request proposes one extra calculation per simulation run" + raise ValueError(msg) + found: dict[UUID, FoundHouseholdRunCalculation] = {} + for simulation_run_id in sorted(by_run): + calculation = by_run[simulation_run_id] + row_id, inserted, status = find_or_insert_household_run_calculation( + session, + { + "id": calculation.id, + "simulation_run_id": simulation_run_id, + "simulation_id": calculation.simulation_id, + "simulation_type": SimulationType.HOUSEHOLD, + "variables": recorded_variables(calculation.variables), + "axes": calculation.axes, + "key_version": HOUSEHOLD_CALCULATION_KEY_VERSION, + "calculation_key": household_calculation_key( + calculation.variables, calculation.axes + ), + "status": SimulationStatus.PENDING, + "modal_call_id": None, + }, + ) + found[simulation_run_id] = FoundHouseholdRunCalculation( + id=row_id, + simulation_run_id=simulation_run_id, + inserted=inserted, + status=status, + ) + return found + + +@dataclass(frozen=True) +class SideRun: + """A report side's simulation and the simulation run a report run names.""" + + simulation_id: UUID + simulation_run_id: UUID + + +@dataclass(frozen=True) +class StoredReportRun: + """A stored report run, its versions and each side's simulation run. + + ``reform`` is None for a report of the baseline alone, and ``baseline`` + for a run that names no baseline run. + """ + + id: UUID + report_id: UUID + status: ReportRunStatus + versions: RunVersions + baseline: SideRun | None + reform: SideRun | None + + +def read_report_run( + session: Session, *, report_id: UUID, report_run_id: UUID +) -> StoredReportRun | None: + """Return the report's run ``report_run_id``, or None when the report has none.""" + baseline = aliased(SimulationRun, name="baseline_run") + reform = aliased(SimulationRun, name="reform_run") + row = session.execute( + select( + ReportRun.id, + ReportRun.report_id, + ReportRun.status, + ReportRun.country_package_version, + ReportRun.policyengine_version, + baseline.id.label("baseline_run_id"), + baseline.simulation_id.label("baseline_simulation_id"), + reform.id.label("reform_run_id"), + reform.simulation_id.label("reform_simulation_id"), + ) + .outerjoin(baseline, baseline.id == ReportRun.baseline_simulation_run_id) + .outerjoin(reform, reform.id == ReportRun.reform_simulation_run_id) + .where(ReportRun.id == report_run_id, ReportRun.report_id == report_id) + ).one_or_none() + if row is None: + return None + return StoredReportRun( + id=row.id, + report_id=row.report_id, + status=ReportRunStatus(row.status), + versions=RunVersions( + country_package_version=row.country_package_version, + policyengine_version=row.policyengine_version, + ), + baseline=_side_run(row.baseline_simulation_id, row.baseline_run_id), + reform=_side_run(row.reform_simulation_id, row.reform_run_id), + ) + + +def _side_run(simulation_id: UUID | None, run_id: UUID | None) -> SideRun | None: + if simulation_id is None or run_id is None: + return None + return SideRun(simulation_id=simulation_id, simulation_run_id=run_id) + + +__all__ = [ + "HOUSEHOLD_CALCULATION_KEY_VERSION", + "FoundHouseholdRunCalculation", + "NewHouseholdRunCalculation", + "SideRun", + "StoredReportRun", + "find_or_insert_household_run_calculations", + "household_calculation_key", + "read_report_run", + "record_household_run_variables", + "recorded_variables", +] diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/household_run_tables.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/household_run_tables.py new file mode 100644 index 000000000..f66948842 --- /dev/null +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/household_run_tables.py @@ -0,0 +1,196 @@ +"""Models of API v1's two tables of a household simulation run's variables. + +``household_run_variables`` records the variables a household report's run +calculates, and ``household_run_calculations`` a household run's extra +calculations, each of other variables or axes. API v1's v2 migration chain +creates both (D2 · 3a); these classes describe them, as ``tables`` describes +the others, and live apart from it only for its length. Each row names its +run together with the run's simulation, and that simulation together with +its type, which must be ``household``; deleting the run or the simulation +deletes the row. +""" + +from __future__ import annotations + +from datetime import datetime # noqa: TC003 # SQLAlchemy reads Mapped annotations +from typing import TYPE_CHECKING, Any, ClassVar, Final +from uuid import UUID # noqa: TC003 # SQLAlchemy reads Mapped annotations at run time + +from sqlalchemy import ( + JSON, + CheckConstraint, + ForeignKeyConstraint, + Index, + Integer, + PrimaryKeyConstraint, + String, + Uuid, + text, +) +from sqlalchemy.orm import Mapped, mapped_column + +from policyengine_simulation_persistence.orm_base import ( + TABLE_SCHEMA, + ServiceBase, + enum_type, + identifier_column, + optional_timestamp_column, + server_timestamp_column, +) +from policyengine_simulation_persistence.tables import ( + DEFINITION_KEY_LENGTH, + MODAL_CALL_ID_LENGTH, + SimulationStatus, + SimulationType, +) + +if TYPE_CHECKING: + from sqlalchemy.orm import MappedColumn + +# The extra calculations a request may join: a failed one never counts. +UNFAILED_HOUSEHOLD_CALCULATIONS: Final = "status <> 'failed'" + + +def _household_only_keys( + table_name: str, +) -> tuple[ForeignKeyConstraint | CheckConstraint, ...]: + """Return the keys and check that hold a row to a household simulation's run.""" + return ( + ForeignKeyConstraint( + ["simulation_run_id", "simulation_id"], + [ + f"{TABLE_SCHEMA}.simulation_runs.id", + f"{TABLE_SCHEMA}.simulation_runs.simulation_id", + ], + name=f"fk_{table_name}_run", + ondelete="CASCADE", + ), + ForeignKeyConstraint( + ["simulation_id", "simulation_type"], + [ + f"{TABLE_SCHEMA}.simulations.id", + f"{TABLE_SCHEMA}.simulations.simulation_type", + ], + name=f"fk_{table_name}_simulation", + ondelete="CASCADE", + ), + CheckConstraint( + "simulation_type = 'household'", name=f"ck_{table_name}_household" + ), + ) + + +def _variable_list_check(table_name: str) -> CheckConstraint: + """Require ``variables`` to be a JSON array of at least one name. + + API v1 creates the check on PostgreSQL alone, whose functions it uses. + """ + return CheckConstraint( + "CASE WHEN json_typeof(variables) = 'array' " + "THEN json_array_length(variables) > 0 ELSE false END", + name=f"ck_{table_name}_variables", + ).ddl_if(dialect="postgresql") + + +def _simulation_type_column() -> MappedColumn[SimulationType]: + """Return the row's simulation type, which its check holds to ``household``.""" + return mapped_column(enum_type(SimulationType, "v2_simulation_type")) + + +class HouseholdRunVariables(ServiceBase): + """The variables a household simulation run calculates, one row per run. + + The service records the names a household report's create or re-run + lists, sorted and each once, with each run it inserts. A household run + with no row calculates every variable. + """ + + __tablename__ = "household_run_variables" + __table_args__: ClassVar = ( + PrimaryKeyConstraint("simulation_run_id", name="pk_household_run_variables"), + *_household_only_keys("household_run_variables"), + _variable_list_check("household_run_variables"), + ) + + simulation_run_id: Mapped[UUID] = mapped_column(Uuid) + simulation_id: Mapped[UUID] = mapped_column(Uuid) + simulation_type: Mapped[SimulationType] = _simulation_type_column() + variables: Mapped[list[str]] = mapped_column(JSON) + created_at: Mapped[datetime] = server_timestamp_column() + + +class HouseholdRunCalculation(ServiceBase): + """One extra calculation of a household simulation run, and its result. + + ``variables`` are the sorted names to calculate, and ``axes`` the + variation, or SQL NULL for the household as stored; ``calculation_key`` + is the SHA-256 of the two, in the format ``key_version`` names. The + household, policy, dynamic, year and versions are the run's. As for a + cliff calculation, the service inserts it pending and records the Modal + call it starts, or fails it when Modal refuses the call; the household + function claims it under its call and records the calculated household + (``result``) or the failure. A run has at most one calculation of each + request that hasn't failed, so identical requests join it. + """ + + __tablename__ = "household_run_calculations" + __table_args__: ClassVar = ( + PrimaryKeyConstraint("id", name="pk_household_run_calculations"), + *_household_only_keys("household_run_calculations"), + _variable_list_check("household_run_calculations"), + CheckConstraint( + "axes IS NULL OR json_typeof(axes) = 'array'", + name="ck_household_run_calculations_axes", + ).ddl_if(dialect="postgresql"), + CheckConstraint( + "key_version > 0", name="ck_household_run_calculations_key_version" + ), + CheckConstraint( + "length(calculation_key) = 64 " + "AND ltrim(calculation_key, '0123456789abcdef') = ''", + name="ck_household_run_calculations_calculation_key", + ), + CheckConstraint( + "status NOT IN ('succeeded', 'failed') OR completed_at IS NOT NULL", + name="ck_household_run_calculations_finished_completion", + ), + CheckConstraint( + "(status = 'succeeded') = (result IS NOT NULL)", + name="ck_household_run_calculations_result_when_succeeded", + ), + Index("ix_household_run_calculations_simulation_run_id", "simulation_run_id"), + # For the stuck-run sweep, which judges a calculation by its age. + Index( + "ix_household_run_calculations_status_started_at", "status", "started_at" + ), + # One calculation of each request per run that hasn't failed: + # find-or-create's conflict target, so identical requests join one. + Index( + "uq_household_run_calculations_unfailed", + "simulation_run_id", + "key_version", + "calculation_key", + unique=True, + postgresql_where=text(UNFAILED_HOUSEHOLD_CALCULATIONS), + ), + ) + + id: Mapped[UUID] = identifier_column() + created_at: Mapped[datetime] = server_timestamp_column() + updated_at: Mapped[datetime] = server_timestamp_column() + simulation_run_id: Mapped[UUID] = mapped_column(Uuid) + simulation_id: Mapped[UUID] = mapped_column(Uuid) + simulation_type: Mapped[SimulationType] = _simulation_type_column() + variables: Mapped[list[str]] = mapped_column(JSON) + # None is written as SQL NULL, here and in ``result``. + axes: Mapped[list[Any] | None] = mapped_column(JSON(none_as_null=True)) + key_version: Mapped[int] = mapped_column(Integer) + calculation_key: Mapped[str] = mapped_column(String(DEFINITION_KEY_LENGTH)) + status: Mapped[SimulationStatus] = mapped_column( + enum_type(SimulationStatus, "v2_simulation_status") + ) + modal_call_id: Mapped[str | None] = mapped_column(String(MODAL_CALL_ID_LENGTH)) + error_message: Mapped[str | None] = mapped_column(String) + result: Mapped[dict[str, Any] | None] = mapped_column(JSON(none_as_null=True)) + started_at: Mapped[datetime | None] = optional_timestamp_column() + completed_at: Mapped[datetime | None] = optional_timestamp_column() 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 93e5338c5..31f2f64b4 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 @@ -17,7 +17,10 @@ found or inserted, then the report run naming them (``find_or_insert_report_run_on_sides``). A report run another request inserted after step 3 is joined, and the savepoint takes back this - request's simulation runs. + request's simulation runs; +5. for a request listing the variables to calculate, each simulation run it + inserted records the list (``record_household_run_variables``). A run it + joined keeps its own. A household simulation run may be another report run's, pending, running or succeeded: the household function waits for a run another call holds @@ -43,6 +46,9 @@ HOUSEHOLD_REPORT_TYPE, household_simulation_run_row, ) +from policyengine_simulation_persistence.household_run_records import ( + record_household_run_variables, +) from policyengine_simulation_persistence.keyed_economy_records import ( FoundReportWithoutRun, FoundSide, @@ -119,7 +125,9 @@ class KeyedHouseholdReport: ``reform`` is None exactly when the definition has no reform (a report of the baseline alone). The runs calculate on the catalog version - ``tax_benefit_model_version_id``. + ``tax_benefit_model_version_id``. ``variables`` lists the variables each + simulation run the request inserts calculates, or is None for every + variable; it is no part of the report's key. """ definition: HouseholdReportDefinition @@ -130,6 +138,7 @@ class KeyedHouseholdReport: tax_benefit_model_id: UUID tax_benefit_model_version_id: UUID versions: RunVersions + variables: tuple[str, ...] | None = None def __post_init__(self) -> None: """Refuse a reform side for a report without a reform, or none for one.""" @@ -210,6 +219,16 @@ def find_or_create_household_report( }, ) inserted = {found.id for found in runs.values() if found.inserted} + if request.variables is not None: + record_household_run_variables( + session, + { + found.id: simulation_ids[side] + for side, found in runs.items() + if found.inserted + }, + request.variables, + ) return _found(report.id, report.inserted, run, simulation_ids, inserted) diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/shared_rows.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/shared_rows.py index 581158561..0801ab53b 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/shared_rows.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/shared_rows.py @@ -13,7 +13,10 @@ - a budget-window run by report, catalog version and .py version, among window runs that haven't failed and aren't recalculations (answer 8); - a simulation run's cliff calculation (``CliffImpact``) by its run, among - calculations that haven't failed (answer 4b). + calculations that haven't failed (answer 4b); +- a household run's extra calculation (``HouseholdRunCalculation``) by its + run and the key of its variables and axes, among calculations that + haven't failed. Under READ COMMITTED an insert that conflicts with another transaction's uncommitted row waits until that transaction ends. Once it commits, the @@ -39,6 +42,9 @@ from sqlalchemy import Index, select from sqlalchemy.dialects.postgresql import insert as postgresql_insert +from policyengine_simulation_persistence.household_run_tables import ( + HouseholdRunCalculation, +) from policyengine_simulation_persistence.tables import ( BudgetWindowRun, CliffImpact, @@ -59,7 +65,13 @@ # The classes a lookup inserts into. type SharedRowModel = type[ - Simulation | Report | SimulationRun | ReportRun | BudgetWindowRun | CliffImpact + Simulation + | Report + | SimulationRun + | ReportRun + | BudgetWindowRun + | CliffImpact + | HouseholdRunCalculation ] # How many times a lookup inserts before giving up on a row that keeps @@ -439,6 +451,32 @@ def find_or_insert_side_cliffs( ) +_UNFAILED_HOUSEHOLD_RUN_CALCULATION: Final = _partial_index( + HouseholdRunCalculation, + "uq_household_run_calculations_unfailed", + (HouseholdRunCalculation.status != SimulationStatus.FAILED,), +) + + +def find_or_insert_household_run_calculation( + session: Session, values: Mapping[str, Any] +) -> tuple[UUID, bool, SimulationStatus]: + """Return a household run's extra calculation like ``values``, or insert it. + + ``values`` is the whole row, its run, key version and calculation key + included. A calculation of the run with the same key that hasn't + failed, pending, running or succeeded, is found instead. Return its ID, + whether this call inserted it, and its status. + """ + row, inserted = _find_or_insert( + session, + _UNFAILED_HOUSEHOLD_RUN_CALCULATION, + values, + (HouseholdRunCalculation.status,), + ) + return row.id, inserted, SimulationStatus(row.status) + + def _refuse_forced(values: Mapping[str, Any]) -> None: if values.get("forced"): msg = "a forced run is inserted directly: it never joins or is joined" diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/table_values.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/table_values.py new file mode 100644 index 000000000..943a971d7 --- /dev/null +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/table_values.py @@ -0,0 +1,53 @@ +"""The values API v1's service tables store: column limits and run states. + +``tables`` re-exports every name, so imports from it keep working. +""" + +from __future__ import annotations + +from enum import StrEnum +from typing import Final + +VERSION_LENGTH: Final = 128 +# A report's budget window covers at most this many years. +MAX_BUDGET_WINDOW_YEARS: Final = 75 +LATEST_YEAR: Final = 2200 +MODAL_CALL_ID_LENGTH: Final = 255 +OUTPUT_URI_LENGTH: Final = 2048 +SHA256_LENGTH: Final = 64 +# A definition key is a SHA-256 in lowercase hexadecimal. +DEFINITION_KEY_LENGTH: Final = 64 + + +class SimulationType(StrEnum): + """Whether a simulation runs on one household or on a population dataset.""" + + HOUSEHOLD = "household" + ECONOMY = "economy" + + +class SimulationStatus(StrEnum): + """Lifecycle state of a simulation run.""" + + PENDING = "pending" + RUNNING = "running" + SUCCEEDED = "succeeded" + FAILED = "failed" + + +class ReportRunStatus(StrEnum): + """Lifecycle state of a report run or a budget window's calculation.""" + + PENDING = "pending" + RUNNING = "running" + SUCCEEDED = "succeeded" + FAILED = "failed" + + +class HouseholdJobStatus(StrEnum): + """Lifecycle state of a household job.""" + + PENDING = "pending" + RUNNING = "running" + SUCCEEDED = "succeeded" + FAILED = "failed" diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/tables.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/tables.py index 9f2fa7e03..c45032a3c 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/tables.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/tables.py @@ -10,8 +10,7 @@ from __future__ import annotations from datetime import datetime # noqa: TC003 # SQLAlchemy reads Mapped annotations -from enum import StrEnum -from typing import TYPE_CHECKING, Any, ClassVar, Final +from typing import TYPE_CHECKING, Any, ClassVar from uuid import UUID # noqa: TC003 # SQLAlchemy reads Mapped annotations at run time from sqlalchemy import ( @@ -50,54 +49,23 @@ ReferencedTaxBenefitModel, ReferencedTaxBenefitModelVersion, ) +from policyengine_simulation_persistence.table_values import ( + DEFINITION_KEY_LENGTH, + LATEST_YEAR, + MAX_BUDGET_WINDOW_YEARS, + MODAL_CALL_ID_LENGTH, + OUTPUT_URI_LENGTH, + SHA256_LENGTH, + VERSION_LENGTH, + HouseholdJobStatus, + ReportRunStatus, + SimulationStatus, + SimulationType, +) if TYPE_CHECKING: from sqlalchemy.orm import InstrumentedAttribute, MappedColumn -VERSION_LENGTH: Final = 128 -# A report's budget window covers at most this many years. -MAX_BUDGET_WINDOW_YEARS: Final = 75 -LATEST_YEAR: Final = 2200 -MODAL_CALL_ID_LENGTH: Final = 255 -OUTPUT_URI_LENGTH: Final = 2048 -SHA256_LENGTH: Final = 64 -# A definition key is a SHA-256 in lowercase hexadecimal. -DEFINITION_KEY_LENGTH: Final = 64 - - -class SimulationType(StrEnum): - """Whether a simulation runs on one household or on a population dataset.""" - - HOUSEHOLD = "household" - ECONOMY = "economy" - - -class SimulationStatus(StrEnum): - """Lifecycle state of a simulation run.""" - - PENDING = "pending" - RUNNING = "running" - SUCCEEDED = "succeeded" - FAILED = "failed" - - -class ReportRunStatus(StrEnum): - """Lifecycle state of a report run or a budget window's calculation.""" - - PENDING = "pending" - RUNNING = "running" - SUCCEEDED = "succeeded" - FAILED = "failed" - - -class HouseholdJobStatus(StrEnum): - """Lifecycle state of a household job.""" - - PENDING = "pending" - RUNNING = "running" - SUCCEEDED = "succeeded" - FAILED = "failed" - def _completion_required(table_name: str) -> CheckConstraint: """Require a succeeded or failed row to record when it completed.""" @@ -235,6 +203,8 @@ class Simulation(ServiceBase): "definition_key", name="uq_simulations_key_version_definition_key", ), + # Named with its type by a household run's variables and calculations. + UniqueConstraint("id", "simulation_type", name="uq_simulations_id_type"), Index( "ix_simulations_tax_benefit_model_version_id", "tax_benefit_model_version_id", @@ -413,6 +383,11 @@ class SimulationRun(ServiceBase): ), _completion_required("simulation_runs"), _year_between("simulation_runs", nullable=False), + # Named with its simulation by a household run's variables and + # calculations. + UniqueConstraint( + "id", "simulation_id", name="uq_simulation_runs_id_simulation" + ), Index( "ix_simulation_runs_current_output", "simulation_id", @@ -795,3 +770,20 @@ class CliffImpact(ServiceBase): service_metadata = ServiceBase.metadata + + +# The column limits and run states moved to table_values; their names stay +# importable here. +__all__ = [ + "DEFINITION_KEY_LENGTH", + "LATEST_YEAR", + "MAX_BUDGET_WINDOW_YEARS", + "MODAL_CALL_ID_LENGTH", + "OUTPUT_URI_LENGTH", + "SHA256_LENGTH", + "VERSION_LENGTH", + "HouseholdJobStatus", + "ReportRunStatus", + "SimulationStatus", + "SimulationType", +] diff --git a/libs/policyengine-simulation-persistence/tests/test_access.py b/libs/policyengine-simulation-persistence/tests/test_access.py index 4e8f5139f..c701bc701 100644 --- a/libs/policyengine-simulation-persistence/tests/test_access.py +++ b/libs/policyengine-simulation-persistence/tests/test_access.py @@ -43,6 +43,9 @@ "household_jobs", # Each simulation run's cliff calculations, which the service starts. "cliff_impacts", + # The variables a household run calculates, and its extra calculations. + "household_run_variables", + "household_run_calculations", ) READ_TABLES = ( "policies", @@ -90,6 +93,7 @@ def test_the_service_updates_only_the_call_state_of_each_run() -> None: "household_jobs": CALL_START_COLUMNS, "budget_window_runs": WINDOW_FAILURE_COLUMNS, "cliff_impacts": CALL_START_COLUMNS, + "household_run_calculations": CALL_START_COLUMNS, } @@ -107,6 +111,7 @@ def test_every_column_the_service_updates_is_modelled() -> None: "household_jobs", "budget_window_runs", "cliff_impacts", + "household_run_calculations", ) # A run's state, which the Modal call holding it records. RUN_STATE_COLUMNS = frozenset( @@ -129,6 +134,8 @@ def test_the_modal_worker_role_reads_its_runs_and_inserts_their_results() -> Non # Each deploy deletes the finished jobs of households given in the # request whose versions it replaced. "household_jobs": frozenset({"SELECT", "DELETE"}), + # A household function reads the variables its run calculates. + "household_run_variables": frozenset({"SELECT"}), # A session's insert also reads the row's server defaults back. **dict.fromkeys(result_tables, frozenset({"SELECT", "INSERT"})), } @@ -147,6 +154,7 @@ def test_the_modal_worker_role_updates_its_runs_state_and_results() -> None: "household_jobs": RUN_STATE_COLUMNS | {"result"}, "budget_window_runs": RUN_STATE_COLUMNS - {"modal_call_id"}, "cliff_impacts": RUN_STATE_COLUMNS | {"cliff_gap", "cliff_share"}, + "household_run_calculations": RUN_STATE_COLUMNS | {"result"}, } @@ -535,10 +543,10 @@ def test_only_the_public_schemas_columns_count(disposable_database): ] -def _granted_privileges(fixture: Path) -> list[tuple[str, ...]]: +def _left_out_grants(fixture: Path) -> set[tuple[str, ...]]: """Read `` []`` lines, skipping comments.""" lines = fixture.read_text(encoding="utf-8").splitlines() - return [tuple(line.split()) for line in lines if line and not line.startswith("#")] + return {tuple(line.split()) for line in lines if line and not line.startswith("#")} @pytest.mark.postgres @@ -557,18 +565,15 @@ def test_rule_proof_missing_privileges_reported( ): """Proof for rule sim.persistence.missing-privileges-reported. - The bad grants leave out ``INSERT`` on ``simulation_runs`` and ``UPDATE`` - on ``report_runs.modal_call_id``; the good ones hold every privilege the - service needs. + The role is granted every privilege the service needs but those its + fixture names, so a table the service starts using changes no fixture. + The bad fixture leaves out ``INSERT`` on ``simulation_runs`` and + ``UPDATE`` on ``report_runs.modal_call_id``; the good one leaves out none. """ + left_out = _left_out_grants(PROOF_FIXTURES / fixture_name) + assert left_out <= set(_required_grants()) _create_tables(disposable_database, SERVICE_TABLE_PRIVILEGES) - _grant( - disposable_database, - [ - _grant_statement(grant) - for grant in _granted_privileges(PROOF_FIXTURES / fixture_name) - ], - ) + _grant_every_required_privilege(disposable_database, except_for=left_out) assert _missing_privileges_as_the_service(disposable_database) == expected_missing diff --git a/libs/policyengine-simulation-persistence/tests/test_economy_sessions.py b/libs/policyengine-simulation-persistence/tests/test_economy_sessions.py index 3bffdd97e..952b8aebf 100644 --- a/libs/policyengine-simulation-persistence/tests/test_economy_sessions.py +++ b/libs/policyengine-simulation-persistence/tests/test_economy_sessions.py @@ -55,6 +55,8 @@ EconomyRequest, EconomyRunStore, EconomySimulationDefinition, + HouseholdRunCalculation, + HouseholdRunVariables, KeyedBudgetWindow, KeyedEconomyReport, KeyedEconomySimulation, @@ -514,6 +516,8 @@ def test_each_refused_key_is_known_by_its_table_and_column() -> None: ReportRun, BudgetWindowRun, CliffImpact, + HouseholdRunVariables, + HouseholdRunCalculation, ) for constraint in model.__table__.constraints if isinstance(constraint, ForeignKeyConstraint) diff --git a/libs/policyengine-simulation-persistence/tests/test_household_run_records.py b/libs/policyengine-simulation-persistence/tests/test_household_run_records.py new file mode 100644 index 000000000..dd613f120 --- /dev/null +++ b/libs/policyengine-simulation-persistence/tests/test_household_run_records.py @@ -0,0 +1,660 @@ +"""The variables a household report's runs calculate, and their extra calculations. + +A household report's create or re-run may list the variables its runs +calculate: each simulation run it inserts records the list, sorted, in +``household_run_variables``, and a run it joins keeps its own. An extra +calculation of a household run (``household_run_calculations``) is found, +or inserted pending, by the run and a key of its variables and axes; one +that failed never counts. 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 + +import hashlib +import json +from dataclasses import replace +from typing import TYPE_CHECKING, Any +from uuid import UUID, uuid4 + +import pytest +from conftest import ( + act_as_the_service, + in_session, + rolled_back_transaction, + session_factory_on, +) +from household_report_rows import insert_household_report_rows +from policyengine_simulation_persistence import ( + HOUSEHOLD_CALCULATION_KEY_VERSION, + FoundHouseholdRunCalculation, + HouseholdReportDefinition, + HouseholdRerunSide, + HouseholdRunCalculationStore, + KeyedHouseholdReport, + NewHouseholdReportRerun, + NewHouseholdRunCalculation, + ProposedSide, + ReportRunStatus, + RunVersions, + SideRun, + SimulationChoice, + SimulationStatus, + StoredReportRun, + fail_unstarted_household_run_calculation, + find_or_create_household_report, + find_or_insert_household_run_calculations, + household_calculation_key, + insert_household_report_rerun, + read_report_run, + record_household_run_calculation_call, +) +from public_api_rows import ( + insert_catalog_version, + insert_household, + insert_model, + insert_policy, +) +from sqlalchemy import text + +if TYPE_CHECKING: + from household_report_rows import StoredHouseholdReport + from public_api_rows import CatalogVersion + from sqlalchemy import Connection + +pytestmark = pytest.mark.public_api_schema + +STATEMENT_TIMEOUT_MILLISECONDS = 5_000 +VERSIONS = RunVersions(country_package_version="1.764.6", policyengine_version="6.17.1") +CURRENT_LAW = SimulationChoice(policy_id=None, dynamic_id=None) +DOCUMENT = { + "people": [ + { + "id": "you", + "values": {"age": 40}, + "memberships": {"household": "your household"}, + } + ], + "household": [{"id": "your household", "values": {}}], +} +# A request's list, unsorted, and the list each run it inserts records. +LISTED = ("household_net_income", "employment_income", "age") +RECORDED = ["age", "employment_income", "household_net_income"] +EARNINGS_AXES: list[Any] = [ + [{"name": "employment_income", "count": 5, "min": 0, "max": 100_000}] +] + + +def _catalog(connection: Connection) -> CatalogVersion: + return insert_catalog_version( + connection, + country="us", + model_id=insert_model(connection, "us"), + policyengine_version=VERSIONS.policyengine_version, + ) + + +def _household(connection: Connection) -> UUID: + return insert_household( + connection, country="us", default_year=2026, document=DOCUMENT + ) + + +def _keyed_report( # what the request names, then its list + catalog: CatalogVersion, + household_id: UUID, + *, + reform: SimulationChoice | None, + variables: tuple[str, ...] | None, +) -> KeyedHouseholdReport: + """Return a request's household report, with fresh IDs to propose.""" + return KeyedHouseholdReport( + definition=HouseholdReportDefinition( + country="us", + baseline=CURRENT_LAW, + reform=reform, + household_id=household_id, + year=2026, + ), + report_id=uuid4(), + run_id=uuid4(), + baseline=ProposedSide(simulation_id=uuid4(), simulation_run_id=uuid4()), + reform=( + None + if reform is None + else ProposedSide(simulation_id=uuid4(), simulation_run_id=uuid4()) + ), + tax_benefit_model_id=catalog.model_id, + tax_benefit_model_version_id=catalog.version_id, + versions=VERSIONS, + variables=variables, + ) + + +def _recorded_variables(connection: Connection) -> dict[UUID, list[str]]: + """Return each run's recorded list, by simulation run ID.""" + rows = connection.execute( + text("SELECT simulation_run_id, variables FROM public.household_run_variables") + ) + return {row.simulation_run_id: row.variables for row in rows} + + +def test_a_household_reports_list_is_recorded_sorted_for_each_run_it_inserts( + public_api_database_url, +) -> None: + with rolled_back_transaction(public_api_database_url) as connection: + catalog = _catalog(connection) + reform = SimulationChoice( + policy_id=insert_policy(connection, catalog), dynamic_id=None + ) + request = _keyed_report( + catalog, _household(connection), reform=reform, variables=LISTED + ) + act_as_the_service(connection) + + found = in_session(connection, find_or_create_household_report, request) + recorded = _recorded_variables(connection) + + assert found.reform is not None + assert recorded == { + found.baseline.simulation_run_id: RECORDED, + found.reform.simulation_run_id: RECORDED, + } + + +def test_a_request_that_joins_runs_records_nothing_of_its_own( + public_api_database_url, +) -> None: + """A joined run keeps its list, or, recorded without one, every variable.""" + with rolled_back_transaction(public_api_database_url) as connection: + catalog = _catalog(connection) + household_id = _household(connection) + reform = SimulationChoice( + policy_id=insert_policy(connection, catalog), dynamic_id=None + ) + act_as_the_service(connection) + first = in_session( + connection, + find_or_create_household_report, + _keyed_report(catalog, household_id, reform=reform, variables=LISTED), + ) + recorded = _recorded_variables(connection) + + identical = in_session( + connection, + find_or_create_household_report, + _keyed_report(catalog, household_id, reform=reform, variables=("age",)), + ) + # A new report run on the first report's baseline run. + baseline_alone = in_session( + connection, + find_or_create_household_report, + _keyed_report(catalog, household_id, reform=None, variables=("age",)), + ) + recorded_after = _recorded_variables(connection) + + assert identical.run.id == first.run.id + assert baseline_alone.run.inserted is True + assert baseline_alone.baseline.simulation_run_id == ( + first.baseline.simulation_run_id + ) + assert recorded_after == recorded + + +def test_a_policy_compared_with_itself_records_its_one_run_once( + public_api_database_url, +) -> None: + with rolled_back_transaction(public_api_database_url) as connection: + catalog = _catalog(connection) + request = _keyed_report( + catalog, _household(connection), reform=CURRENT_LAW, variables=LISTED + ) + act_as_the_service(connection) + + found = in_session(connection, find_or_create_household_report, request) + recorded = _recorded_variables(connection) + + assert recorded == {found.baseline.simulation_run_id: RECORDED} + + +def test_a_request_without_a_list_records_none(public_api_database_url) -> None: + """Such a run calculates every variable, as every run did before lists.""" + with rolled_back_transaction(public_api_database_url) as connection: + catalog = _catalog(connection) + request = _keyed_report( + catalog, _household(connection), reform=None, variables=None + ) + act_as_the_service(connection) + + found = in_session(connection, find_or_create_household_report, request) + recorded = _recorded_variables(connection) + + assert found.run.inserted is True + assert recorded == {} + + +def _stored_report(connection: Connection, catalog: CatalogVersion): + """Insert a household report with no key and its first runs, as the superuser.""" + return insert_household_report_rows( + connection, + catalog, + household_id=_household(connection), + year=2026, + versions=VERSIONS, + reform_policy_id=insert_policy(connection, catalog), + ) + + +def test_a_reruns_list_is_recorded_for_each_run_it_inserts( + public_api_database_url, +) -> None: + with rolled_back_transaction(public_api_database_url) as connection: + catalog = _catalog(connection) + report = _stored_report(connection, catalog) + assert report.reform is not None + rerun = NewHouseholdReportRerun( + report_id=report.id, + run_id=uuid4(), + tax_benefit_model_version_id=catalog.version_id, + year=2026, + versions=VERSIONS, + baseline=HouseholdRerunSide( + simulation_id=report.baseline.simulation_id, simulation_run_id=uuid4() + ), + reform=HouseholdRerunSide( + simulation_id=report.reform.simulation_id, simulation_run_id=uuid4() + ), + forced=True, + variables=LISTED, + ) + act_as_the_service(connection) + + created = in_session(connection, insert_household_report_rerun, rerun) + recorded = _recorded_variables(connection) + + assert created.inserted is True + assert recorded == dict.fromkeys(rerun.simulation_run_ids, RECORDED) + + +NEXT_VERSIONS = replace(VERSIONS, country_package_version="1.764.7") + + +def _unforced_rerun( + report: StoredHouseholdReport, + catalog: CatalogVersion, + *, + versions: RunVersions, + variables: tuple[str, ...], +) -> NewHouseholdReportRerun: + """Return a keyed report's re-run of both sides, proposing fresh run IDs.""" + assert report.reform is not None + return NewHouseholdReportRerun( + report_id=report.id, + run_id=uuid4(), + tax_benefit_model_version_id=catalog.version_id, + year=2026, + versions=versions, + baseline=HouseholdRerunSide( + simulation_id=report.baseline.simulation_id, simulation_run_id=uuid4() + ), + reform=HouseholdRerunSide( + simulation_id=report.reform.simulation_id, simulation_run_id=uuid4() + ), + forced=False, + variables=variables, + ) + + +def _fail(connection: Connection, table: str, row_id: UUID) -> None: + """Fail a run as the superuser, then act as the service again.""" + connection.execute(text("RESET ROLE")) + connection.execute( + text( + f"UPDATE public.{table} SET status = 'failed', " # noqa: S608 # a test's own table name + "error_message = 'failed', completed_at = now() WHERE id = :id" + ), + {"id": row_id}, + ) + act_as_the_service(connection) + + +def test_an_unforced_reruns_list_is_recorded_only_for_runs_it_inserts( + public_api_database_url, +) -> None: + """A re-run joining the report's run, or a side's run, records nothing on it.""" + with rolled_back_transaction(public_api_database_url) as connection: + catalog = _catalog(connection) + report = _stored_report(connection, catalog) + act_as_the_service(connection) + # The report's run on VERSIONS hasn't failed, so the re-run joins it. + joined = in_session( + connection, + insert_household_report_rerun, + _unforced_rerun(report, catalog, versions=VERSIONS, variables=LISTED), + ) + recorded_after_joining = _recorded_variables(connection) + inserted = in_session( + connection, + insert_household_report_rerun, + _unforced_rerun(report, catalog, versions=NEXT_VERSIONS, variables=LISTED), + ) + recorded_after_inserting = _recorded_variables(connection) + # That report run and its reform's run fail; its baseline's run hasn't. + assert inserted.reform_simulation_run_id is not None + _fail(connection, "report_runs", inserted.id) + _fail(connection, "simulation_runs", inserted.reform_simulation_run_id) + mixed = in_session( + connection, + insert_household_report_rerun, + _unforced_rerun( + report, catalog, versions=NEXT_VERSIONS, variables=("age",) + ), + ) + recorded_after_mixing = _recorded_variables(connection) + + assert (joined.inserted, recorded_after_joining) == (False, {}) + assert inserted.inserted is True + assert recorded_after_inserting == { + inserted.baseline_simulation_run_id: RECORDED, + inserted.reform_simulation_run_id: RECORDED, + } + assert mixed.inserted is True + assert mixed.baseline_simulation_run_id == inserted.baseline_simulation_run_id + assert mixed.reform_simulation_run_id is not None + assert recorded_after_mixing == { + **recorded_after_inserting, + mixed.reform_simulation_run_id: ["age"], + } + + +def test_a_calculation_key_names_the_sorted_variables_and_the_axes() -> None: + """The key is the SHA-256 of the two as canonical JSON, the list sorted.""" + canonical = json.dumps( + {"axes": EARNINGS_AXES, "variables": RECORDED}, + sort_keys=True, + separators=(",", ":"), + ) + + assert household_calculation_key(LISTED, EARNINGS_AXES) == ( + hashlib.sha256(canonical.encode()).hexdigest() + ) + assert household_calculation_key(LISTED, None) == household_calculation_key( + tuple(reversed(LISTED)), None + ) + assert household_calculation_key(LISTED, None) != household_calculation_key( + LISTED, EARNINGS_AXES + ) + assert HOUSEHOLD_CALCULATION_KEY_VERSION == 1 + + +def _calculation( + report: StoredHouseholdReport, + *, + variables: tuple[str, ...] = LISTED, + axes: list[Any] | None = None, +) -> NewHouseholdRunCalculation: + """Return an extra calculation of the report's baseline run, with a fresh ID.""" + return NewHouseholdRunCalculation( + id=uuid4(), + simulation_run_id=report.baseline.simulation_run_id, + simulation_id=report.baseline.simulation_id, + variables=variables, + axes=axes, + ) + + +def _calculation_row(connection: Connection, calculation_id: UUID) -> dict[str, Any]: + row = connection.execute( + text("SELECT * FROM public.household_run_calculations WHERE id = :id"), + {"id": calculation_id}, + ).mappings() + return dict(row.one()) + + +def test_an_extra_calculation_is_inserted_pending_then_joined( + public_api_database_url, +) -> None: + with rolled_back_transaction(public_api_database_url) as connection: + report = _stored_report(connection, _catalog(connection)) + proposed = _calculation(report, axes=EARNINGS_AXES) + act_as_the_service(connection) + + found = in_session( + connection, find_or_insert_household_run_calculations, [proposed] + ) + row = _calculation_row(connection, proposed.id) + identical = in_session( + connection, + find_or_insert_household_run_calculations, + [replace(proposed, id=uuid4(), variables=tuple(reversed(LISTED)))], + ) + + run_id = report.baseline.simulation_run_id + assert found == { + run_id: FoundHouseholdRunCalculation( + id=proposed.id, + simulation_run_id=run_id, + inserted=True, + status=SimulationStatus.PENDING, + ) + } + assert identical == {run_id: replace(found[run_id], inserted=False)} + assert { + name: row[name] + for name in ( + "simulation_run_id", + "simulation_id", + "simulation_type", + "variables", + "axes", + "key_version", + "calculation_key", + "status", + "modal_call_id", + "result", + ) + } == { + "simulation_run_id": run_id, + "simulation_id": report.baseline.simulation_id, + "simulation_type": "household", + "variables": RECORDED, + "axes": EARNINGS_AXES, + "key_version": HOUSEHOLD_CALCULATION_KEY_VERSION, + "calculation_key": household_calculation_key(LISTED, EARNINGS_AXES), + "status": "pending", + "modal_call_id": None, + "result": None, + } + + +def test_other_variables_or_axes_are_another_calculation_of_the_run( + public_api_database_url, +) -> None: + with rolled_back_transaction(public_api_database_url) as connection: + report = _stored_report(connection, _catalog(connection)) + act_as_the_service(connection) + + calculations = [ + _calculation(report), + _calculation(report, axes=EARNINGS_AXES), + _calculation(report, variables=("age",)), + ] + found = [ + in_session( + connection, find_or_insert_household_run_calculations, [proposed] + )[report.baseline.simulation_run_id] + for proposed in calculations + ] + + assert [calculation.inserted for calculation in found] == [True, True, True] + assert len({calculation.id for calculation in found}) == len(calculations) + + +def test_each_run_named_gets_its_own_calculation(public_api_database_url) -> None: + with rolled_back_transaction(public_api_database_url) as connection: + report = _stored_report(connection, _catalog(connection)) + assert report.reform is not None + baseline = _calculation(report) + reform = replace( + baseline, + id=uuid4(), + simulation_run_id=report.reform.simulation_run_id, + simulation_id=report.reform.simulation_id, + ) + act_as_the_service(connection) + + found = in_session( + connection, find_or_insert_household_run_calculations, [reform, baseline] + ) + + assert {run_id: calculation.id for run_id, calculation in found.items()} == { + report.baseline.simulation_run_id: baseline.id, + report.reform.simulation_run_id: reform.id, + } + + +def test_a_failed_calculation_never_counts(public_api_database_url) -> None: + """Modal refused its call, so the next identical request starts another.""" + with rolled_back_transaction(public_api_database_url) as connection: + report = _stored_report(connection, _catalog(connection)) + proposed = _calculation(report) + act_as_the_service(connection) + in_session(connection, find_or_insert_household_run_calculations, [proposed]) + + failed = in_session( + connection, + fail_unstarted_household_run_calculation, + household_run_calculation_id=proposed.id, + error_message="modal_call_refused: Modal did not accept the call.", + ) + again = in_session( + connection, + find_or_insert_household_run_calculations, + [replace(proposed, id=uuid4())], + ) + failed_row = _calculation_row(connection, proposed.id) + + assert failed is True + assert failed_row["status"] == "failed" + assert failed_row["completed_at"] is not None + (calculation,) = again.values() + assert calculation.inserted is True + assert calculation.id != proposed.id + + +def test_a_calculations_call_is_recorded_while_it_is_pending_with_none( + public_api_database_url, +) -> None: + with rolled_back_transaction(public_api_database_url) as connection: + report = _stored_report(connection, _catalog(connection)) + proposed = _calculation(report) + act_as_the_service(connection) + in_session(connection, find_or_insert_household_run_calculations, [proposed]) + + recorded = in_session( + connection, + record_household_run_calculation_call, + household_run_calculation_id=proposed.id, + modal_call_id="fc-extra", + ) + again = in_session( + connection, + record_household_run_calculation_call, + household_run_calculation_id=proposed.id, + modal_call_id="fc-other", + ) + not_failed = in_session( + connection, + fail_unstarted_household_run_calculation, + household_run_calculation_id=proposed.id, + error_message="modal_call_refused: Modal did not accept the call.", + ) + missing = in_session( + connection, + record_household_run_calculation_call, + household_run_calculation_id=uuid4(), + modal_call_id="fc-extra", + ) + row = _calculation_row(connection, proposed.id) + + assert (recorded, again, missing) == ( + SimulationStatus.PENDING, + SimulationStatus.PENDING, + None, + ) + assert not_failed is False + assert (row["status"], row["modal_call_id"]) == ("pending", "fc-extra") + + +def test_a_report_run_is_read_with_each_sides_simulation_and_run( + public_api_database_url, +) -> None: + with rolled_back_transaction(public_api_database_url) as connection: + catalog = _catalog(connection) + report = _stored_report(connection, catalog) + other = _stored_report(connection, catalog) + act_as_the_service(connection) + + stored = in_session( + connection, + read_report_run, + report_id=report.id, + report_run_id=report.run_id, + ) + of_another_report = in_session( + connection, read_report_run, report_id=other.id, report_run_id=report.run_id + ) + missing = in_session( + connection, read_report_run, report_id=report.id, report_run_id=uuid4() + ) + + assert report.reform is not None + assert stored == StoredReportRun( + id=report.run_id, + report_id=report.id, + status=ReportRunStatus.PENDING, + versions=VERSIONS, + baseline=SideRun( + simulation_id=report.baseline.simulation_id, + simulation_run_id=report.baseline.simulation_run_id, + ), + reform=SideRun( + simulation_id=report.reform.simulation_id, + simulation_run_id=report.reform.simulation_run_id, + ), + ) + assert (of_another_report, missing) == (None, None) + + +def test_the_store_reads_a_report_with_its_run_and_writes_calculations( + public_api_database_url, +) -> None: + """Each operation is a transaction of its own; a run of another report is None.""" + with rolled_back_transaction(public_api_database_url) as connection: + catalog = _catalog(connection) + report = _stored_report(connection, catalog) + act_as_the_service(connection) + store = HouseholdRunCalculationStore.from_session_factory( + session_factory_on(connection), + statement_timeout_milliseconds=STATEMENT_TIMEOUT_MILLISECONDS, + ) + proposed = _calculation(report) + + read = store.read_report_with_run(report.id, report.run_id) + unknown_run = store.read_report_with_run(report.id, uuid4()) + unknown_report = store.read_report_with_run(uuid4(), report.run_id) + found = store.find_or_create_calculations([proposed]) + recorded = store.record_calculation_call(proposed.id, "fc-extra") + failed = store.fail_unstarted_calculation(proposed.id, "modal_call_refused: x") + + assert read.definition is not None + assert read.definition.kind == "household" + assert read.run is not None + assert read.run.id == report.run_id + assert unknown_run.definition is not None + assert unknown_run.run is None + assert (unknown_report.definition, unknown_report.run) == (None, None) + assert found[report.baseline.simulation_run_id].inserted is True + assert recorded == SimulationStatus.PENDING + assert failed is False diff --git a/libs/policyengine-simulation-persistence/tests/test_household_run_tables.py b/libs/policyengine-simulation-persistence/tests/test_household_run_tables.py new file mode 100644 index 000000000..87a9a5968 --- /dev/null +++ b/libs/policyengine-simulation-persistence/tests/test_household_run_tables.py @@ -0,0 +1,119 @@ +"""Sim's models of API v1's two household run tables (D2 · 3a). + +``household_run_variables`` records the variables a household simulation run +calculates, and ``household_run_calculations`` a household run's extra +calculations. The CI comparison checks the models against the tables API +v1's chain builds; these check what the service's writes rely on. +""" + +from __future__ import annotations + +from policyengine_simulation_persistence import ( + HouseholdRunCalculation, + HouseholdRunVariables, + Simulation, + SimulationRun, + SimulationStatus, + SimulationType, + service_metadata, +) +from sqlalchemy import JSON, ForeignKeyConstraint, Table, UniqueConstraint + + +def _foreign_keys(table: Table) -> dict[str, tuple[tuple[str, ...], str, str]]: + """Return each key's columns, the columns it names, and its delete rule.""" + keys = {} + for constraint in table.constraints: + if not isinstance(constraint, ForeignKeyConstraint): + continue + named_columns = ", ".join( + element.column.name for element in constraint.elements + ) + keys[str(constraint.name)] = ( + tuple(constraint.column_keys), + f"{constraint.referred_table.name}({named_columns})", + str(constraint.ondelete), + ) + return keys + + +def _unique_keys(table: Table) -> dict[str, tuple[str, ...]]: + return { + str(constraint.name): tuple(column.name for column in constraint.columns) + for constraint in table.constraints + if isinstance(constraint, UniqueConstraint) + } + + +def test_both_tables_are_among_the_tables_the_service_creates_rows_in() -> None: + assert {"household_run_variables", "household_run_calculations"} <= { + table.name for table in service_metadata.tables.values() + } + + +def test_each_row_names_a_household_run_and_goes_with_it() -> None: + """Each table names its run with the run's simulation, and the simulation's type.""" + for model in (HouseholdRunVariables, HouseholdRunCalculation): + table = model.__table__ + table_name = table.name + + assert _foreign_keys(table) == { + f"fk_{table_name}_run": ( + ("simulation_run_id", "simulation_id"), + "simulation_runs(id, simulation_id)", + "CASCADE", + ), + f"fk_{table_name}_simulation": ( + ("simulation_id", "simulation_type"), + "simulations(id, simulation_type)", + "CASCADE", + ), + }, table_name + assert table.c.simulation_type.type.enums == list(SimulationType) + + +def test_the_keys_name_unique_constraints_of_simulations_and_their_runs() -> None: + assert _unique_keys(Simulation.__table__)["uq_simulations_id_type"] == ( + "id", + "simulation_type", + ) + assert _unique_keys(SimulationRun.__table__)[ + "uq_simulation_runs_id_simulation" + ] == ("id", "simulation_id") + + +def test_a_run_records_one_variable_list() -> None: + table = HouseholdRunVariables.__table__ + + assert [column.name for column in table.primary_key.columns] == [ + "simulation_run_id" + ] + assert isinstance(table.c.variables.type, JSON) + + +def test_a_run_has_one_unfailed_extra_calculation_of_each_request() -> None: + """A failed calculation stays recorded, and a later request starts another.""" + table = HouseholdRunCalculation.__table__ + (index,) = ( + index + for index in table.indexes + if index.name == "uq_household_run_calculations_unfailed" + ) + + assert index.unique is True + assert tuple(column.name for column in index.columns) == ( + "simulation_run_id", + "key_version", + "calculation_key", + ) + assert str(index.dialect_options["postgresql"]["where"]) == "status <> 'failed'" + assert table.c.status.type.enums == list(SimulationStatus) + + +def test_absent_axes_and_results_are_stored_as_sql_null() -> None: + columns = HouseholdRunCalculation.__table__.c + + assert columns.axes.type.none_as_null is True + assert columns.result.type.none_as_null is True + assert columns.axes.nullable is True + assert columns.result.nullable is True diff --git a/libs/policyengine-simulation-persistence/tests/test_mapped_classes.py b/libs/policyengine-simulation-persistence/tests/test_mapped_classes.py index 27cf3fa85..01409408b 100644 --- a/libs/policyengine-simulation-persistence/tests/test_mapped_classes.py +++ b/libs/policyengine-simulation-persistence/tests/test_mapped_classes.py @@ -27,6 +27,8 @@ Household, HouseholdJob, HouseholdJobStatus, + HouseholdRunCalculation, + HouseholdRunVariables, Inequality, InputBase, IntraDecileImpact, @@ -75,6 +77,8 @@ "report_runs": ReportRun, "household_jobs": HouseholdJob, "cliff_impacts": CliffImpact, + "household_run_variables": HouseholdRunVariables, + "household_run_calculations": HouseholdRunCalculation, } REFERENCED_CLASSES = { "datasets": referenced_tables.ReferencedDataset, @@ -124,6 +128,8 @@ pytest.param(input_tables, INPUT_CLASSES, id="input"), pytest.param(result_tables, RESULT_CLASSES, id="result"), ] +# API v1 keys a household run's variables by the run, one row per run. +PRIMARY_KEYS = {HouseholdRunVariables: ["simulation_run_id"]} ALL_CLASSES = [ *SERVICE_CLASSES.values(), *REFERENCED_CLASSES.values(), @@ -195,10 +201,13 @@ def test_each_annotation_states_whether_its_column_allows_null(mapped_class) -> @pytest.mark.parametrize("mapped_class", ALL_CLASSES, ids=lambda item: item.__name__) -def test_each_class_is_identified_by_the_id_column(mapped_class) -> None: +def test_each_class_is_identified_by_id_or_its_listed_primary_key(mapped_class) -> None: + """A class in ``PRIMARY_KEYS`` is identified by its listed key, others by id.""" primary_key = inspect(mapped_class).primary_key - assert [column.name for column in primary_key] == ["id"] + assert [column.name for column in primary_key] == PRIMARY_KEYS.get( + mapped_class, ["id"] + ) def test_the_keys_to_api_v1s_tables_name_the_referenced_classes() -> None: diff --git a/libs/policyengine-simulation-persistence/tests/test_tables.py b/libs/policyengine-simulation-persistence/tests/test_tables.py index c5b9b38ff..57d43a217 100644 --- a/libs/policyengine-simulation-persistence/tests/test_tables.py +++ b/libs/policyengine-simulation-persistence/tests/test_tables.py @@ -184,8 +184,9 @@ def test_every_enum_type_names_the_public_schema() -> None: if isinstance(column.type, Enum) ] - # Including cliff_impacts.status, which reuses the simulation runs' type. - assert len(enum_columns) == 6 + # Including cliff_impacts.status and the household run tables' types, + # which reuse the simulations' and simulation runs' types. + assert len(enum_columns) == 9 for column in enum_columns: assert column.type.schema == "public", f"{column.table.name}.{column.name}" # The helper every enum column uses, before any table adopts its type. diff --git a/libs/policyengine-stage12-persistence/src/policyengine_stage12_persistence/household_report_run_store.py b/libs/policyengine-stage12-persistence/src/policyengine_stage12_persistence/household_report_run_store.py index f6d6cd512..00b6d7ed8 100644 --- a/libs/policyengine-stage12-persistence/src/policyengine_stage12_persistence/household_report_run_store.py +++ b/libs/policyengine-stage12-persistence/src/policyengine_stage12_persistence/household_report_run_store.py @@ -14,16 +14,28 @@ another call holds, which other report runs may share, is left alone; a run whose holding call ended without an outcome is failed with ``fail_simulation_run_held_by``. + +A run calculates the variables it records in ``household_run_variables``, +or every variable when it records none (``household_run_variables``). An +extra calculation of a run, of other variables or across axes, is claimed, +completed and failed the same way, under its own call: the simulation +service inserts it pending, and the stuck-run sweep fails one no call +finishes. """ from __future__ import annotations from typing import TYPE_CHECKING, Any +from policyengine_simulation_persistence.household_run_tables import ( + HouseholdRunCalculation, + HouseholdRunVariables, +) from policyengine_simulation_persistence.tables import ReportRun, SimulationRun -from sqlalchemy import select, update +from sqlalchemy import func, or_, select, update from policyengine_stage12_persistence.report_run_store import ( + ACTIVE_STATUSES, ReportRunStore, RunStatus, running_under_call, @@ -38,7 +50,119 @@ class HouseholdReportRunStore(ReportRunStore): - """A report run store that also records household simulation runs' results.""" + """A report run store that also writes household runs and extra calculations.""" + + def household_run_variables( + self, simulation_run_id: UUID + ) -> tuple[str, ...] | None: + """Return the variables the household run records; None for every variable.""" + statement = select(HouseholdRunVariables.variables).where( + HouseholdRunVariables.simulation_run_id == simulation_run_id + ) + with self.sessions.transaction("household_run_variables") as session: + recorded = session.execute(statement).scalar_one_or_none() + return None if recorded is None else tuple(recorded) + + def claim_household_run_calculation( + self, + calculation_id: UUID, + *, + modal_call_id: str, + claimed_at: datetime, + ) -> RunWrite: + """Mark the extra calculation running under the worker's ``modal_call_id``. + + A pending or running calculation is claimed while it records no call + or this call, as a cliff result is. Raises LookupError when it does + not exist. + """ + statement = ( + update(HouseholdRunCalculation) + .where( + HouseholdRunCalculation.id == calculation_id, + HouseholdRunCalculation.status.in_(ACTIVE_STATUSES), + or_( + HouseholdRunCalculation.modal_call_id.is_(None), + HouseholdRunCalculation.modal_call_id == modal_call_id, + ), + ) + .values( + status=RunStatus.RUNNING.value, + modal_call_id=modal_call_id, + started_at=func.coalesce( + HouseholdRunCalculation.started_at, claimed_at + ), + updated_at=claimed_at, + ) + ) + return self._write( + HouseholdRunCalculation, + calculation_id, + statement, + "claim_household_run_calculation", + ) + + def complete_household_run_calculation( + self, + calculation_id: UUID, + *, + modal_call_id: str, + result: Mapping[str, Any], + completed_at: datetime, + ) -> RunWrite: + """Record the calculated household; mark it succeeded under this call. + + ``result`` is the calculation's ``HouseholdExecutionResult`` as JSON. + """ + statement = ( + update(HouseholdRunCalculation) + .where( + HouseholdRunCalculation.id == calculation_id, + running_under_call(HouseholdRunCalculation, modal_call_id), + ) + .values( + status=RunStatus.SUCCEEDED.value, + result=dict(result), + error_message=None, + completed_at=completed_at, + updated_at=completed_at, + ) + ) + return self._write( + HouseholdRunCalculation, + calculation_id, + statement, + "complete_household_run_calculation", + ) + + def fail_household_run_calculation( + self, + calculation_id: UUID, + *, + modal_call_id: str, + error_message: str, + failed_at: datetime, + ) -> RunWrite: + """Mark the extra calculation failed while ``modal_call_id`` holds it.""" + statement = ( + update(HouseholdRunCalculation) + .where( + HouseholdRunCalculation.id == calculation_id, + running_under_call(HouseholdRunCalculation, modal_call_id), + ) + .values( + status=RunStatus.FAILED.value, + error_message=error_message, + completed_at=failed_at, + updated_at=failed_at, + ) + ) + return self._write( + HouseholdRunCalculation, + calculation_id, + statement, + "fail_household_run_calculation", + ) def household_report_simulation_runs( self, report_run_id: UUID diff --git a/libs/policyengine-stage12-persistence/src/policyengine_stage12_persistence/report_run_results.py b/libs/policyengine-stage12-persistence/src/policyengine_stage12_persistence/report_run_results.py index d3d430480..b0d9adee8 100644 --- a/libs/policyengine-stage12-persistence/src/policyengine_stage12_persistence/report_run_results.py +++ b/libs/policyengine-stage12-persistence/src/policyengine_stage12_persistence/report_run_results.py @@ -7,7 +7,8 @@ keyed by each simulation run. The SPM receipts and data version are columns of the report run itself, which its completion sets. A cliff impact is not stored here: each simulation run has its own cliff result, which the -worker that calculates it writes. +worker that calculates it writes. ``result_inserts`` inserts the rows in +the transaction that completes the report run. The result tables' models are the simulation service library's (``policyengine_simulation_persistence.result_tables``), which the CI @@ -17,7 +18,7 @@ from __future__ import annotations from dataclasses import dataclass -from typing import TYPE_CHECKING, Any, Literal, NamedTuple +from typing import TYPE_CHECKING, Any, Final, Literal, NamedTuple from uuid import uuid4 from policyengine_simulation_contract.macro_output import ( @@ -38,9 +39,11 @@ ProgramStatistics, WithheldAreaCode, ) +from sqlalchemy import insert +from sqlalchemy.dialects.postgresql import insert as postgresql_insert if TYPE_CHECKING: - from collections.abc import Mapping + from collections.abc import Callable, Mapping from policyengine_simulation_contract.macro_output import ( AgePovertyOutput, @@ -56,6 +59,7 @@ ) from policyengine_simulation_contract.stage12_execution import ReportRunIds from policyengine_simulation_persistence.orm_base import ResultBase + from sqlalchemy.orm import Session # The household variable each headline budget figure totals, and the column # its figure goes in. ``budgetary_impact`` is tax minus benefits, as the @@ -601,3 +605,35 @@ def _sides(run_ids: ReportRunIds) -> tuple[tuple[str, Any], ...]: ("baseline", run_ids.baseline_simulation_run_id), ("reform", run_ids.reform_simulation_run_id), ) + + +# A bulk insert otherwise leaves out each column a row sets to None. Every row +# names the same columns, so the insert stays one statement that sets them NULL. +_EVERY_NAMED_COLUMN: Final = {"render_nulls": True} + + +def result_inserts(result: ReportRunResult) -> Callable[[Session], None]: + """Return the step that inserts ``result``'s rows in an open transaction.""" + + def insert_rows(session: Session) -> None: + for result_rows in result.rows: + if not result_rows.rows: + continue + statement = ( + postgresql_insert(result_rows.model).on_conflict_do_nothing() + if result_rows.shared_by_reports + else insert(result_rows.model) + ) + session.execute( + statement, + _uniform_rows(result_rows.rows), + execution_options=_EVERY_NAMED_COLUMN, + ) + + return insert_rows + + +def _uniform_rows(rows: tuple[dict[str, Any], ...]) -> list[dict[str, Any]]: + """Give every row the same columns, unset ones null, for one batched insert.""" + columns = {name for row in rows for name in row} + return [dict.fromkeys(columns) | row for row in rows] diff --git a/libs/policyengine-stage12-persistence/src/policyengine_stage12_persistence/report_run_store.py b/libs/policyengine-stage12-persistence/src/policyengine_stage12_persistence/report_run_store.py index 70c4e2a6a..c0d655e69 100644 --- a/libs/policyengine-stage12-persistence/src/policyengine_stage12_persistence/report_run_store.py +++ b/libs/policyengine-stage12-persistence/src/policyengine_stage12_persistence/report_run_store.py @@ -7,7 +7,8 @@ transaction, only when its update changed the run. A household job is written the same way, and its result document is set in the update that finishes it. The stuck-run sweep's reads and failures here also serve cliff -results, which ``CliffResultStore`` otherwise writes. +results, which ``CliffResultStore`` otherwise writes, and household runs' +extra calculations, which ``HouseholdReportRunStore`` otherwise writes. """ from __future__ import annotations @@ -16,6 +17,9 @@ from enum import StrEnum from typing import TYPE_CHECKING, Any, Final +from policyengine_simulation_persistence.household_run_tables import ( + HouseholdRunCalculation, +) from policyengine_simulation_persistence.tables import ( BudgetWindowRun, CliffImpact, @@ -23,8 +27,7 @@ ReportRun, SimulationRun, ) -from sqlalchemy import and_, case, exists, func, insert, or_, select, true, update -from sqlalchemy.dialects.postgresql import insert as postgresql_insert +from sqlalchemy import and_, case, exists, func, or_, select, true, update from policyengine_stage12_persistence.engine import ( WITHOUT_OBJECT_SYNC, @@ -32,6 +35,7 @@ StoreSessions, open_session_once, ) +from policyengine_stage12_persistence.report_run_results import result_inserts if TYPE_CHECKING: from collections.abc import Callable, Mapping @@ -46,7 +50,7 @@ class RunStatus(StrEnum): - """A report run's, simulation run's, household job's or cliff result's status.""" + """A run's, household job's, cliff result's or extra calculation's status.""" PENDING = "pending" RUNNING = "running" @@ -58,21 +62,29 @@ class RunStatus(StrEnum): class RunKind(StrEnum): - """Which table a run, household job or simulation run's cliff result is in.""" + """Which table a run, household job, cliff result or extra calculation is in. + + A cliff result is a simulation run's, and an extra calculation a household + simulation run's. + """ REPORT_RUN = "report_run" SIMULATION_RUN = "simulation_run" HOUSEHOLD_JOB = "household_job" CLIFF_RESULT = "cliff_result" + HOUSEHOLD_RUN_CALCULATION = "household_run_calculation" -type RunModel = type[ReportRun | SimulationRun | HouseholdJob | CliffImpact] +type RunModel = type[ + ReportRun | SimulationRun | HouseholdJob | CliffImpact | HouseholdRunCalculation +] RUN_MODELS: Final[dict[RunKind, RunModel]] = { RunKind.REPORT_RUN: ReportRun, RunKind.SIMULATION_RUN: SimulationRun, RunKind.HOUSEHOLD_JOB: HouseholdJob, RunKind.CLIFF_RESULT: CliffImpact, + RunKind.HOUSEHOLD_RUN_CALCULATION: HouseholdRunCalculation, } # What a missing row is called. _ROW_NOUNS: Final[dict[RunModel, str]] = { @@ -80,15 +92,13 @@ class RunKind(StrEnum): SimulationRun: "simulation run", HouseholdJob: "household job", CliffImpact: "cliff result", + HouseholdRunCalculation: "household run calculation", } -# A bulk insert otherwise leaves out each column a row sets to None. Every row -# names the same columns, so the insert stays one statement that sets them NULL. -_EVERY_NAMED_COLUMN: Final = {"render_nulls": True} @dataclass(frozen=True) class ActiveRun: - """A pending or running run, household job or cliff result, and its Modal call. + """A pending or running row of a ``RunKind``, and its Modal call. ``modal_call_id`` is None for a run with no call recorded. ``budget_window_run_id`` is the budget-window run a report run is a year @@ -289,7 +299,7 @@ def complete_report_run( run_ids.report_run_id, statement, "complete_report_run", - after_change=None if result is None else _result_inserts(result), + after_change=None if result is None else result_inserts(result), ) def fail_report_run( @@ -565,8 +575,9 @@ def list_active_runs( ) -> tuple[ActiveRun, ...]: """Return the pending and running runs of ``kind`` active since before a time. - A run or cliff result counts from its first claim, or from its creation - while it is pending; a household job counts from its creation, as the table's + A run, cliff result or extra calculation counts from its first claim, + or from its creation while it is pending; a household job counts from + its creation, as the table's status and creation index allows. Runs are oldest first, with or without a recorded Modal call. A simulation run is listed only while no pending or running report run names it as its baseline or reform: @@ -690,38 +701,11 @@ def _write( return RunWrite(changed=False, status=RunStatus(current)) -def _result_inserts(result: ReportRunResult) -> Callable[[Session], None]: - """Return the step that inserts ``result``'s rows in an open transaction.""" - - def insert_rows(session: Session) -> None: - for result_rows in result.rows: - if not result_rows.rows: - continue - statement = ( - postgresql_insert(result_rows.model).on_conflict_do_nothing() - if result_rows.shared_by_reports - else insert(result_rows.model) - ) - session.execute( - statement, - _uniform_rows(result_rows.rows), - execution_options=_EVERY_NAMED_COLUMN, - ) - - return insert_rows - - -def _uniform_rows(rows: tuple[dict[str, Any], ...]) -> list[dict[str, Any]]: - """Give every row the same columns, unset ones null, for one batched insert.""" - columns = {name for row in rows for name in row} - return [dict.fromkeys(columns) | row for row in rows] - - def running_under_call(model: RunModel, modal_call_id: str) -> ColumnElement[bool]: """Return the condition that a row is running under ``modal_call_id``. - A run, household job or cliff result is completed or failed by a call only - while that call holds it running. + A row of any ``RunKind`` is completed or failed by a call only while that + call holds it running. """ return and_( model.status == RunStatus.RUNNING.value, @@ -732,9 +716,10 @@ def running_under_call(model: RunModel, modal_call_id: str) -> ColumnElement[boo def _active_since(kind: RunKind) -> SQLColumnExpression[datetime]: """Return when a run of ``kind`` became active, for the sweep's ages. - A household job counts from its creation. A run or cliff result counts from - its first claim or, before it, from its creation, except a budget window's - year, which counts from its last change: when its call was recorded. + A household job counts from its creation. A run, cliff result or extra + calculation counts from its first claim or, before it, from its creation, + except a budget window's year, which counts from its last change: when its + call was recorded. """ if kind is RunKind.HOUSEHOLD_JOB: return HouseholdJob.created_at @@ -742,6 +727,10 @@ def _active_since(kind: RunKind) -> SQLColumnExpression[datetime]: return func.coalesce(SimulationRun.started_at, SimulationRun.created_at) if kind is RunKind.CLIFF_RESULT: return func.coalesce(CliffImpact.started_at, CliffImpact.created_at) + if kind is RunKind.HOUSEHOLD_RUN_CALCULATION: + return func.coalesce( + HouseholdRunCalculation.started_at, HouseholdRunCalculation.created_at + ) unclaimed_since = case( (ReportRun.budget_window_run_id.is_not(None), ReportRun.updated_at), else_=ReportRun.created_at, diff --git a/libs/policyengine-stage12-persistence/tests/report_run_database.py b/libs/policyengine-stage12-persistence/tests/report_run_database.py index de5dcb610..a20245294 100644 --- a/libs/policyengine-stage12-persistence/tests/report_run_database.py +++ b/libs/policyengine-stage12-persistence/tests/report_run_database.py @@ -51,6 +51,8 @@ "local_authority_impacts", "households", "household_jobs", + "household_run_variables", + "household_run_calculations", ) NOW = datetime(2026, 11, 4, tzinfo=UTC) VERSIONS = {"country_package_version": "1.0.0", "policyengine_version": "6.12.0"} diff --git a/libs/policyengine-stage12-persistence/tests/test_household_run_calculation_store.py b/libs/policyengine-stage12-persistence/tests/test_household_run_calculation_store.py new file mode 100644 index 000000000..21b5e5f34 --- /dev/null +++ b/libs/policyengine-stage12-persistence/tests/test_household_run_calculation_store.py @@ -0,0 +1,240 @@ +"""The Modal worker role's reads and writes of a household run's extra calculations. + +The simulation service inserts an extra calculation of a household +simulation run pending, and may record the Modal call it starts. The +household function's call then claims it under its call, as a cliff result +is claimed, and records the calculated household, or the failure, only while +its call holds it running; the stuck-run sweep fails one no call finishes. The +function also reads the variables each side's run records. These run against +a disposable Postgres that API v1's v2 migrations created, connected +as the Modal worker role (see ``report_run_database``). +""" + +from __future__ import annotations + +from datetime import timedelta +from typing import TYPE_CHECKING, Any +from uuid import UUID, uuid4 + +import pytest +from household_report_database import ( + remove_household_report_run, + seed_household_report_run, +) +from policyengine_stage12_persistence import ( + ActiveRun, + HouseholdReportRunStore, + RunKind, + RunStatus, + RunWrite, +) +from report_run_database import NOW, worker_database_url +from sqlalchemy import insert + +if TYPE_CHECKING: + from collections.abc import Iterator + + from household_report_database import SeededHouseholdReportRun + from report_run_database import ReportRunSeeder + +LATER = NOW + timedelta(minutes=5) +CALL = "fc-extra-calculation" +OTHER_CALL = "fc-other" +VARIABLES = ["age", "marginal_tax_rate"] +# What the household function stores: a household function's result document. +RESULT: dict[str, Any] = { + "status": "succeeded", + "output": {"household": {"people": {"you": {"marginal_tax_rate": {"2026": 0.3}}}}}, +} + + +@pytest.fixture +def store() -> HouseholdReportRunStore: + return HouseholdReportRunStore(worker_database_url()) + + +@pytest.fixture +def seeded_report(seeder: ReportRunSeeder) -> Iterator[SeededHouseholdReportRun]: + seeded = seed_household_report_run(seeder) + try: + yield seeded + finally: + # Deleting the runs deletes their calculations and variable lists. + remove_household_report_run(seeder, seeded) + + +def _simulation_of(seeder: ReportRunSeeder, simulation_run_id: UUID) -> UUID: + return seeder.row("simulation_runs", simulation_run_id)["simulation_id"] + + +def _insert_calculation( + seeder: ReportRunSeeder, + simulation_run_id: UUID, + *, + modal_call_id: str | None = None, +) -> UUID: + """Insert a pending extra calculation of the run, as the service does.""" + calculation_id = uuid4() + with seeder.engine.begin() as connection: + connection.execute( + insert(seeder.table("household_run_calculations")).values( + id=calculation_id, + created_at=NOW, + updated_at=NOW, + simulation_run_id=simulation_run_id, + simulation_id=_simulation_of(seeder, simulation_run_id), + simulation_type="household", + variables=VARIABLES, + # No axes: left out, so the column is SQL NULL, not JSON null. + key_version=1, + calculation_key="a" * 64, + status="pending", + modal_call_id=modal_call_id, + ) + ) + return calculation_id + + +def test_a_runs_recorded_variables_are_read( + store: HouseholdReportRunStore, + seeder: ReportRunSeeder, + seeded_report: SeededHouseholdReportRun, +) -> None: + """A run with no row calculates every variable: None.""" + run_id = seeded_report.baseline_simulation_run_id + with seeder.engine.begin() as connection: + connection.execute( + insert(seeder.table("household_run_variables")).values( + simulation_run_id=run_id, + simulation_id=_simulation_of(seeder, run_id), + simulation_type="household", + variables=VARIABLES, + ) + ) + + assert store.household_run_variables(run_id) == tuple(VARIABLES) + assert seeded_report.reform_simulation_run_id is not None + assert store.household_run_variables(seeded_report.reform_simulation_run_id) is ( + None + ) + + +def test_a_calculation_is_claimed_and_completed_only_under_its_call( + store: HouseholdReportRunStore, + seeder: ReportRunSeeder, + seeded_report: SeededHouseholdReportRun, +) -> None: + calculation_id = _insert_calculation( + seeder, seeded_report.baseline_simulation_run_id, modal_call_id=CALL + ) + + by_other_call = store.claim_household_run_calculation( + calculation_id, modal_call_id=OTHER_CALL, claimed_at=NOW + ) + claimed = store.claim_household_run_calculation( + calculation_id, modal_call_id=CALL, claimed_at=NOW + ) + completed_by_other = store.complete_household_run_calculation( + calculation_id, modal_call_id=OTHER_CALL, result=RESULT, completed_at=LATER + ) + completed = store.complete_household_run_calculation( + calculation_id, modal_call_id=CALL, result=RESULT, completed_at=LATER + ) + failed_after = store.fail_household_run_calculation( + calculation_id, + modal_call_id=CALL, + error_message="household_function_error: late", + failed_at=LATER, + ) + + assert by_other_call == RunWrite(changed=False, status=RunStatus.PENDING) + assert claimed == RunWrite(changed=True, status=RunStatus.RUNNING) + assert completed_by_other == RunWrite(changed=False, status=RunStatus.RUNNING) + assert completed == RunWrite(changed=True, status=RunStatus.SUCCEEDED) + assert failed_after == RunWrite(changed=False, status=RunStatus.SUCCEEDED) + row = seeder.row("household_run_calculations", calculation_id) + assert (row["status"], row["result"], row["error_message"]) == ( + "succeeded", + RESULT, + None, + ) + assert (row["started_at"], row["completed_at"]) == (NOW, LATER) + + +def test_a_calculation_with_no_call_is_claimed_and_fails_with_its_summary( + store: HouseholdReportRunStore, + seeder: ReportRunSeeder, + seeded_report: SeededHouseholdReportRun, +) -> None: + calculation_id = _insert_calculation( + seeder, seeded_report.baseline_simulation_run_id + ) + + claimed = store.claim_household_run_calculation( + calculation_id, modal_call_id=CALL, claimed_at=NOW + ) + failed = store.fail_household_run_calculation( + calculation_id, + modal_call_id=CALL, + error_message="invalid_inputs: Unrecognized variable", + failed_at=LATER, + ) + + assert claimed == RunWrite(changed=True, status=RunStatus.RUNNING) + assert failed == RunWrite(changed=True, status=RunStatus.FAILED) + row = seeder.row("household_run_calculations", calculation_id) + assert (row["status"], row["result"], row["error_message"]) == ( + "failed", + None, + "invalid_inputs: Unrecognized variable", + ) + assert row["completed_at"] == LATER + + +def test_a_missing_calculation_raises_lookup_error( + store: HouseholdReportRunStore, +) -> None: + missing_id = uuid4() + + with pytest.raises(LookupError, match=f"household run calculation {missing_id}"): + store.claim_household_run_calculation( + missing_id, modal_call_id=CALL, claimed_at=NOW + ) + + +def test_the_sweep_lists_and_fails_a_stuck_calculation_once( + store: HouseholdReportRunStore, + seeder: ReportRunSeeder, + seeded_report: SeededHouseholdReportRun, +) -> None: + """A calculation counts from its creation until its first claim.""" + calculation_id = _insert_calculation( + seeder, seeded_report.baseline_simulation_run_id, modal_call_id=CALL + ) + + not_yet = store.list_active_runs( + RunKind.HOUSEHOLD_RUN_CALCULATION, active_since_before=NOW + ) + listed = store.list_active_runs( + RunKind.HOUSEHOLD_RUN_CALCULATION, active_since_before=LATER + ) + stuck = ActiveRun( + kind=RunKind.HOUSEHOLD_RUN_CALCULATION, + run_id=calculation_id, + status=RunStatus.PENDING, + modal_call_id=CALL, + ) + failed = store.fail_stuck_run( + stuck, error_message="stuck_run: no call finished it", failed_at=LATER + ) + again = store.fail_stuck_run( + stuck, error_message="stuck_run: no call finished it", failed_at=LATER + ) + + assert calculation_id not in {run.run_id for run in not_yet} + assert stuck in listed + assert failed == RunWrite(changed=True, status=RunStatus.FAILED) + assert again == RunWrite(changed=False, status=RunStatus.FAILED) + assert seeder.row("household_run_calculations", calculation_id)["status"] == ( + "failed" + ) diff --git a/libs/policyengine-stage12-persistence/tests/test_shared_table_models.py b/libs/policyengine-stage12-persistence/tests/test_shared_table_models.py index e30196335..b79141b4d 100644 --- a/libs/policyengine-stage12-persistence/tests/test_shared_table_models.py +++ b/libs/policyengine-stage12-persistence/tests/test_shared_table_models.py @@ -24,6 +24,7 @@ from policyengine_simulation_contract.stage12_execution import ReportRunIds from policyengine_simulation_persistence import ( HouseholdJobStatus, + HouseholdRunCalculation, ReportRunStatus, SimulationStatus, engine, @@ -63,6 +64,9 @@ def test_the_run_stores_write_the_shared_run_table_models() -> None: assert RUN_MODELS[RunKind.SIMULATION_RUN] is shared_tables.SimulationRun assert RUN_MODELS[RunKind.HOUSEHOLD_JOB] is shared_tables.HouseholdJob assert RUN_MODELS[RunKind.CLIFF_RESULT] is shared_tables.CliffImpact + assert ( + RUN_MODELS[RunKind.HOUSEHOLD_RUN_CALCULATION] is HouseholdRunCalculation + ) assert cliff_result_store.CliffImpact is shared_tables.CliffImpact assert report_run_store.BudgetWindowRun is shared_tables.BudgetWindowRun @@ -76,6 +80,9 @@ def test_the_budget_window_store_writes_the_shared_run_table_models() -> None: def test_the_household_report_store_writes_the_shared_run_table_models() -> None: assert household_report_run_store.ReportRun is shared_tables.ReportRun assert household_report_run_store.SimulationRun is shared_tables.SimulationRun + assert household_report_run_store.HouseholdRunCalculation is ( + HouseholdRunCalculation + ) def test_every_table_the_library_names_is_shared_or_a_comparison_table() -> None: diff --git a/projects/policyengine-apis-integ/tests/test_household_run_calculation_generated_client.py b/projects/policyengine-apis-integ/tests/test_household_run_calculation_generated_client.py new file mode 100644 index 000000000..c0803b839 --- /dev/null +++ b/projects/policyengine-apis-integ/tests/test_household_run_calculation_generated_client.py @@ -0,0 +1,179 @@ +"""Hermetic wire checks of household runs' variables through the generated client. + +API v1 sends a household report's create and re-run with the ``variables`` +their runs calculate, and sends +``POST /reports/{report_id}/runs/{report_run_id}/household-calculations`` +with the variables to calculate and any axes, reading the 201 naming each +side's extra calculation, or the refusals economy reports share. +""" + +from uuid import UUID + +import httpx +from policyengine_api_simulation_client import AuthenticatedClient +from policyengine_api_simulation_client.api.default import ( + create_household_run_calculations, + create_report, + rerun_report, +) +from policyengine_api_simulation_client.models import ( + EconomyError, + EconomyRequestUnprocessable, + HouseholdReportRequest, + HouseholdRunCalculationRequest, + HouseholdRunCalculationsCreated, + ReportRerunRequest, + SimulationStatus, +) + +BASE_URL = "https://simulation.example" +REPORT_ID = "00000000-0000-4000-8000-0000000000e1" +REPORT_RUN_ID = "00000000-0000-4000-8000-0000000000e2" +RUN_IDS = [f"00000000-0000-4000-8000-0000000000f{digit}" for digit in "1234"] +HOUSEHOLD_ID = "00000000-0000-4000-8000-0000000000bb" +POLICY_ID = "00000000-0000-4000-8000-0000000000c5" +LISTED = ["household_net_income", "employment_income"] +CALCULATION_PATH = f"/reports/{REPORT_ID}/runs/{REPORT_RUN_ID}/household-calculations" +CALCULATION_BODY = { + "variables": ["marginal_tax_rate", "household_net_income"], + "axes": [[{"name": "employment_income", "count": 5, "min": 0, "max": 100_000}]], +} +CREATED_CALCULATIONS = { + "report_id": REPORT_ID, + "report_run_id": REPORT_RUN_ID, + "baseline": { + "household_run_calculation_id": RUN_IDS[0], + "simulation_run_id": RUN_IDS[1], + "status": "pending", + }, + "reform": { + "household_run_calculation_id": RUN_IDS[2], + "simulation_run_id": RUN_IDS[3], + "status": "succeeded", + }, +} +CREATED_HOUSEHOLD_REPORT = { + "report_id": REPORT_ID, + "report_run_id": REPORT_RUN_ID, + "status": "pending", + "year": 2026, + "baseline_simulation_id": RUN_IDS[0], + "baseline_simulation_run_id": RUN_IDS[1], + "reform_simulation_id": RUN_IDS[2], + "reform_simulation_run_id": RUN_IDS[3], +} + + +def _client( + status_code: int, answer_body: dict, sent: list[tuple[str, dict]] +) -> AuthenticatedClient: + """Return a client whose every request is recorded and answered as given.""" + + def answer(http_request: httpx.Request) -> httpx.Response: + body = httpx.Response(200, content=http_request.content).json() + sent.append((http_request.url.path, body)) + return httpx.Response(status_code, json=answer_body) + + client = AuthenticatedClient(base_url=BASE_URL, token="test") + client.set_httpx_client( + httpx.Client(base_url=BASE_URL, transport=httpx.MockTransport(answer)) + ) + return client + + +def _create_calculations(status_code: int, answer_body: dict, request: dict): + sent: list[tuple[str, dict]] = [] + response = create_household_run_calculations.sync_detailed( + UUID(REPORT_ID), + UUID(REPORT_RUN_ID), + client=_client(status_code, answer_body, sent), + body=HouseholdRunCalculationRequest.from_dict(request), + ) + return response, sent + + +def test_an_extra_calculation_is_sent_as_given_and_read_with_each_side(): + response, sent = _create_calculations(201, CREATED_CALCULATIONS, CALCULATION_BODY) + + assert sent == [(CALCULATION_PATH, CALCULATION_BODY)] + assert isinstance(response.parsed, HouseholdRunCalculationsCreated) + assert response.parsed.baseline.status is SimulationStatus.PENDING + assert response.parsed.to_dict() == CREATED_CALCULATIONS + + +def test_an_extra_calculation_without_axes_or_a_reform_is_read_as_one(): + created = {**CREATED_CALCULATIONS, "reform": None} + + response, sent = _create_calculations(201, created, {"variables": LISTED}) + + assert sent == [(CALCULATION_PATH, {"variables": LISTED})] + assert isinstance(response.parsed, HouseholdRunCalculationsCreated) + assert response.parsed.reform is None + + +def test_the_extra_calculation_refusals_are_read_with_their_codes(): + failed_run, _ = _create_calculations( + 409, + { + "code": "report_run_failed", + "detail": f"Report run {REPORT_RUN_ID} failed. Re-run the report first.", + }, + {"variables": LISTED}, + ) + unknown_run, _ = _create_calculations( + 404, + { + "code": "unknown_report_run", + "detail": f"Report {REPORT_ID} has no run {REPORT_RUN_ID}.", + }, + {"variables": LISTED}, + ) + not_household, _ = _create_calculations( + 422, + { + "detail": [ + { + "loc": ["path", "report_id"], + "msg": "An economy report has no household to calculate.", + "type": "household_calculations_not_available", + } + ], + "code": "household_calculations_not_available", + }, + {"variables": LISTED}, + ) + + assert isinstance(failed_run.parsed, EconomyError) + assert failed_run.parsed.code == "report_run_failed" + assert isinstance(unknown_run.parsed, EconomyError) + assert unknown_run.parsed.code == "unknown_report_run" + assert isinstance(not_household.parsed, EconomyRequestUnprocessable) + assert not_household.parsed.code == "household_calculations_not_available" + + +def test_a_household_reports_variables_are_sent_on_its_create_and_re_run(): + request = { + "country": "us", + "report_type": "household", + "label": None, + "description": None, + "household_id": HOUSEHOLD_ID, + "baseline": {"policy_id": None}, + "reform": {"policy_id": POLICY_ID}, + "variables": LISTED, + } + sent: list[tuple[str, dict]] = [] + client = _client(201, CREATED_HOUSEHOLD_REPORT, sent) + + create_report.sync_detailed( + client=client, body=HouseholdReportRequest.from_dict(request) + ) + rerun_report.sync_detailed( + UUID(REPORT_ID), + client=client, + body=ReportRerunRequest.from_dict({"variables": LISTED}), + ) + + ((create_path, created), (rerun_path, rerun)) = sent + assert (create_path, created) == ("/reports", request) + assert (rerun_path, rerun["variables"]) == (f"/reports/{REPORT_ID}/runs", LISTED) diff --git a/projects/policyengine-simulation-entry/README.md b/projects/policyengine-simulation-entry/README.md index f40adde7b..905b4a018 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/{report_id}/runs/{report_run_id}/household-calculations` | `simulation:submit` | | `POST /reports/without-run` | `simulation:submit` | | `POST /simulations` | `simulation:submit` | | `GET /simulations/{simulation_id}` | `simulation:read` | @@ -328,10 +329,15 @@ baseline and, optionally, a reform. It names the `country`, `label`, `description`, `household_id`, `baseline` and `reform` (each a stored `policy_id`, null for current law, and a stored `dynamic_id`, null for none; a null or omitted `reform` makes a report of the baseline alone). It names -no year, region, dataset, .py version or record ID, and has no options: -each side adds every variable the -household lacks, as the Public API's stored-household route does, so the -report holds every value, and `reports.inputs` is `{}`. A household's saved +no year, region, dataset, .py version or record ID, and has no options +(`reports.inputs` is `{}`). It may list `variables`, at least one name, +each once: each side then calculates those variables alone. Without them, +each side adds every variable the household lacks, as API v1's +stored-household route does, so the report holds every value. The list is +no part of the report's key: each simulation run the request inserts +records it, sorted, in `household_run_variables`, and a run it joins keeps +its own list, or every variable with none. The household function +calculates each side with the list its run records. A household's saved SPM selection is applied to both sides. The service reads the catalog version for the default worker's .py version, @@ -372,6 +378,40 @@ 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`. +### Extra calculations of a household report run + +`POST /reports/{report_id}/runs/{report_run_id}/household-calculations` +calculates other variables of a household report run's sides, or their +household across axes, under each side's run's household, policy, dynamic, +year and versions. Its body is `{"variables": [...], "axes": ...}`: +`variables` lists at least one name, each once and none with a NUL +character, and the optional `axes` +takes the household calculation routes' axes. For each distinct simulation +run the report run names, it finds, in one transaction, the run's +`household_run_calculations` row of the same variables, in any order, and +axes that hasn't failed, or inserts one pending; it starts one household +function call (`household_run_calculation_id`) for each row it inserted and +records the call's ID. The function claims the row under its call and +records the calculated household (a `HouseholdExecutionResult`) as its +`result`, or the failure's one-line summary as its `error_message`; the +stuck-run sweep fails a row no call finishes. API v1 reads the rows. The +answer is 201 with `report_id`, `report_run_id` and, for `baseline` and +`reform` (null for a report of the baseline alone), the row's +`household_run_calculation_id`, its `simulation_run_id` and its `status`. A +row Modal refused to start is failed at once and answered `failed`; the next +identical request inserts another. + +It is refused before anything is written: 404 `unknown_report` or +`unknown_report_run` (a run the report doesn't have); 422 +`household_calculations_not_available` for a report that is not a +household report; 409 `report_run_failed` for a run that failed, and +`report_run_not_current` for a run on other versions than the default +worker's, since its extra calculations would not match it (re-run the +report first); and a household report re-run's 400, 422 and 503 answers, +located at the stored report. A pending, running or succeeded run gets +extra calculations, and a run failing after they started doesn't stop +them. + ## Creating a report without a run `POST /reports/without-run` takes `POST /reports`' body (an economy, @@ -384,7 +424,9 @@ 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 +true` is refused with 422 `cliffs_not_available`, and a household report's +`variables` with 422 `variables_not_available`, since no run records them: +the report's first run lists its own. 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 @@ -455,7 +497,10 @@ every re-run of a household report created before keys, makes an extra run on a new run of each side, all marked `forced`. A report run it created is started by one household function call, as a new household report's is, and the re-run answers 201 with the household report -create's fields. +create's fields. A household report's re-run may list `variables`, as its +create may: each simulation run the re-run inserts records them. An economy +or budget-window report's re-run listing `variables` is refused with 422 +`variables_not_available`, located at `variables`. `POST /simulations/{simulation_id}/runs`, with no body, joins a stored economy simulation's run on the default worker's versions, catalog version and year that hasn't failed and wasn't forced, pending, running or 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 fefc4a83e..f91cc1756 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/app.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/app.py @@ -92,6 +92,12 @@ HouseholdCalculations, add_household_calculation_routes, ) +from policyengine_simulation_entry.household_run_calculation_routes import ( + add_household_run_calculation_routes, +) +from policyengine_simulation_entry.household_run_calculations import ( + household_run_calculations_for, +) from policyengine_simulation_entry.household_workers import ( ManifestHouseholdWorkers, ModalHouseholdFunctionCaller, @@ -514,20 +520,6 @@ async def get_budget_window_job( ) -def _register_household_calculation_routes( - app: FastAPI, - entry: EntryRuntime, - calculations: HouseholdCalculations | None, - *, - submitter: AuthorizationDependency, - reader: AuthorizationDependency, -) -> None: - """Add the routes that submit household calculations and read their jobs.""" - add_household_calculation_routes( - app, entry, calculations, submitter=submitter, reader=reader - ) - - def household_calculations_for( settings: Settings, database: SimulationDatabaseConnection | None ) -> HouseholdCalculations | None: @@ -764,7 +756,7 @@ async def lifespan(_: FastAPI) -> AsyncIterator[None]: submitter=simulation_submitter, reader=simulation_reader, ) - _register_household_calculation_routes( + add_household_calculation_routes( app, entry, household_calculations_for(runtime_settings, runtime_database), @@ -783,6 +775,12 @@ async def lifespan(_: FastAPI) -> AsyncIterator[None]: submitter=simulation_submitter, reader=simulation_reader, ) + add_household_run_calculation_routes( + app, + entry, + household_run_calculations_for(runtime_settings, runtime_database), + submitter=simulation_submitter, + ) # Kept apart from the services above, so removing it touches nothing else. add_report_without_run_routes( app, diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_api_models.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_api_models.py index 4be112a00..3a0421d2e 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_api_models.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_api_models.py @@ -44,11 +44,13 @@ from typing import Annotated, Any, Literal from uuid import UUID +from policyengine_simulation_contract.household_execution import ListedVariables from policyengine_simulation_contract.local_area_breakdown import UK_NATION_REGIONS from policyengine_simulation_contract.spm import SPMSelection from policyengine_simulation_contract.stage12_bundle import CountryId from policyengine_simulation_persistence import ReportRunStatus, SimulationStatus from pydantic import ( + AfterValidator, BaseModel, ConfigDict, Field, @@ -63,6 +65,22 @@ CatalogKey = Annotated[str, Field(min_length=1, max_length=255, pattern=r"^\S+$")] ReportLabel = Annotated[str, Field(min_length=1, max_length=255)] ReportDescription = Annotated[str, Field(max_length=10_000)] + + +def _refuse_nul_characters(names: tuple[str, ...]) -> tuple[str, ...]: + """Refuse a name with a NUL character, which a database text value can't hold.""" + if any("\x00" in name for name in names): + msg = "variable names must not contain NUL characters" + raise ValueError(msg) + return names + + +# The variables a household report's runs calculate: at least one, each named +# once, none with a NUL character. Without a list, each run calculates every +# variable. +ReportVariables = Annotated[ + ListedVariables, Field(min_length=1), AfterValidator(_refuse_nul_characters) +] # The one data source a report may ask for: the bundle's local-area dataset, # on which a UK-wide or nation report also calculates its constituency and # local-authority impacts. @@ -130,12 +148,27 @@ # A budget window's or household report's re-run asks for cliffs # (include_cliffs: true), which neither calculates; located at the field. "cliffs_not_available", + # An economy or budget-window report's re-run lists variables to + # calculate, which only a household report's runs do, or a household + # report created without a run lists them, which no run records; located + # at the field. + "variables_not_available", + # An extra calculation of a report run names a report that is not a + # household report, whose runs calculate no household; located at the + # path's report ID. + "household_calculations_not_available", ] # Why a stored record is not re-run now (409). EconomyConflictCode = Literal[ # The service does not re-run this kind of record, or the record lacks a # row it calculates on. "rerun_not_supported", + # An extra calculation names a household report run on other versions + # than the default worker's: the report is re-run first. + "report_run_not_current", + # An extra calculation names a household report run that failed: the + # report is re-run first. + "report_run_failed", ] # Why a route cannot answer now (503); retry after ``Retry-After`` seconds. EconomyUnavailableCode = Literal[ @@ -156,6 +189,8 @@ "internal_error", "unknown_report", "unknown_simulation", + # An extra calculation names a run the report doesn't have. + "unknown_report_run", ] @@ -318,10 +353,18 @@ class ReportRerunRequest(_Request): C1 · 27 asking for cliffs asks for them on its re-run too. A budget window or household report calculates no cliffs, and its re-run asking for them is refused (422 ``cliffs_not_available``). + + ``variables`` lists the variables a household report's re-run calculates + on each simulation run it creates, as a household report's create does; + without it, every variable. A run the re-run joins keeps its own list. + Only a household report's runs calculate household variables, so any + other report's re-run listing them is refused (422 + ``variables_not_available``). """ force: StrictBool = False include_cliffs: StrictBool = False + variables: ReportVariables | None = None class _Answer(BaseModel): 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 ced446bdf..965924a3c 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 @@ -118,6 +118,36 @@ def refuse_cliffs_for(kind: RecordKind) -> None: ) +# The reports whose runs calculate no household variables, as answers name them. +_REPORTS_WITHOUT_HOUSEHOLDS: Final[dict[RecordKind, str]] = { + "economy": "An economy report", + "budget_window": "A budget-window report", +} + + +def refuse_variables_for(kind: RecordKind) -> None: + """Refuse a re-run listing variables of a report whose runs calculate none. + + Only a household report's runs calculate household variables. A report + of a kind the service doesn't re-run is answered as such later. + """ + report = _REPORTS_WITHOUT_HOUSEHOLDS.get(kind) + if report is None: + return + raise EconomySubmissionUnprocessableError( + code="variables_not_available", + reasons=( + UnprocessableReason( + loc=("body", "variables"), + msg=( + f"{report} calculates no household variables. Leave out variables." + ), + type="variables_not_available", + ), + ), + ) + + def asks_for_cliffs(*, include_cliffs: bool, stored_inputs: Mapping[str, Any]) -> bool: """Return whether a report's re-run asks for its runs' cliffs. 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 5185d289a..4f0678b8b 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 @@ -34,6 +34,9 @@ that has none, as a create does; a report stored before C1 · 27 asking for cliffs asks for them on its re-run too. A budget window's or household report's re-run asking for cliffs answers 422 ``cliffs_not_available``. +A household report's re-run may list the variables each simulation run it +creates calculates; an economy or budget-window report's re-run listing +them answers 422 ``variables_not_available``. The other answers are the creates': 400 or 422 when the stored record cannot be calculated on the current catalog version, 503 with ``Retry-After`` before any write or when Modal refused the new run's call (then the run was failed, @@ -158,6 +161,16 @@ class EconomyService(EconomySubmissions, EconomyReruns, Protocol): ), "simulation": "", } +# Only a household report's runs calculate household variables, so another +# report's re-run listing them is refused. +_VARIABLES_REFUSED: dict[RecordName, str] = { + "report": ( + "; or an economy or budget-window report's re-run lists variables, " + "which only a household report's runs calculate " + "(variables_not_available, located at variables)" + ), + "simulation": "", +} def _responses(record: RecordName) -> dict[int | str, dict[str, Any]]: @@ -200,7 +213,8 @@ def _responses(record: RecordName) -> dict[int | str, dict[str, Any]]: "dynamics cannot be calculated on the current catalog version " "(missing_parameters or overlapping_parameters, located under " f"{record}){_HOUSEHOLD_ANSWERS[record].get(422, '')}" - f"{_CLIFFS_REFUSED[record]}; nothing was written" + f"{_CLIFFS_REFUSED[record]}{_VARIABLES_REFUSED[record]}; nothing " + "was written" ), "model": EconomyRequestUnprocessable, }, @@ -309,7 +323,10 @@ async def answer( # the route, its record and how to re-run it "budget-window run with a report run per year, up to a new one's " "first four started at once, each year on its own year's simulations. " "A household report's run calculates its stored household in the " - "report's year, in one household function call." + "report's year, in one household function call; with variables, " + "each simulation run the re-run creates calculates those alone, " + "and an economy or budget-window report's re-run listing them is " + "refused (422 variables_not_available)." ), operation_id="rerun_report", status_code=status.HTTP_201_CREATED, 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 2f60b0461..1d63bfc9a 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 @@ -88,6 +88,7 @@ from policyengine_simulation_entry.economy_requests import ( asks_for_cliffs, refuse_cliffs_for, + refuse_variables_for, ) from policyengine_simulation_entry.economy_submission_errors import ( STORED_REPORT, @@ -269,10 +270,13 @@ async def rerun_report( raise EconomyRecordNotFoundError(_REPORT) if request.include_cliffs: refuse_cliffs_for(definition.kind) + if request.variables is not None: + refuse_variables_for(definition.kind) if definition.kind == "household": return await self._rerun_household_report( definition, force=request.force, + variables=request.variables, observability_context=observability_context, ) stored = rerunnable_report(definition) @@ -480,6 +484,7 @@ async def _rerun_household_report( definition: ReportDefinition, *, force: bool, + variables: tuple[str, ...] | None, observability_context: dict[str, Any] | None, ) -> HouseholdReportCreated: """Hand a stored household report the service can re-run to its service.""" @@ -489,7 +494,10 @@ async def _rerun_household_report( code="not_configured", detail="Household reports are not configured." ) return await self._household_reports.rerun_report( - stored, force=force, observability_context=observability_context + stored, + force=force, + observability_context=observability_context, + variables=variables, ) async def _rerun_window( diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_report_api_models.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_report_api_models.py index 7d2c1a106..0695c7ae8 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_report_api_models.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_report_api_models.py @@ -26,6 +26,7 @@ LABEL_NOT_STORED, ReportDescription, ReportLabel, + ReportVariables, ) @@ -48,12 +49,16 @@ class HouseholdReportRequest(_Request): """A household report: one stored household under a baseline and a reform. ``reform`` is null, or omitted, for a report of the baseline alone. The - report calculates the household's ``default_year``. Each side's - calculation adds every yearly, monthly and eternal variable the - household lacks, as the Public API's stored-household route does, so the - report holds every value; a household report has no option for it. A - household's saved SPM selection is applied, or the bundle's certified - defaults without one. + report calculates the household's ``default_year``. Without + ``variables``, each simulation run the request creates adds every + yearly, monthly and eternal variable the household lacks, as API v1's + stored-household route does. With it, each simulation run the request + creates calculates the listed variables alone and records the list, + sorted. The list is no part of the report's key: a run the request + joins, which an identical side of another request created, keeps its + own list, or every variable without one, so which variables a side + holds is read from ``household_run_variables``. A household's saved SPM + selection is applied, or the bundle's certified defaults without one. """ country: CountryId @@ -65,6 +70,7 @@ class HouseholdReportRequest(_Request): household_id: UUID baseline: HouseholdPolicyChoice reform: HouseholdPolicyChoice | None = None + variables: ReportVariables | None = None def options(self) -> dict[str, Any]: """Return the report's options as it stores them (``reports.inputs``). diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_report_calculations.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_report_calculations.py index d8bd867ef..5f3b97972 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_report_calculations.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_report_calculations.py @@ -2,7 +2,10 @@ Each side's request calculates the stored household, in its country, for the report's year with the household's saved SPM selection, on the default -worker's bundle; its calculation ID is the side's simulation run. The +worker's bundle, the listed variables or every variable; its calculation ID +is the side's simulation run. An extra calculation of a run +(``household_run_calculation_request``) calculates the same household and +policy, with any axes, under its own calculation ID. The household report services (``household_report_submissions``, ``household_report_reruns``) build it before writing anything, on the run IDs a request proposes, and again for a run they created, on the runs it @@ -139,6 +142,7 @@ def side_runs_calculation( year: int, run_ids: Mapping[ReportSide, UUID], worker: HouseholdWorker, + variables: tuple[str, ...] | None = None, ) -> HouseholdReportRunCalculation: """Build the household function payload for these side runs of ``inputs``. @@ -157,25 +161,28 @@ def side_runs_calculation( baseline=sides["baseline"], reform=sides.get("reform"), worker=worker, + variables=variables, ) -def household_report_calculation( +def household_report_calculation( # noqa: PLR0913 # the household, its year, each side, then the worker and variables *, household: StoredHousehold, year: int, baseline: HouseholdReportSideInputs, reform: HouseholdReportSideInputs | None = None, worker: HouseholdWorker, + variables: tuple[str, ...] | None = None, ) -> HouseholdReportRunCalculation: """Build a household report run's household function payload from its inputs. Each side's request calculates the stored ``household``, in its country, for ``year`` with the household's saved SPM selection, on ``worker``'s bundle, and its calculation ID is the side's simulation - run; ``reform`` is None for a report of the baseline alone. Every side - adds the household's missing variables, so a household report holds - every value. Creating a report passes the household's default year. A + run; ``reform`` is None for a report of the baseline alone. Each side + calculates ``variables``, the sorted list its run records, or, when it is + None, adds the household's missing variables, so the report holds every + value. Creating a report passes the household's default year. A restart or re-run passes the stored report's year, and the household and policy values as they are now read. @@ -188,17 +195,7 @@ def household_report_calculation( contract refuses a field the service builds, two sides recording one simulation run included. """ - country = household.country - try: - situation = household_situation(country, household.document) - except UnreadableHouseholdError: - raise household_not_calculable( - UnprocessableReason( - loc=("body", "household_id"), - msg="the stored household's people or groups cannot be read", - type="household_unreadable", - ) - ) from None + situation = _stored_situation(household) sides: dict[ReportSide, HouseholdReportSideInputs] = {"baseline": baseline} if reform is not None: sides["reform"] = reform @@ -210,6 +207,7 @@ def household_report_calculation( situation=situation, household=household, worker=worker, + variables=variables, ) for side, side_inputs in sides.items() } @@ -224,6 +222,60 @@ def household_report_calculation( raise HouseholdReportBuildError(msg) from None +def household_run_calculation_request( # noqa: PLR0913 # the side and what it calculates + side: ReportSide, + side_inputs: HouseholdReportSideInputs, + *, + household: StoredHousehold, + year: int, + worker: HouseholdWorker, + variables: tuple[str, ...], + axes: list[Any] | None, +) -> HouseholdExecutionRequest: + """Build an extra calculation's household contract request for one side. + + It calculates ``variables`` of the side's run's household, policy and + year, as the run did, on ``worker``'s bundle, across ``axes``, the + contract's axes as JSON, when given. ``side_inputs.simulation_run_id`` + is the calculation's own ID. Raise as ``household_report_calculation`` + does. + """ + situation = _stored_situation(household) + if axes is not None: + situation = {**situation, "axes": axes} + return _side_request( + side, + side_inputs, + year=year, + situation=situation, + household=household, + worker=worker, + variables=variables, + ) + + +def _stored_situation(household: StoredHousehold) -> dict[str, Any]: + """Return the stored household as a situation; raise its refusal if unreadable.""" + try: + return household_situation(household.country, household.document) + except UnreadableHouseholdError: + raise household_not_calculable( + UnprocessableReason( + loc=("body", "household_id"), + msg="the stored household's people or groups cannot be read", + type="household_unreadable", + ) + ) from None + + +def _variable_fields(variables: tuple[str, ...] | None) -> dict[str, object]: + """Return the contract's fields calculating ``variables``, or every variable.""" + if variables is None: + # Every value, as API v1's stored-household route gives it. + return {"add_missing_variables": True} + return {"add_missing_variables": False, "variables": variables} + + def _side_request( # noqa: PLR0913 # the side and what it calculates side: ReportSide, side_inputs: HouseholdReportSideInputs, @@ -232,6 +284,7 @@ def _side_request( # noqa: PLR0913 # the side and what it calculates situation: dict[str, Any], household: StoredHousehold, worker: HouseholdWorker, + variables: tuple[str, ...] | None, ) -> HouseholdExecutionRequest: """Build one side's household contract request; raise its refusal.""" try: @@ -243,9 +296,7 @@ def _side_request( # noqa: PLR0913 # the side and what it calculates "year": str(year), "household": situation, **job_policy_fields(reform=side_inputs.reform.values), - # A household report holds every value, as the Public API's - # stored-household route gives it. - "add_missing_variables": True, + **_variable_fields(variables), "bundle": worker.bundle, **_spm_fields(household.document), } 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..031565bab 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 @@ -16,7 +16,8 @@ report's run on the current versions that hasn't failed and wasn't forced, or else creates the report's new run naming each side's household simulation run on those versions, found or - inserted, as an economy report's re-run does (C1 · 24's answer 8). A + inserted, as an economy report's re-run does (C1 · 24's answer 8), each + simulation run it inserted recording the variables the re-run lists. A forced re-run, and every re-run of a report created before keys, whose runs may have been calculated for it alone (interim answer B), creates an extra report run and a new run of each side, all marked forced, @@ -36,6 +37,7 @@ from __future__ import annotations +from contextlib import contextmanager from dataclasses import dataclass, replace from typing import TYPE_CHECKING, Any, Protocol @@ -59,6 +61,7 @@ HouseholdReports, HouseholdReportSubmissionService, household_report_created, + listed_variables, ) from policyengine_simulation_entry.household_workers import ( ManifestHouseholdWorkers, @@ -67,7 +70,7 @@ from policyengine_simulation_entry.simulation_database import SimulationDatabase if TYPE_CHECKING: - from collections.abc import Mapping + from collections.abc import Iterator, Mapping, Sequence from uuid import UUID from policyengine_simulation_contract.household_report_execution import ( @@ -144,6 +147,7 @@ async def rerun_report( *, force: bool, observability_context: dict[str, Any] | None, + variables: Sequence[str] | None = None, ) -> HouseholdReportCreated: """Join or create the stored report's run, and start a run it created.""" ... @@ -160,10 +164,13 @@ async def rerun_report( *, force: bool, observability_context: dict[str, Any] | None, + variables: Sequence[str] | None = None, ) -> HouseholdReportCreated: """Join or create the stored report's run on the current versions. ``force``, or a report without keys, makes it an extra forced run. + Each simulation run it creates calculates ``variables``, sorted, or + every variable when it is None. A run it created is started; one it joined is answered as it is. Raise EconomyRecordNotFoundError (404) for a report deleted after it was read, and otherwise the errors ``submit_report`` raises, located @@ -201,6 +208,7 @@ async def rerun_report( baseline=new_sides["baseline"], reform=new_sides.get("reform"), forced=forced, + variables=listed_variables(variables), ) # Refused before anything is written, on the run IDs it proposes. _stored_report_calculation( @@ -211,6 +219,7 @@ async def rerun_report( for side, proposed in rerun.named_sides.items() }, worker=worker, + variables=rerun.variables, ) with rerun_refusals("report"): found = await self._create( @@ -224,7 +233,11 @@ async def rerun_report( status = await self._start_report_run( worker, _stored_report_calculation( - inputs, year=rerun.year, run_ids=run_ids, worker=worker + inputs, + year=rerun.year, + run_ids=run_ids, + worker=worker, + variables=rerun.variables, ), report_id=rerun.report_id, run_id=found.id, @@ -273,14 +286,24 @@ def _stored_report_calculation( year: int, run_ids: Mapping[ReportSide, UUID], worker: HouseholdWorker, + variables: tuple[str, ...] | None, ) -> HouseholdReportRunCalculation: """Build the re-run's household function payload, in the stored report's year. A household or policy the contract refuses is located at the stored report's fields rather than a request's. """ + with refusals_at_stored_report(): + return side_runs_calculation( + inputs, year=year, run_ids=run_ids, worker=worker, variables=variables + ) + + +@contextmanager +def refusals_at_stored_report() -> Iterator[None]: + """Locate a refusal of the household or policy at the stored report's fields.""" try: - return side_runs_calculation(inputs, year=year, run_ids=run_ids, worker=worker) + yield except EconomySubmissionUnprocessableError as error: raise EconomySubmissionUnprocessableError( code=error.code, 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 fce81e8f9..5ce10ed8b 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 @@ -11,12 +11,14 @@ worker's .py version, its model, the stored household and each side's policy and dynamic values, combined as an economy simulation's are, and checks each side's household contract request for - the household's ``default_year`` (on the run IDs it would propose); + the household's ``default_year`` (on the run IDs it would propose), of + the variables the request lists, sorted, or of every variable; 3. finds or creates, in one transaction, each side's household simulation by its key, the report by its key, which has no options, and its run on the current versions that hasn't failed and wasn't forced, or else the report run naming each side's simulation run on those versions, found - or inserted, all pending with no Modal call ID + or inserted, all pending with no Modal call ID, each simulation run it + inserted recording the listed variables (``find_or_create_household_report``); 4. for a report run it created, starts one household function call with ``spawn``, passing the report run's ID and both sides' requests, each @@ -65,6 +67,7 @@ SimulationChoice, UnknownCatalogVersionError, UnknownHouseholdError, + recorded_variables, ) from sqlalchemy.exc import SQLAlchemyError @@ -128,8 +131,8 @@ CALL_START_TIMEOUT_SECONDS = 10.0 -class HouseholdReports(Protocol): - """The household report reads and writes (``HouseholdReportStore``).""" +class HouseholdInputReads(Protocol): + """A household report's input read (``HouseholdReportStore``).""" def read_inputs( self, @@ -142,6 +145,10 @@ def read_inputs( """Read the catalog version, household and each side's values together.""" ... + +class HouseholdReports(HouseholdInputReads, Protocol): + """The household report reads and writes (``HouseholdReportStore``).""" + def find_or_create_report( self, report: KeyedHouseholdReport ) -> FoundHouseholdReport: @@ -216,7 +223,8 @@ def household_report_created( # noqa: PLR0913 # the report, its run and each s ) -def _database_unavailable() -> EconomySubmissionUnavailableError: +def database_unavailable() -> EconomySubmissionUnavailableError: + """Return the 503 answering a simulation database that cannot be read.""" return EconomySubmissionUnavailableError( code="database_unavailable", detail="The simulation database could not be read." ) @@ -272,6 +280,11 @@ def _read_refusal( ) +def listed_variables(variables: Sequence[str] | None) -> tuple[str, ...] | None: + """Return the variables a request lists as its runs record them: sorted.""" + return None if variables is None else tuple(recorded_variables(variables)) + + def _report_year(household: StoredHousehold) -> int: """Return the year a new report calculates: the household's default year.""" if household.default_year is None: @@ -285,6 +298,76 @@ def _report_year(household: StoredHousehold) -> int: return household.default_year +async def default_report_worker( + workers: HouseholdWorkerSource, country: str +) -> HouseholdWorker: + """Return the default worker's household function for the country. + + Raise EconomySubmissionRefusedError (``no_household_function``) when it + has none, and EconomySubmissionUnavailableError when the manifest cannot + be read. + """ + try: + return await asyncio.to_thread(workers.default_worker, country) + except HouseholdFunctionUnavailableError: + raise EconomySubmissionRefusedError( + code="no_household_function", + detail=f"The default v2 worker has no household function for {country}.", + ) from None + except VersionManifestUnavailableError as error: + logger.warning( + "household_report_manifest_unavailable", + extra=log_extra(error_type=type(error.__cause__).__name__), + ) + raise EconomySubmissionUnavailableError( + code="manifest_unavailable", + detail="The v2 version manifest could not be read.", + ) from None + + +async def read_report_inputs( # noqa: PLR0913 # the store, then what the report names + store: HouseholdInputReads, + *, + country: str, + household_id: UUID, + choices: Mapping[ReportSide, SimulationChoice], + worker: HouseholdWorker, + source: RefusalSource = REQUEST_BODY, +) -> HouseholdReportInputs: + """Read a household report's inputs; answer each refusal as ``source``'s error. + + See ``HouseholdReportStore.read_inputs``; the catalog version is the one + for ``worker``'s .py version. A database that cannot be read answers + EconomySubmissionUnavailableError (``database_unavailable``). + """ + policyengine_version = worker.bundle.policyengine_version + try: + return await asyncio.to_thread( + lambda: store.read_inputs( + country=country, + household_id=household_id, + choices=choices, + policyengine_version=policyengine_version, + ) + ) + except SQLAlchemyError as error: + logger.warning( + "household_report_inputs_unreadable", + extra=log_extra(error_type=type(error).__name__), + ) + raise database_unavailable() from None + except Exception as error: + refusal = _read_refusal( + error, + country=country, + policyengine_version=policyengine_version, + source=source, + ) + if refusal is None: + raise + raise refusal from None + + class HouseholdReportSubmissionService[Store: HouseholdReports = HouseholdReports]: """Create household reports and start the household function call for each. @@ -341,7 +424,11 @@ async def submit_report( status = await self._start_report_run( worker, side_runs_calculation( - inputs, year=year, run_ids=run_ids, worker=worker + inputs, + year=year, + run_ids=run_ids, + worker=worker, + variables=report.variables, ), report_id=found.report_id, run_id=found.run.id, @@ -385,28 +472,12 @@ async def _prepare_report( for side, proposed in report.proposed_sides.items() }, worker=worker, + variables=report.variables, ) 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) - except HouseholdFunctionUnavailableError: - raise EconomySubmissionRefusedError( - code="no_household_function", - detail=( - f"The default v2 worker has no household function for {country}." - ), - ) from None - except VersionManifestUnavailableError as error: - logger.warning( - "household_report_manifest_unavailable", - extra=log_extra(error_type=type(error.__cause__).__name__), - ) - raise EconomySubmissionUnavailableError( - code="manifest_unavailable", - detail="The v2 version manifest could not be read.", - ) from None + return await default_report_worker(self._workers, country) async def _read_inputs( self, @@ -418,32 +489,14 @@ async def _read_inputs( source: RefusalSource = REQUEST_BODY, ) -> HouseholdReportInputs: """Read the report's inputs; answer each refusal as ``source``'s error.""" - policyengine_version = worker.bundle.policyengine_version - try: - return await asyncio.to_thread( - lambda: self._store.read_inputs( - country=country, - household_id=household_id, - choices=choices, - policyengine_version=policyengine_version, - ) - ) - except SQLAlchemyError as error: - logger.warning( - "household_report_inputs_unreadable", - extra=log_extra(error_type=type(error).__name__), - ) - raise _database_unavailable() from None - except Exception as error: - refusal = _read_refusal( - error, - country=country, - policyengine_version=policyengine_version, - source=source, - ) - if refusal is None: - raise - raise refusal from None + return await read_report_inputs( + self._store, + country=country, + household_id=household_id, + choices=choices, + worker=worker, + source=source, + ) def _keyed_report( self, @@ -455,7 +508,7 @@ def _keyed_report( The report calculates the household's default year, and has no options (``reports.inputs`` is empty). Each side's key names its - policy and dynamic. + policy and dynamic. Its runs calculate the listed variables, sorted. """ report_id, run_id = self._new_id(), self._new_id() choices = _side_choices(request) @@ -483,6 +536,7 @@ def _keyed_report( country_package_version=worker.bundle.country_package_version, policyengine_version=worker.bundle.policyengine_version, ), + variables=listed_variables(request.variables), ) async def _create[Created]( @@ -517,7 +571,7 @@ async def _create[Created]( "household_report_not_created", extra=log_extra(error_type=type(error).__name__), ) - raise _database_unavailable() from None + raise database_unavailable() from None async def _start_report_run( # noqa: PLR0913 # the call, then the runs it calculates self, @@ -629,12 +683,17 @@ async def _fail_unconfirmed( # stay importable here. __all__ = [ "CALL_START_TIMEOUT_SECONDS", + "HouseholdInputReads", "HouseholdReportBuildError", "HouseholdReportSideInputs", "HouseholdReportSideRuns", "HouseholdReportSubmissionService", "HouseholdReports", + "database_unavailable", + "default_report_worker", "household_report_calculation", "household_report_created", + "listed_variables", + "read_report_inputs", "side_runs_calculation", ] diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_run_calculation_api_models.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_run_calculation_api_models.py new file mode 100644 index 000000000..bc8b0bb5f --- /dev/null +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_run_calculation_api_models.py @@ -0,0 +1,61 @@ +"""The request and answer of a household report run's extra calculations. + +``POST /reports/{report_id}/runs/{report_run_id}/household-calculations`` +calculates other variables of each side's simulation run, or its household +across axes, under the run's household, policy, dynamic, year and +versions. The answer names each side's extra calculation, found or created, +and its status; the household function records the calculated household on +it. +""" + +from __future__ import annotations + +from uuid import UUID + +from policyengine_simulation_contract.household_execution import Axes +from policyengine_simulation_persistence import SimulationStatus +from pydantic import BaseModel, ConfigDict + +from policyengine_simulation_entry.economy_api_models import ReportVariables + + +class HouseholdRunCalculationRequest(BaseModel): + """The variables to calculate on each side's run, and any axes to vary. + + ``variables`` names at least one variable, each once and none with a NUL + character. ``axes`` varies + inputs across points as a household calculation's axes do; without it, + the household is calculated as stored. Identical requests, whatever + their order of variables, share one calculation per run that hasn't + failed. + """ + + model_config = ConfigDict(extra="forbid", frozen=True, allow_inf_nan=False) + + variables: ReportVariables + axes: Axes = None + + +class _Answer(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + +class HouseholdRunCalculationState(_Answer): + """One side's extra calculation, the simulation run it is of, and its status.""" + + household_run_calculation_id: UUID + simulation_run_id: UUID + status: SimulationStatus + + +class HouseholdRunCalculationsCreated(_Answer): + """Each side's extra calculation of the report run. + + ``reform`` is null for a report of the baseline alone. Sides naming one + simulation run name one calculation. + """ + + report_id: UUID + report_run_id: UUID + baseline: HouseholdRunCalculationState + reform: HouseholdRunCalculationState | None diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_run_calculation_routes.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_run_calculation_routes.py new file mode 100644 index 000000000..c2a04aaf7 --- /dev/null +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_run_calculation_routes.py @@ -0,0 +1,272 @@ +"""The route that finds or starts a household report run's extra calculations. + +``POST /reports/{report_id}/runs/{report_run_id}/household-calculations`` +(permission ``simulation:submit``) calculates the listed variables of each +side's simulation run of a household report run, or its household across +the given axes, under the run's household, policy, dynamic, year and +versions. For each distinct simulation run it finds the extra calculation of +the same variables and axes that hasn't failed, or creates one and starts +its household function call, answering 201 with each side's calculation and +its status; API v1 reads the calculated household from the calculation's +row. A calculation Modal refused is answered failed, and the next identical +request starts another. + +It answers 404 for an unknown report or run, 409 for a run that failed or +one on other versions than the default worker's, and 422 for a report that +is not a household report or a calculation the household contract refuses; +then nothing is written. The other answers are a household report re-run's: 400 +when a row the stored report names is missing, 503 with ``Retry-After`` +before any write, and the JSON 500, which says when the calculations +may have been written. +""" + +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING, Any, Protocol +from uuid import UUID + +from fastapi import APIRouter, Depends, Request, status +from fastapi.responses import JSONResponse +from policyengine_simulation_observability.log_records import log_extra + +from policyengine_simulation_entry.economy_api_models import ( + EconomyError, + EconomyRequestUnprocessable, +) +from policyengine_simulation_entry.economy_routes import ( + ERROR_ANSWER, + FORBIDDEN_ANSWER, + RETRY_AFTER_HEADER, + SUBMISSION_FAILURES, + error_response, + not_configured_response, + submission_failure_response, + unexpected_failure_response, + unknown_record_response, +) +from policyengine_simulation_entry.economy_submission_errors import ( + EconomyRecordNotFoundError, + EconomyRerunConflictError, +) +from policyengine_simulation_entry.household_run_calculation_api_models import ( + HouseholdRunCalculationRequest, + HouseholdRunCalculationsCreated, +) +from policyengine_simulation_entry.household_run_calculations import ( + HouseholdRunCalculationsOutcomeUnknownError, + ReportRunNotFoundError, +) +from policyengine_simulation_entry.route_support import observability_context + +if TYPE_CHECKING: + from fastapi import FastAPI + + from policyengine_simulation_entry.auth import AuthorizationDependency + from policyengine_simulation_entry.entry_runtime import EntryRuntime + +logger = logging.getLogger(__name__) + +HOUSEHOLD_RUN_CALCULATIONS_PATH = ( + "/reports/{report_id}/runs/{report_run_id}/household-calculations" +) + + +class HouseholdRunCalculationCreates(Protocol): + """Find or start extra calculations (``HouseholdRunCalculationService``).""" + + async def create_calculations( + self, + report_id: UUID, + report_run_id: UUID, + request: HouseholdRunCalculationRequest, + *, + observability_context: dict[str, Any] | None, + ) -> HouseholdRunCalculationsCreated: + """Find or start each side's extra calculation of the report run.""" + ... + + +_RESPONSES: dict[int | str, dict[str, Any]] = { + 201: { + "description": ( + "Each side's extra calculation: one found that hasn't failed, " + "pending, running or succeeded, which gets no new call, or one " + "created and started, or failed at once when Modal refused its call" + ) + }, + 400: { + "description": ( + "A row the stored report names, such as its household, policy or " + "dynamic, or the default worker's household function or catalog " + "version, is missing; nothing was written" + ), + **ERROR_ANSWER, + }, + 403: FORBIDDEN_ANSWER, + 404: { + "description": ( + "There is no such report (code unknown_report), or the report has " + "no run of that ID (code unknown_report_run)" + ), + **ERROR_ANSWER, + }, + 409: { + "description": ( + "The run failed (report_run_failed), or calculated on other " + "versions than the default worker's (report_run_not_current): " + "re-run the report first; or the stored report lacks a row its " + "runs calculate on (rerun_not_supported). Nothing was written" + ), + **ERROR_ANSWER, + }, + 422: { + "description": ( + "The IDs or the body are malformed; or the report is not a " + "household report (household_calculations_not_available, located " + "at the path's report_id); or the stored household or policies " + "cannot be calculated (household_not_calculable, " + "missing_parameters or overlapping_parameters, located under " + "report). Nothing was written" + ), + "model": EconomyRequestUnprocessable, + }, + 500: { + "description": ( + "The service failed unexpectedly, or could not confirm the " + "calculations were written (internal_error), possibly after " + "creating them; an identical request finds them" + ), + **ERROR_ANSWER, + }, + 503: { + "description": ( + "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, + }, +} + + +def _failure_response( + error: Exception, report_id: UUID, report_run_id: UUID +) -> JSONResponse: + """Answer a request the service refused or could not serve.""" + if isinstance(error, EconomyRecordNotFoundError): + return unknown_record_response("report", report_id) + if isinstance(error, ReportRunNotFoundError): + return error_response( + status.HTTP_404_NOT_FOUND, + EconomyError( + code="unknown_report_run", + detail=f"Report {report_id} has no run {report_run_id}.", + ), + ) + if isinstance(error, EconomyRerunConflictError): + return error_response( + status.HTTP_409_CONFLICT, + EconomyError(code=error.code, detail=error.detail), + ) + if isinstance(error, HouseholdRunCalculationsOutcomeUnknownError): + return _outcome_unknown_response(error) + return submission_failure_response(error, "report") + + +def _outcome_unknown_response( + error: HouseholdRunCalculationsOutcomeUnknownError, +) -> JSONResponse: + """Answer calculations whose commit can't be confirmed with the JSON 500. + + The log is the fixed event ``household_run_calculations_outcome_unknown`` + with the commit error's type, never its text, as + ``economy_record_outcome_unknown`` logs. + """ + logger.error( + "household_run_calculations_outcome_unknown", + extra=log_extra(error_type=error.error_type), + ) + return error_response( + status.HTTP_500_INTERNAL_SERVER_ERROR, + EconomyError( + code="internal_error", + detail=( + "The service may have created the report run's extra " + "calculations, but could not confirm they were written. An " + "identical request finds them." + ), + ), + ) + + +_FAILURES = ( + *SUBMISSION_FAILURES, + EconomyRecordNotFoundError, + ReportRunNotFoundError, + EconomyRerunConflictError, + HouseholdRunCalculationsOutcomeUnknownError, +) + + +def add_household_run_calculation_routes( + app: FastAPI, + entry: EntryRuntime, + calculations: HouseholdRunCalculationCreates | None, + *, + submitter: AuthorizationDependency, +) -> None: + """Add the extra calculation route; without a service it answers 503.""" + log_string_limit = entry.runtime.config.limits.max_string_length + router = APIRouter() + + @router.post( + HOUSEHOLD_RUN_CALCULATIONS_PATH, + summary="Calculate other variables of a household report run", + description=( + "Calculate the listed variables of each side's simulation run of " + "the household report run, or its household across the given axes, " + "under the run's household, policy, dynamic, year and versions. " + "Each distinct simulation run gets one extra calculation of the " + "same variables and axes that hasn't failed: one found is answered " + "as it is, and one created is started by a household function " + "call. API v1 reads the calculated household from the " + "calculation's row." + ), + operation_id="create_household_run_calculations", + status_code=status.HTTP_201_CREATED, + response_model=HouseholdRunCalculationsCreated, + responses=_RESPONSES, + dependencies=[Depends(submitter)], + ) + async def create_household_run_calculations( + report_id: UUID, + report_run_id: UUID, + body: HouseholdRunCalculationRequest, + request: Request, + ) -> JSONResponse: + if calculations is None: + return not_configured_response("Household reports are not configured.") + observability_id = entry.start_workflow_observability(request) + try: + created = await calculations.create_calculations( + report_id, + report_run_id, + body, + observability_context=observability_context(entry, observability_id), + ) + except _FAILURES as error: + return _failure_response(error, report_id, report_run_id) + # 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( + HOUSEHOLD_RUN_CALCULATIONS_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/household_run_calculations.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_run_calculations.py new file mode 100644 index 000000000..951acd4e1 --- /dev/null +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_run_calculations.py @@ -0,0 +1,525 @@ +"""Find or start extra calculations of a household report run's simulation runs. + +An extra calculation calculates other variables of a household report +run's simulation run, or its household across axes, under the run's +household, policy, dynamic, year and versions. ``HouseholdRunCalculationService``: + +1. reads, in one transaction, the stored report and the run, refusing an + unknown report (404 ``unknown_report``), a report that is not a household + report (422 ``household_calculations_not_available``), a run the report + doesn't have (404 ``unknown_report_run``) and a run that failed (409 + ``report_run_failed``): the report is re-run first. A pending, running or + succeeded run gets extra calculations, and one failing after they started + doesn't stop them; +2. finds the v2 version manifest's default worker's household function for + the country, and refuses a run on other versions than that worker's + (409 ``report_run_not_current``): the report is re-run first, so an + extra calculation always matches its run; +3. reads, in one transaction, the stored household and each side's policy + and dynamic values, as a household report's re-run does, and builds each + distinct simulation run's household contract request, refusing what + cannot be calculated located at the stored report; +4. finds, in one transaction, each run's extra calculation of the same + variables and axes that hasn't failed, or inserts one pending with no + Modal call (``find_or_insert_household_run_calculations``); +5. for each calculation it inserted, starts one household function call + with the calculation's ID and request, then records the call's ID while + it is still pending with none. When Modal refuses the call, or does not + confirm it in time, it fails the calculation at once, under the same + condition, and answers it failed, so the next identical request inserts + another, as a cliff calculation is answered. A calculation it found gets + no call, and is answered with its status as read. + +Nothing is written before step 4. The household function claims the +calculation under its call and records the calculated household on it; the +stuck-run sweep fails one no call finishes. +""" + +from __future__ import annotations + +import asyncio +import logging +from typing import TYPE_CHECKING, Any, Final, Protocol +from uuid import UUID, uuid4 + +from policyengine_simulation_observability.log_records import ( + database_row_attributes, + log_extra, +) +from policyengine_simulation_persistence import ( + EconomyRecordOutcomeUnknownError, + EconomyRecordReferenceError, + HouseholdRunCalculationStore, + NewHouseholdRunCalculation, + ReportRunStatus, + RunVersions, + SharedRowNotSettledError, + SimulationStatus, + recorded_variables, +) +from sqlalchemy.exc import SQLAlchemyError + +from policyengine_simulation_entry.economy_submission_errors import ( + STORED_REPORT, + EconomyRecordNotFoundError, + EconomyRerunConflictError, + EconomySubmissionUnprocessableError, + UnprocessableReason, +) +from policyengine_simulation_entry.household_report_calculations import ( + HouseholdReportSideInputs, + household_run_calculation_request, +) +from policyengine_simulation_entry.household_report_reruns import ( + STATEMENT_TIMEOUT_MILLISECONDS, + refusals_at_stored_report, +) +from policyengine_simulation_entry.household_report_submissions import ( + CALL_START_TIMEOUT_SECONDS, + HouseholdInputReads, + database_unavailable, + default_report_worker, + read_report_inputs, +) +from policyengine_simulation_entry.household_run_calculation_api_models import ( + HouseholdRunCalculationsCreated, + HouseholdRunCalculationState, +) +from policyengine_simulation_entry.household_workers import ( + ManifestHouseholdWorkers, + ModalHouseholdFunctionCaller, +) +from policyengine_simulation_entry.rerunnable_records import ( + rerunnable_household_report, +) +from policyengine_simulation_entry.simulation_database import SimulationDatabase + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + from policyengine_simulation_contract.household_execution import ( + HouseholdExecutionRequest, + ) + from policyengine_simulation_persistence import ( + FoundHouseholdRunCalculation, + HouseholdReportInputs, + ReportSide, + ReportWithRun, + SideRun, + StoredReportRun, + ) + + from policyengine_simulation_entry.config import Settings + from policyengine_simulation_entry.economy_submission_errors import RecordName + from policyengine_simulation_entry.entry_runtime import ( + SimulationDatabaseConnection, + ) + from policyengine_simulation_entry.household_report_reruns import ( + StoredHouseholdReport, + ) + from policyengine_simulation_entry.household_run_calculation_api_models import ( + HouseholdRunCalculationRequest, + ) + from policyengine_simulation_entry.household_workers import ( + HouseholdRunCalculationCaller, + HouseholdWorker, + HouseholdWorkerSource, + ) + +logger = logging.getLogger(__name__) + +_REPORT: Final[RecordName] = "report" + + +class ReportRunNotFoundError(LookupError): + """The report has no run of the ID a request names (404).""" + + def __init__(self, report_run_id: UUID) -> None: + """Keep the run's ID.""" + super().__init__(f"no report run {report_run_id}") + self.report_run_id = report_run_id + + +class HouseholdRunCalculationsOutcomeUnknownError(Exception): + """The calculations may have been written, but that can't be confirmed. + + The commit failed after the rows were inserted, or after they were + found. The route answers 500, which API v1 reads as rows that may + exist, never a 503, which it reads as nothing created; an identical + request finds them. No call was started. + """ + + def __init__(self, *, error_type: str) -> None: + """Keep the commit error's type.""" + super().__init__("the extra calculations may have been created") + self.error_type = error_type + + +class HouseholdRunCalculationRows(HouseholdInputReads, Protocol): + """The reads and writes of extra calculations (``HouseholdRunCalculationStore``).""" + + def read_report_with_run( + self, report_id: UUID, report_run_id: UUID + ) -> ReportWithRun: + """Read the stored report and its run together.""" + ... + + def find_or_create_calculations( + self, proposed: Sequence[NewHouseholdRunCalculation] + ) -> dict[UUID, FoundHouseholdRunCalculation]: + """Find each run's calculation of its request, or insert it pending.""" + ... + + def record_calculation_call( + self, calculation_id: UUID, modal_call_id: str + ) -> SimulationStatus | None: + """Record the calculation's call ID while it is pending with none.""" + ... + + def fail_unstarted_calculation( + self, calculation_id: UUID, error_message: str + ) -> bool: + """Fail the calculation while it is pending with no call ID.""" + ... + + +def _not_a_household_report() -> EconomySubmissionUnprocessableError: + return EconomySubmissionUnprocessableError( + code="household_calculations_not_available", + reasons=( + UnprocessableReason( + loc=("path", "report_id"), + msg=( + "Only a household report's runs calculate a household, so " + "only they have extra calculations." + ), + type="household_calculations_not_available", + ), + ), + ) + + +def _axes_json(request: HouseholdRunCalculationRequest) -> list[Any] | None: + """Return the request's axes as the contract writes them, or None for none.""" + if request.axes is None: + return None + return [[axis.model_dump(mode="json") for axis in group] for group in request.axes] + + +def _side_runs( + stored: StoredHouseholdReport, run: StoredReportRun +) -> dict[ReportSide, SideRun]: + """Return each side's simulation run the report run names. + + Raise ValueError for a run that names a side the report lacks, or none + for one it has: a household report run names each side's run. + """ + named = {"baseline": run.baseline, "reform": run.reform} + side_runs: dict[ReportSide, SideRun] = {} + for side in ("baseline", "reform"): + side_run = named[side] + if (side_run is None) != (side not in stored.sides): + msg = f"report run {run.id} names its {side} run unlike its report" + raise ValueError(msg) + if side_run is not None: + side_runs[side] = side_run + return side_runs + + +class HouseholdRunCalculationService: + """Find or start extra calculations of household report runs. + + The database and the manifest are read on threads, so the event loop + never waits on them. + """ + + def __init__( + self, + *, + store: HouseholdRunCalculationRows, + workers: HouseholdWorkerSource, + caller: HouseholdRunCalculationCaller, + call_start_timeout_seconds: float = CALL_START_TIMEOUT_SECONDS, + new_id: Callable[[], UUID] = uuid4, + ) -> None: + """Use these seams; tests replace each of them.""" + self._store = store + self._workers = workers + self._caller = caller + self._call_start_timeout_seconds = call_start_timeout_seconds + self._new_id = new_id + + async def create_calculations( + self, + report_id: UUID, + report_run_id: UUID, + request: HouseholdRunCalculationRequest, + *, + observability_context: dict[str, Any] | None, + ) -> HouseholdRunCalculationsCreated: + """Find or start each side's extra calculation of the report run. + + Raise EconomyRecordNotFoundError or ReportRunNotFoundError (404), + EconomyRerunConflictError (409), EconomySubmissionUnprocessableError + (422), or EconomySubmissionRefusedError (400) and + EconomySubmissionUnavailableError (503) as a household report's + re-run does, all before anything is written but a run deleted after + its read (404); and HouseholdRunCalculationsOutcomeUnknownError + (500) when the calculations' commit can't be confirmed. + """ + stored, run = await self._read_report_run(report_id, report_run_id) + if run.status is ReportRunStatus.FAILED: + raise EconomyRerunConflictError( + code="report_run_failed", + detail=f"Report run {report_run_id} failed. Re-run the report first.", + ) + side_runs = _side_runs(stored, run) + worker = await default_report_worker(self._workers, stored.country) + current = RunVersions( + country_package_version=worker.bundle.country_package_version, + policyengine_version=worker.bundle.policyengine_version, + ) + if run.versions != current: + raise EconomyRerunConflictError( + code="report_run_not_current", + detail=( + f"Report run {report_run_id} calculated on other versions than " + "the default worker's. Re-run the report first." + ), + ) + inputs = await read_report_inputs( + self._store, + country=stored.country, + household_id=stored.household_id, + choices={ + side: definition.choice for side, definition in stored.sides.items() + }, + worker=worker, + source=STORED_REPORT, + ) + variables = tuple(recorded_variables(request.variables)) + axes = _axes_json(request) + proposed: dict[UUID, NewHouseholdRunCalculation] = {} + requests: dict[UUID, HouseholdExecutionRequest] = {} + for side, side_run in side_runs.items(): + run_id = side_run.simulation_run_id + if run_id in proposed: + # A policy compared with itself: both sides name one run. + continue + calculation_id = self._new_id() + proposed[run_id] = NewHouseholdRunCalculation( + id=calculation_id, + simulation_run_id=run_id, + simulation_id=side_run.simulation_id, + variables=variables, + axes=axes, + ) + # Refused before anything is written. + requests[run_id] = _calculation_request( + inputs, + side, + calculation_id=calculation_id, + year=stored.year, + worker=worker, + variables=variables, + axes=axes, + ) + found = await self._find_or_create(report_run_id, list(proposed.values())) + states: dict[UUID, HouseholdRunCalculationState] = {} + # The baseline's call is started first. + for run_id in proposed: + calculation = found[run_id] + status = calculation.status + if calculation.inserted: + status = await self._start( + worker, + requests[run_id], + calculation_id=calculation.id, + observability_context=observability_context, + ) + states[run_id] = HouseholdRunCalculationState( + household_run_calculation_id=calculation.id, + simulation_run_id=run_id, + status=status, + ) + reform = side_runs.get("reform") + return HouseholdRunCalculationsCreated( + report_id=report_id, + report_run_id=report_run_id, + baseline=states[side_runs["baseline"].simulation_run_id], + reform=None if reform is None else states[reform.simulation_run_id], + ) + + async def _read_report_run( + self, report_id: UUID, report_run_id: UUID + ) -> tuple[StoredHouseholdReport, StoredReportRun]: + """Read the stored household report and its run; refuse either missing.""" + try: + read = await asyncio.to_thread( + self._store.read_report_with_run, report_id, report_run_id + ) + except SQLAlchemyError as error: + logger.warning( + "household_run_calculation_report_unreadable", + extra=log_extra(error_type=type(error).__name__), + ) + raise database_unavailable() from None + if read.definition is None: + raise EconomyRecordNotFoundError(_REPORT) + if read.definition.kind != "household": + raise _not_a_household_report() + if read.run is None: + raise ReportRunNotFoundError(report_run_id) + return rerunnable_household_report(read.definition), read.run + + async def _find_or_create( + self, report_run_id: UUID, proposed: list[NewHouseholdRunCalculation] + ) -> dict[UUID, FoundHouseholdRunCalculation]: + """Find or insert the calculations; a run deleted since its read is unknown.""" + try: + return await asyncio.to_thread( + self._store.find_or_create_calculations, proposed + ) + except EconomyRecordReferenceError: + raise ReportRunNotFoundError(report_run_id) from None + except EconomyRecordOutcomeUnknownError as error: + # The route logs it, with the commit error's type. + raise HouseholdRunCalculationsOutcomeUnknownError( + error_type=type(error.__cause__).__name__ + ) from None + # A calculation kept failing between a lookup's insert and its read; + # its transaction wrote nothing, so the caller may ask again. + except (SharedRowNotSettledError, SQLAlchemyError) as error: + logger.warning( + "household_run_calculations_not_created", + extra=log_extra(error_type=type(error).__name__), + ) + raise database_unavailable() from None + + async def _start( + self, + worker: HouseholdWorker, + request: HouseholdExecutionRequest, + *, + calculation_id: UUID, + observability_context: dict[str, Any] | None, + ) -> SimulationStatus: + """Start the calculation's household function call and record it, or fail it. + + Return the calculation's status: failed when Modal didn't confirm the + call and the failure was written, pending otherwise. + """ + try: + call_id = await asyncio.wait_for( + self._caller.start_household_run_calculation( + worker, + request.model_dump(mode="json"), + household_run_calculation_id=calculation_id, + observability_context=observability_context, + ), + timeout=self._call_start_timeout_seconds, + ) + # Modal raises its own errors; any of them, or the timeout, means the + # call was not confirmed, and the calculation is failed unless it + # has started. + except Exception as error: # noqa: BLE001 # every unconfirmed call is answered alike + failed = await self._fail_unconfirmed(error, calculation_id) + return SimulationStatus.FAILED if failed else SimulationStatus.PENDING + try: + status = await asyncio.to_thread( + self._store.record_calculation_call, calculation_id, call_id + ) + except SQLAlchemyError as error: + # The household function claims a pending calculation with no + # call ID itself, so the calculation goes ahead either way. + logger.warning( + "household_run_calculation_call_not_recorded", + extra=log_extra( + error_type=type(error).__name__, + **database_row_attributes( + "household_run_calculations", calculation_id + ), + ), + ) + return SimulationStatus.PENDING + return SimulationStatus.PENDING if status is None else status + + async def _fail_unconfirmed( + self, error: BaseException, calculation_id: UUID + ) -> bool: + """Fail the calculation of a call Modal didn't confirm, unless it started. + + Return whether it was failed. When the write itself fails, the + calculation is left pending for the stuck-run sweep. + """ + row = database_row_attributes("household_run_calculations", calculation_id) + # The log names the error type only; its text could repeat request data. + logger.error( + "household_run_calculation_call_unconfirmed", + extra=log_extra(error_type=type(error).__name__, **row), + ) + message = ( + "modal_call_refused: Modal did not accept the extra calculation's " + f"call ({type(error).__name__})." + ) + try: + return await asyncio.to_thread( + self._store.fail_unstarted_calculation, calculation_id, message + ) + except SQLAlchemyError as write_error: + logger.warning( + "household_run_calculation_not_failed", + extra=log_extra(error_type=type(write_error).__name__, **row), + ) + return False + + +def _calculation_request( # noqa: PLR0913 # the inputs and side, then what is calculated + inputs: HouseholdReportInputs, + side: ReportSide, + *, + calculation_id: UUID, + year: int, + worker: HouseholdWorker, + variables: tuple[str, ...], + axes: list[Any] | None, +) -> HouseholdExecutionRequest: + """Build one side's extra calculation request, refusals at the stored report.""" + with refusals_at_stored_report(): + return household_run_calculation_request( + side, + HouseholdReportSideInputs( + simulation_run_id=calculation_id, reform=inputs.reforms[side] + ), + household=inputs.household, + year=year, + worker=worker, + variables=variables, + axes=axes, + ) + + +def household_run_calculations_for( + settings: Settings, database: SimulationDatabaseConnection | None +) -> HouseholdRunCalculationService | None: + """Build the extra calculation service as the household report one is. + + It needs the simulation database and the v2 Modal environment; without + them the route answers 503. Nothing is read from Modal until the first + request. + """ + if not settings.household_calculations_configured or not isinstance( + database, SimulationDatabase + ): + return None + return HouseholdRunCalculationService( + store=HouseholdRunCalculationStore.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), + ) diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_workers.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_workers.py index 0ec81bcd4..764e5ec7d 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_workers.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_workers.py @@ -87,6 +87,21 @@ async def start_report_run( ... +class HouseholdRunCalculationCaller(Protocol): + """Start an extra calculation's call (``ModalHouseholdFunctionCaller``).""" + + async def start_household_run_calculation( + self, + worker: HouseholdWorker, + payload: dict[str, Any], + *, + household_run_calculation_id: UUID, + observability_context: dict[str, Any] | None, + ) -> str: + """Start the call without waiting for it and return its Modal call ID.""" + ... + + def default_household_worker( manifest: V2VersionManifest, country: str ) -> HouseholdWorker: @@ -199,6 +214,27 @@ async def start_report_run( observability_context=observability_context, ) + async def start_household_run_calculation( + self, + worker: HouseholdWorker, + payload: dict[str, Any], + *, + household_run_calculation_id: UUID, + observability_context: dict[str, Any] | None, + ) -> str: + """Start the household function on an extra calculation of a household run. + + ``payload`` is the calculation's ``HouseholdExecutionRequest``. + Return the call's Modal call ID; raise RuntimeError when Modal + returns none. + """ + return await self._spawn( + worker, + payload, + household_run_calculation_id=str(household_run_calculation_id), + observability_context=observability_context, + ) + async def _spawn( self, worker: HouseholdWorker, payload: dict[str, Any], **keywords: object ) -> str: 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 a6457208f..86e8ff509 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 @@ -13,7 +13,8 @@ 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 +for ``include_cliffs: true`` (``cliffs_not_available``) and for a household +report's ``variables`` (``variables_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. @@ -82,8 +83,9 @@ "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" + "carry POST /reports' codes; include_cliffs: true is refused " + "with cliffs_not_available, and a household report's variables " + "with variables_not_available" ), "model": EconomyRequestUnprocessable, }, 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 63f010038..c78c2f67b 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 @@ -18,7 +18,9 @@ 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. +there is none. So is a household report listing ``variables`` (422 +``variables_not_available``): each simulation run records the list, and +the report's first run lists its own. The services are built apart from those that create runs (``economy_reports_without_run_for``, ``household_reports_without_run_for``), @@ -130,6 +132,25 @@ def refuse_cliffs_without_run(request: EconomyReportRequest) -> None: ) +def refuse_variables_without_run(request: HouseholdReportRequest) -> None: + """Refuse a household report without a run that lists variables (422).""" + if request.variables is None: + return + raise EconomySubmissionUnprocessableError( + code="variables_not_available", + reasons=( + UnprocessableReason( + loc=("body", "variables"), + msg=( + "A report created without a run calculates no variables. " + "Leave variables out, and list them on the report's first run." + ), + type="variables_not_available", + ), + ), + ) + + def report_without_run_created( found: FoundReportWithoutRun, report_type: Literal["economy", "household"], @@ -217,10 +238,13 @@ async def create_report_without_run( ) -> 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. + Raise EconomySubmissionUnprocessableError (422) for a request listing + variables, 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. """ + refuse_variables_without_run(request) report = (await self._prepare_report(request)).report found = await self._create( lambda: self._store.find_or_create_report_without_run(report.without_run) diff --git a/projects/policyengine-simulation-entry/tests/test_household_report_variables.py b/projects/policyengine-simulation-entry/tests/test_household_report_variables.py new file mode 100644 index 000000000..f13b8824c --- /dev/null +++ b/projects/policyengine-simulation-entry/tests/test_household_report_variables.py @@ -0,0 +1,222 @@ +"""The variables a household report's runs calculate (D2 · 3b). + +A household report's create or re-run may list the variables to calculate; +without a list, each side calculates every variable, as before. The +service records the list, sorted, with each side's simulation run the +request inserts (the store's write is tested in the persistence library), +and each side's household contract request lists the variables instead of +adding every missing one. An economy or budget-window report's re-run +calculates no household variables, so listing them is refused. +""" + +from __future__ import annotations + +import asyncio +from dataclasses import replace + +import pytest +from economy_rerun_fakes import ( + BASELINE_SIMULATION_ID, + REFORM_SIMULATION_ID, + REPORT_ID, + STORED_REPORT, + STORED_WINDOW, + FakeRerunStore, + rerun_service, +) +from economy_service_fakes import FakeCaller +from household_report_fakes import ( + HOUSEHOLD_ID, + POLICY_ID, + FakeHouseholdReportCaller, + FakeHouseholdReportStore, + household_report_request, + household_report_service, + household_rerun_service, +) +from policyengine_simulation_contract.household_report_execution import ( + HouseholdReportRunCalculation, +) +from policyengine_simulation_entry.economy_api_models import ReportRerunRequest +from policyengine_simulation_entry.economy_submission_errors import ( + EconomySubmissionUnprocessableError, +) +from policyengine_simulation_persistence import ( + ReportDefinition, + SideDefinition, + SimulationChoice, +) +from pydantic import ValidationError + +LISTED = ["household_net_income", "employment_income", "age"] +RECORDED = ("age", "employment_income", "household_net_income") +CONTEXT = {"observability_id": "observed"} +STORED_HOUSEHOLD_REPORT = ReportDefinition( + id=REPORT_ID, + country="us", + kind="household", + year=2026, + region_code=None, + dataset_name=None, + inputs={}, + baseline=SideDefinition( + simulation_id=BASELINE_SIMULATION_ID, + choice=SimulationChoice(policy_id=None, dynamic_id=None), + ), + reform=SideDefinition( + simulation_id=REFORM_SIMULATION_ID, + choice=SimulationChoice(policy_id=POLICY_ID, dynamic_id=None), + ), + household_id=HOUSEHOLD_ID, + keyed=True, +) + + +def _submit(service, request): + return asyncio.run(service.submit_report(request, observability_context=CONTEXT)) + + +def _rerun(service, request: ReportRerunRequest): + return asyncio.run( + service.rerun_report( + REPORT_ID, request, request_id="observed", observability_context=CONTEXT + ) + ) + + +def test_a_household_report_may_list_the_variables_to_calculate() -> None: + assert household_report_request(variables=LISTED).variables == tuple(LISTED) + assert household_report_request().variables is None + assert ReportRerunRequest(variables=LISTED).variables == tuple(LISTED) + assert ReportRerunRequest().variables is None + + +@pytest.mark.parametrize( + "variables", + [[], ["age", "age"], [""], ["age\x00"]], + ids=["empty", "repeated", "unnamed", "nul"], +) +def test_an_empty_or_repeated_variable_list_is_refused(variables) -> None: + """Both tables refuse an empty list, and the contract a repeated name. + + A name with a NUL character is refused as ``/v2/household-calculations`` + refuses it (Anthony's answer to D2 · 3c's decision 2). + """ + with pytest.raises(ValidationError) as refused_create: + household_report_request(variables=variables) + with pytest.raises(ValidationError) as refused_rerun: + ReportRerunRequest(variables=variables) + + for refused in (refused_create, refused_rerun): + ((location, error_type),) = { + (error["loc"][0], error["type"]) for error in refused.value.errors() + } + # The list itself is refused, not an unknown field. + assert location == "variables" + assert error_type != "extra_forbidden" + + +def test_a_listed_report_records_its_variables_and_each_side_calculates_them(): + store = FakeHouseholdReportStore() + caller = FakeHouseholdReportCaller() + + _submit( + household_report_service(store, caller=caller), + household_report_request(variables=LISTED), + ) + + (report,) = store.keyed_reports + assert report.variables == RECORDED + ((_, payload, _, _),) = caller.calls + for side in ("baseline", "reform"): + assert payload[side]["variables"] == list(RECORDED) + assert payload[side]["add_missing_variables"] is False + HouseholdReportRunCalculation.model_validate(payload) + + +def test_a_report_without_a_list_records_none_and_calculates_every_variable(): + store = FakeHouseholdReportStore() + caller = FakeHouseholdReportCaller() + + _submit(household_report_service(store, caller=caller), household_report_request()) + + (report,) = store.keyed_reports + assert report.variables is None + ((_, payload, _, _),) = caller.calls + for side in ("baseline", "reform"): + assert "variables" not in payload[side] + assert payload[side]["add_missing_variables"] is True + + +@pytest.mark.parametrize("force", [False, True]) +def test_a_household_reports_rerun_records_and_calculates_its_listed_variables( + force, +) -> None: + households = FakeHouseholdReportStore() + caller = FakeHouseholdReportCaller() + service = rerun_service( + FakeRerunStore(report_definition=STORED_HOUSEHOLD_REPORT), + household_reports=household_rerun_service(households, caller=caller), + ) + + _rerun(service, ReportRerunRequest(force=force, variables=LISTED)) + + (rerun,) = households.report_reruns + assert (rerun.forced, rerun.variables) == (force, RECORDED) + ((_, payload, _, _),) = caller.calls + for side in ("baseline", "reform"): + assert payload[side]["variables"] == list(RECORDED) + assert payload[side]["add_missing_variables"] is False + + +def test_a_household_reports_rerun_without_a_list_records_none() -> None: + households = FakeHouseholdReportStore() + service = rerun_service( + FakeRerunStore(report_definition=STORED_HOUSEHOLD_REPORT), + household_reports=household_rerun_service(households), + ) + + _rerun(service, ReportRerunRequest()) + + (rerun,) = households.report_reruns + assert rerun.variables is None + + +@pytest.mark.parametrize( + "stored", + [STORED_REPORT, STORED_WINDOW], + ids=["economy", "budget-window"], +) +def test_a_rerun_listing_variables_of_a_report_without_households_is_refused( + stored, +) -> None: + store = FakeRerunStore(report_definition=stored) + caller = FakeCaller() + + with pytest.raises(EconomySubmissionUnprocessableError) as refused: + _rerun( + rerun_service(store, caller=caller), ReportRerunRequest(variables=LISTED) + ) + + assert refused.value.code == "variables_not_available" + ((reason,),) = (refused.value.reasons,) + assert (reason.loc, reason.type) == ( + ("body", "variables"), + "variables_not_available", + ) + assert (store.rerun_reads, store.report_reruns, store.windows) == ([], [], []) + assert caller.report_runs == [] + + +def test_a_household_report_without_keys_records_its_list_on_its_forced_runs(): + """A report created before keys is always re-run as forced runs.""" + households = FakeHouseholdReportStore() + service = rerun_service( + FakeRerunStore(report_definition=replace(STORED_HOUSEHOLD_REPORT, keyed=False)), + household_reports=household_rerun_service(households), + ) + + _rerun(service, ReportRerunRequest(variables=LISTED)) + + (rerun,) = households.report_reruns + assert (rerun.forced, rerun.variables) == (True, RECORDED) diff --git a/projects/policyengine-simulation-entry/tests/test_household_run_calculations.py b/projects/policyengine-simulation-entry/tests/test_household_run_calculations.py new file mode 100644 index 000000000..b1a7c562b --- /dev/null +++ b/projects/policyengine-simulation-entry/tests/test_household_run_calculations.py @@ -0,0 +1,705 @@ +"""Extra calculations of a household report run's simulation runs (D2 · 3b). + +``POST /reports/{report_id}/runs/{report_run_id}/household-calculations`` +finds, for each distinct side's simulation run, the extra calculation of +the same variables and axes that hasn't failed, or inserts one pending and +starts one household function call for it. The store and Modal are faked +here; the store's own reads and writes are tested in the persistence +library. +""" + +from __future__ import annotations + +import asyncio +from dataclasses import dataclass, field, replace +from typing import Any +from uuid import UUID + +import pytest +from conftest import FakeBackend, make_settings +from fastapi.testclient import TestClient +from household_report_fakes import ( + HOUSEHOLD_ID, + POLICY_ID, + REFORM, + SITUATION, + FakeHouseholdReportStore, + FakeHouseholdWorkers, + manifest_household_worker, + numbered_ids, +) +from policyengine_simulation_contract.household_execution import ( + HouseholdExecutionRequest, +) +from policyengine_simulation_entry import app as app_module +from policyengine_simulation_entry.app import create_app +from policyengine_simulation_entry.economy_submission_errors import ( + EconomyRecordNotFoundError, + EconomyRerunConflictError, + EconomySubmissionUnavailableError, + EconomySubmissionUnprocessableError, +) +from policyengine_simulation_entry.household_run_calculation_api_models import ( + HouseholdRunCalculationRequest, + HouseholdRunCalculationsCreated, + HouseholdRunCalculationState, +) +from policyengine_simulation_entry.household_run_calculations import ( + HouseholdRunCalculationService, + ReportRunNotFoundError, + household_run_calculations_for, +) +from policyengine_simulation_entry.simulation_database import SimulationDatabase +from policyengine_simulation_persistence import ( + EconomyRecordOutcomeUnknownError, + EconomyRecordReferenceError, + FoundHouseholdRunCalculation, + NewHouseholdRunCalculation, + ReportDefinition, + ReportRunStatus, + ReportWithRun, + RunVersions, + SideDefinition, + SideRun, + SimulationChoice, + SimulationStatus, + StoredReportRun, +) +from pydantic import ValidationError +from sqlalchemy.exc import OperationalError + +REPORT_ID = UUID("00000000-0000-4000-8000-0000000000f0") +REPORT_RUN_ID = UUID("00000000-0000-4000-8000-0000000000f1") +BASELINE_SIMULATION_ID = UUID("00000000-0000-4000-8000-0000000000f2") +BASELINE_RUN_ID = UUID("00000000-0000-4000-8000-0000000000f3") +REFORM_SIMULATION_ID = UUID("00000000-0000-4000-8000-0000000000f4") +REFORM_RUN_ID = UUID("00000000-0000-4000-8000-0000000000f5") +JOINED_CALCULATION_ID = UUID("00000000-0000-4000-8000-0000000000f6") +# The service's IDs, in the order it takes them: each side's proposed row. +BASELINE_CALCULATION_ID, REFORM_CALCULATION_ID = (UUID(int=1), UUID(int=2)) +CONTEXT = {"observability_id": "observed"} +DATABASE_ERROR = OperationalError("SELECT 1", {}, Exception("server closed")) +LISTED = ["marginal_tax_rate", "household_net_income"] +RECORDED = ("household_net_income", "marginal_tax_rate") +AXES = [[{"name": "employment_income", "count": 3, "min": 0, "max": 60_000}]] +WORKER = manifest_household_worker("us") +CURRENT_VERSIONS = RunVersions( + country_package_version=WORKER.bundle.country_package_version, + policyengine_version=WORKER.bundle.policyengine_version, +) +STORED_REPORT = ReportDefinition( + id=REPORT_ID, + country="us", + kind="household", + year=2025, + region_code=None, + dataset_name=None, + inputs={}, + baseline=SideDefinition( + simulation_id=BASELINE_SIMULATION_ID, + choice=SimulationChoice(policy_id=None, dynamic_id=None), + ), + reform=SideDefinition( + simulation_id=REFORM_SIMULATION_ID, + choice=SimulationChoice(policy_id=POLICY_ID, dynamic_id=None), + ), + household_id=HOUSEHOLD_ID, + keyed=True, +) +STORED_RUN = StoredReportRun( + id=REPORT_RUN_ID, + report_id=REPORT_ID, + status=ReportRunStatus.SUCCEEDED, + versions=CURRENT_VERSIONS, + baseline=SideRun( + simulation_id=BASELINE_SIMULATION_ID, simulation_run_id=BASELINE_RUN_ID + ), + reform=SideRun(simulation_id=REFORM_SIMULATION_ID, simulation_run_id=REFORM_RUN_ID), +) + + +@dataclass +class FakeCalculationStore(FakeHouseholdReportStore): + """Reads the report and run it is given; finds ``joined`` rows by run. + + Every other proposed row is inserted pending. ``create_failure`` is + raised by the find-or-create instead of recording it. + """ + + definition: ReportDefinition | None = STORED_REPORT + run: StoredReportRun | None = STORED_RUN + report_read_failure: Exception | None = None + joined: dict[UUID, FoundHouseholdRunCalculation] = field(default_factory=dict) + proposals: list[list[NewHouseholdRunCalculation]] = field(default_factory=list) + recorded_calculation_calls: list[tuple[UUID, str]] = field(default_factory=list) + failed_calculations: list[tuple[UUID, str]] = field(default_factory=list) + + def read_report_with_run( + self, report_id: UUID, report_run_id: UUID + ) -> ReportWithRun: + if self.report_read_failure is not None: + raise self.report_read_failure + definition = self.definition + if definition is None or definition.id != report_id: + return ReportWithRun(definition=None, run=None) + run = self.run + if run is None or run.id != report_run_id or run.report_id != report_id: + run = None + return ReportWithRun(definition=definition, run=run) + + def find_or_create_calculations( + self, proposed: list[NewHouseholdRunCalculation] + ) -> dict[UUID, FoundHouseholdRunCalculation]: + if self.create_failure is not None: + raise self.create_failure + self.proposals.append(list(proposed)) + return { + calculation.simulation_run_id: self.joined.get( + calculation.simulation_run_id, + FoundHouseholdRunCalculation( + id=calculation.id, + simulation_run_id=calculation.simulation_run_id, + inserted=True, + status=SimulationStatus.PENDING, + ), + ) + for calculation in proposed + } + + def record_calculation_call( + self, household_run_calculation_id: UUID, modal_call_id: str + ) -> SimulationStatus | None: + self.recorded_calculation_calls.append( + (household_run_calculation_id, modal_call_id) + ) + return SimulationStatus.PENDING + + def fail_unstarted_calculation( + self, household_run_calculation_id: UUID, error_message: str + ) -> bool: + self.failed_calculations.append((household_run_calculation_id, error_message)) + return True + + +@dataclass +class FakeCalculationCaller: + """Starts calls by recording them; ``failure`` is raised instead when set.""" + + failure: Exception | None = None + calls: list[tuple[Any, dict, UUID, Any]] = field(default_factory=list) + + async def start_household_run_calculation( + self, + worker, + payload: dict[str, Any], + *, + household_run_calculation_id: UUID, + observability_context: dict[str, Any] | None, + ) -> str: + if self.failure is not None: + raise self.failure + self.calls.append( + (worker, payload, household_run_calculation_id, observability_context) + ) + return f"fc-extra-{len(self.calls)}" + + +def _service( + store: FakeCalculationStore, + caller: FakeCalculationCaller | None = None, + workers: FakeHouseholdWorkers | None = None, +) -> HouseholdRunCalculationService: + return HouseholdRunCalculationService( + store=store, + workers=workers or FakeHouseholdWorkers(), + caller=caller or FakeCalculationCaller(), + call_start_timeout_seconds=0.05, + new_id=numbered_ids(), + ) + + +def _create( + service: HouseholdRunCalculationService, + request: HouseholdRunCalculationRequest | None = None, + *, + report_run_id: UUID = REPORT_RUN_ID, +) -> HouseholdRunCalculationsCreated: + return asyncio.run( + service.create_calculations( + REPORT_ID, + report_run_id, + request + or HouseholdRunCalculationRequest.model_validate( + {"variables": LISTED, "axes": AXES} + ), + observability_context=CONTEXT, + ) + ) + + +def _side_payload(calculation_id: UUID, parameters: dict) -> dict[str, Any]: + return { + "schema_version": 1, + "calculation_id": str(calculation_id), + "country": "us", + "year": "2025", + "household": {**SITUATION, "axes": AXES}, + "policy": {"parameters": parameters}, + "add_missing_variables": False, + "variables": list(RECORDED), + "spm_selection_source": "request", + "bundle": WORKER.bundle.model_dump(mode="json"), + } + + +def _state( + calculation_id: UUID, + run_id: UUID, + status: SimulationStatus = SimulationStatus.PENDING, +) -> HouseholdRunCalculationState: + return HouseholdRunCalculationState( + household_run_calculation_id=calculation_id, + simulation_run_id=run_id, + status=status, + ) + + +def test_each_sides_run_gets_an_extra_calculation_and_its_call() -> None: + store = FakeCalculationStore() + caller = FakeCalculationCaller() + + created = _create(_service(store, caller)) + + assert store.reads == [ + { + "country": "us", + "household_id": HOUSEHOLD_ID, + "choices": { + "baseline": SimulationChoice(policy_id=None, dynamic_id=None), + "reform": SimulationChoice(policy_id=POLICY_ID, dynamic_id=None), + }, + "policyengine_version": WORKER.bundle.policyengine_version, + } + ] + assert store.proposals == [ + [ + NewHouseholdRunCalculation( + id=BASELINE_CALCULATION_ID, + simulation_run_id=BASELINE_RUN_ID, + simulation_id=BASELINE_SIMULATION_ID, + variables=RECORDED, + axes=AXES, + ), + NewHouseholdRunCalculation( + id=REFORM_CALCULATION_ID, + simulation_run_id=REFORM_RUN_ID, + simulation_id=REFORM_SIMULATION_ID, + variables=RECORDED, + axes=AXES, + ), + ] + ] + assert caller.calls == [ + ( + WORKER, + _side_payload(BASELINE_CALCULATION_ID, {}), + BASELINE_CALCULATION_ID, + CONTEXT, + ), + ( + WORKER, + _side_payload(REFORM_CALCULATION_ID, REFORM), + REFORM_CALCULATION_ID, + CONTEXT, + ), + ] + for _, payload, _, _ in caller.calls: + HouseholdExecutionRequest.model_validate(payload) + assert store.recorded_calculation_calls == [ + (BASELINE_CALCULATION_ID, "fc-extra-1"), + (REFORM_CALCULATION_ID, "fc-extra-2"), + ] + assert created == HouseholdRunCalculationsCreated( + report_id=REPORT_ID, + report_run_id=REPORT_RUN_ID, + baseline=_state(BASELINE_CALCULATION_ID, BASELINE_RUN_ID), + reform=_state(REFORM_CALCULATION_ID, REFORM_RUN_ID), + ) + + +def test_a_calculation_without_axes_calculates_the_household_as_stored() -> None: + store = FakeCalculationStore() + caller = FakeCalculationCaller() + + _create( + _service(store, caller), + HouseholdRunCalculationRequest.model_validate({"variables": LISTED}), + ) + + assert [proposed.axes for proposed in store.proposals[0]] == [None, None] + for _, payload, _, _ in caller.calls: + assert payload["household"] == SITUATION + + +def test_a_joined_calculation_is_answered_as_it_is_and_gets_no_call() -> None: + joined = FoundHouseholdRunCalculation( + id=JOINED_CALCULATION_ID, + simulation_run_id=BASELINE_RUN_ID, + inserted=False, + status=SimulationStatus.RUNNING, + ) + store = FakeCalculationStore(joined={BASELINE_RUN_ID: joined}) + caller = FakeCalculationCaller() + + created = _create(_service(store, caller)) + + assert [call[2] for call in caller.calls] == [REFORM_CALCULATION_ID] + assert created.baseline == _state( + JOINED_CALCULATION_ID, BASELINE_RUN_ID, SimulationStatus.RUNNING + ) + assert created.reform == _state(REFORM_CALCULATION_ID, REFORM_RUN_ID) + + +def test_a_policy_compared_with_itself_names_one_calculation_on_both_sides() -> None: + """Both sides name one simulation run, so one row and one call serve both.""" + store = FakeCalculationStore( + definition=replace(STORED_REPORT, reform=STORED_REPORT.baseline), + run=replace(STORED_RUN, reform=STORED_RUN.baseline), + ) + caller = FakeCalculationCaller() + + created = _create(_service(store, caller)) + + ((proposed,),) = store.proposals + assert proposed.simulation_run_id == BASELINE_RUN_ID + assert len(caller.calls) == 1 + assert ( + created.baseline + == created.reform + == _state(BASELINE_CALCULATION_ID, BASELINE_RUN_ID) + ) + + +def test_a_report_of_the_baseline_alone_has_no_reform_calculation() -> None: + store = FakeCalculationStore( + definition=replace(STORED_REPORT, reform=None), + run=replace(STORED_RUN, reform=None), + ) + caller = FakeCalculationCaller() + + created = _create(_service(store, caller)) + + assert [proposed.simulation_run_id for proposed in store.proposals[0]] == [ + BASELINE_RUN_ID + ] + assert created.reform is None + + +def test_an_unknown_report_or_run_is_refused_before_anything_is_written() -> None: + unknown_report = FakeCalculationStore(definition=None) + unknown_run = FakeCalculationStore(run=None) + + with pytest.raises(EconomyRecordNotFoundError) as no_report: + _create(_service(unknown_report)) + with pytest.raises(ReportRunNotFoundError): + _create(_service(unknown_run)) + + assert no_report.value.record == "report" + for store in (unknown_report, unknown_run): + assert (store.reads, store.proposals) == ([], []) + + +@pytest.mark.parametrize("kind", ["economy", "budget_window"]) +def test_a_report_without_households_has_no_extra_calculations(kind) -> None: + store = FakeCalculationStore(definition=replace(STORED_REPORT, kind=kind)) + + with pytest.raises(EconomySubmissionUnprocessableError) as refused: + _create(_service(store)) + + assert refused.value.code == "household_calculations_not_available" + ((reason,),) = (refused.value.reasons,) + assert reason.loc == ("path", "report_id") + assert (store.reads, store.proposals) == ([], []) + + +def test_a_run_on_other_versions_than_the_default_workers_is_refused() -> None: + """Its extra calculations would not match it: the report is re-run first.""" + older = RunVersions(country_package_version="1.0.0", policyengine_version="6.0.0") + store = FakeCalculationStore(run=replace(STORED_RUN, versions=older)) + caller = FakeCalculationCaller() + + with pytest.raises(EconomyRerunConflictError) as refused: + _create(_service(store, caller)) + + assert refused.value.code == "report_run_not_current" + assert (store.proposals, caller.calls) == ([], []) + + +def test_a_failed_run_is_refused_until_the_report_is_re_run() -> None: + """Anthony's answer to D2 · 3c's decision 3: a failed run has no extras.""" + store = FakeCalculationStore(run=replace(STORED_RUN, status=ReportRunStatus.FAILED)) + caller = FakeCalculationCaller() + + with pytest.raises(EconomyRerunConflictError) as refused: + _create(_service(store, caller)) + + assert refused.value.code == "report_run_failed" + assert (store.reads, store.proposals, caller.calls) == ([], [], []) + + +@pytest.mark.parametrize( + "status", + [ReportRunStatus.PENDING, ReportRunStatus.RUNNING, ReportRunStatus.SUCCEEDED], +) +def test_an_unfailed_run_gets_extra_calculations(status) -> None: + store = FakeCalculationStore(run=replace(STORED_RUN, status=status)) + + created = _create(_service(store)) + + assert created.baseline == _state(BASELINE_CALCULATION_ID, BASELINE_RUN_ID) + + +def test_a_stored_household_the_contract_cannot_read_is_located_at_the_report() -> None: + store = FakeCalculationStore(document={"people": "not a list of people"}) + + with pytest.raises(EconomySubmissionUnprocessableError) as refused: + _create(_service(store)) + + assert refused.value.code == "household_not_calculable" + assert [reason.loc for reason in refused.value.reasons] == [ + ("report", "household_id") + ] + assert store.proposals == [] + + +def test_an_unreadable_database_answers_503() -> None: + store = FakeCalculationStore(report_read_failure=DATABASE_ERROR) + + with pytest.raises(EconomySubmissionUnavailableError) as unavailable: + _create(_service(store)) + + assert unavailable.value.code == "database_unavailable" + + +def test_a_run_deleted_after_its_read_is_answered_as_unknown() -> None: + store = FakeCalculationStore( + create_failure=EconomyRecordReferenceError( + "household_run_calculations", "simulation_run_id" + ) + ) + + with pytest.raises(ReportRunNotFoundError): + _create(_service(store)) + + +def test_a_calculation_modal_refuses_is_failed_and_answered_failed() -> None: + """The next identical request then inserts another, as for cliffs.""" + store = FakeCalculationStore() + caller = FakeCalculationCaller(failure=ConnectionError("Modal is down")) + + created = _create(_service(store, caller)) + + assert [failed_id for failed_id, _ in store.failed_calculations] == [ + BASELINE_CALCULATION_ID, + REFORM_CALCULATION_ID, + ] + for _, message in store.failed_calculations: + assert message.startswith("modal_call_refused:") + assert store.recorded_calculation_calls == [] + assert created.baseline.status == SimulationStatus.FAILED + assert created.reform is not None + assert created.reform.status == SimulationStatus.FAILED + + +@pytest.mark.parametrize( + "body", + [ + {}, + {"variables": []}, + {"variables": ["age", "age"]}, + {"variables": ["age\x00"]}, + {"variables": ["age"], "add_missing_variables": True}, + { + "variables": ["age"], + "axes": [[{"name": "employment_income", "count": 0, "min": 0, "max": 1}]], + }, + ], + ids=["no-list", "empty", "repeated", "nul", "unknown-field", "no-points"], +) +def test_a_malformed_extra_calculation_is_refused(body) -> None: + with pytest.raises(ValidationError): + HouseholdRunCalculationRequest.model_validate(body) + + +@dataclass +class FakeCalculations: + """Records each route call, and answers as told.""" + + failure: Exception | None = None + created: list[tuple[UUID, UUID, HouseholdRunCalculationRequest]] = field( + default_factory=list + ) + + async def create_calculations( + self, + report_id: UUID, + report_run_id: UUID, + request: HouseholdRunCalculationRequest, + *, + observability_context: dict[str, Any] | None, + ) -> HouseholdRunCalculationsCreated: + self.created.append((report_id, report_run_id, request)) + if self.failure is not None: + raise self.failure + return HouseholdRunCalculationsCreated( + report_id=report_id, + report_run_id=report_run_id, + baseline=_state(BASELINE_CALCULATION_ID, BASELINE_RUN_ID), + reform=None, + ) + + +def _client( + monkeypatch, + calculations: FakeCalculations | HouseholdRunCalculationService | None, +) -> TestClient: + monkeypatch.setattr( + app_module, + "household_run_calculations_for", + lambda settings, database: calculations, + ) + return TestClient( + create_app( + settings=make_settings(), + backend=FakeBackend(), + auth_dependency=lambda: None, + ) + ) + + +PATH = f"/reports/{REPORT_ID}/runs/{REPORT_RUN_ID}/household-calculations" + + +def test_the_route_answers_201_with_each_sides_calculation(monkeypatch) -> None: + calculations = FakeCalculations() + + with _client(monkeypatch, calculations) as client: + result = client.post(PATH, json={"variables": LISTED, "axes": AXES}) + + assert result.status_code == 201 + assert result.json() == { + "report_id": str(REPORT_ID), + "report_run_id": str(REPORT_RUN_ID), + "baseline": { + "household_run_calculation_id": str(BASELINE_CALCULATION_ID), + "simulation_run_id": str(BASELINE_RUN_ID), + "status": "pending", + }, + "reform": None, + } + ((report_id, report_run_id, request),) = calculations.created + assert (report_id, report_run_id) == (REPORT_ID, REPORT_RUN_ID) + assert request.variables == tuple(LISTED) + + +@pytest.mark.parametrize( + ("failure", "code"), + [ + (EconomyRecordNotFoundError("report"), "unknown_report"), + (ReportRunNotFoundError(REPORT_RUN_ID), "unknown_report_run"), + ], +) +def test_the_route_answers_404_for_an_unknown_report_or_run( + monkeypatch, failure, code +) -> None: + with _client(monkeypatch, FakeCalculations(failure=failure)) as client: + result = client.post(PATH, json={"variables": LISTED}) + + assert result.status_code == 404 + assert result.json()["code"] == code + + +def test_the_route_answers_an_unconfirmed_commit_as_possibly_written( + monkeypatch, caplog +) -> None: + """As other creates answer it: a 500 that may follow a write, never a 503.""" + commit_failed = EconomyRecordOutcomeUnknownError("the commit failed") + commit_failed.__cause__ = DATABASE_ERROR + caller = FakeCalculationCaller() + service = _service(FakeCalculationStore(create_failure=commit_failed), caller) + + with _client(monkeypatch, service) as client: + result = client.post(PATH, json={"variables": LISTED}) + + assert result.status_code == 500 + assert result.json() == { + "code": "internal_error", + "detail": ( + "The service may have created the report run's extra calculations, " + "but could not confirm they were written. An identical request " + "finds them." + ), + } + (logged,) = [ + record + for record in caplog.records + if record.getMessage() == "household_run_calculations_outcome_unknown" + ] + assert logged.__dict__["error_type"] == "OperationalError" + assert caller.calls == [] + + +def test_the_route_answers_409_for_a_run_on_other_versions(monkeypatch) -> None: + failure = EconomyRerunConflictError( + code="report_run_not_current", detail="Re-run the report first." + ) + with _client(monkeypatch, FakeCalculations(failure=failure)) as client: + result = client.post(PATH, json={"variables": LISTED}) + + assert result.status_code == 409 + assert result.json()["code"] == "report_run_not_current" + + +def test_the_route_answers_503_when_extra_calculations_are_not_configured( + monkeypatch, +) -> None: + with _client(monkeypatch, None) as client: + result = client.post(PATH, json={"variables": LISTED}) + + assert result.status_code == 503 + assert result.json()["code"] == "not_configured" + assert "Retry-After" in result.headers + + +def test_the_route_refuses_a_malformed_body_before_calling_the_service( + monkeypatch, +) -> None: + calculations = FakeCalculations() + + with _client(monkeypatch, calculations) as client: + result = client.post(PATH, json={"variables": []}) + + assert result.status_code == 422 + assert calculations.created == [] + + +DATABASE_URL = "postgresql://simulation_service:secret@db.example:5432/postgres" + + +def test_extra_calculations_are_built_only_when_households_are_configured() -> None: + """Nothing reaches the database or Modal until the first request.""" + database = SimulationDatabase.from_url(DATABASE_URL) + try: + configured = household_run_calculations_for( + make_settings( + simulation_database_url=DATABASE_URL, v2_modal_environment="staging" + ), + database, + ) + unconfigured = household_run_calculations_for(make_settings(), database) + finally: + database.dispose() + + assert isinstance(configured, HouseholdRunCalculationService) + assert unconfigured is None + assert household_run_calculations_for(make_settings(), None) is None diff --git a/projects/policyengine-simulation-entry/tests/test_household_workers.py b/projects/policyengine-simulation-entry/tests/test_household_workers.py index b87d536dc..22d3fb8f7 100644 --- a/projects/policyengine-simulation-entry/tests/test_household_workers.py +++ b/projects/policyengine-simulation-entry/tests/test_household_workers.py @@ -238,3 +238,41 @@ async def test_a_report_run_call_modal_gives_no_id_is_refused(monkeypatch): await ModalHouseholdFunctionCaller("staging").start_report_run( worker, {}, report_run_id=REPORT_RUN_ID, observability_context=None ) + + +CALCULATION_ID = UUID("00000000-0000-4000-8000-0000000000ac") + + +@pytest.mark.asyncio +async def test_an_extra_calculation_is_started_by_name_with_its_row(monkeypatch): + """The household function is given the extra calculation's row to record.""" + function = FakeModalFunction("fc-extra-calculation-1") + monkeypatch.setattr( + household_workers.modal.Function, + "from_name", + lambda *names, environment_name: function, + ) + worker = ManifestHouseholdWorkers( + manifest_store(household_worker_version()) + ).default_worker("us") + payload = {"calculation_id": str(CALCULATION_ID)} + + call_id = await ModalHouseholdFunctionCaller( + "staging" + ).start_household_run_calculation( + worker, + payload, + household_run_calculation_id=CALCULATION_ID, + observability_context={"observability_id": "o-1"}, + ) + + assert call_id == "fc-extra-calculation-1" + assert function.spawned == [ + ( + (payload,), + { + "household_run_calculation_id": str(CALCULATION_ID), + "observability_context": {"observability_id": "o-1"}, + }, + ) + ] diff --git a/projects/policyengine-simulation-entry/tests/test_openapi.py b/projects/policyengine-simulation-entry/tests/test_openapi.py index 679b9ab6c..b0cfde21b 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/{report_id}/runs/{report_run_id}/household-calculations"), ("POST", "/reports/without-run"), ("POST", "/simulate/economy/budget-window"), ("POST", "/simulate/economy/comparison"), @@ -91,6 +92,7 @@ def operation_ids(spec: OpenAPIDocument) -> dict[tuple[str, str], str]: "/reports", "/reports/{report_id}", "/reports/{report_id}/runs", + "/reports/{report_id}/runs/{report_run_id}/household-calculations", "/reports/without-run", "/simulations", "/simulations/{simulation_id}", @@ -113,6 +115,9 @@ def operation_ids(spec: OpenAPIDocument) -> dict[tuple[str, str], str]: "HouseholdPolicyChoice", "HouseholdReportCreated", "HouseholdReportRequest", + "HouseholdRunCalculationRequest", + "HouseholdRunCalculationState", + "HouseholdRunCalculationsCreated", "PolicyChoice", "ReportCliffs", "ReportRerunRequest", @@ -554,8 +559,10 @@ def test_rerun_routes_declare_every_answer(): assert "cliffs_not_available" in report_answers["422"]["description"] simulation_answers = _responses(spec, "post", "/simulations/{simulation_id}/runs") assert "cliffs_not_available" not in simulation_answers["422"]["description"] + # Only a household report's re-run lists the variables its runs calculate. + assert "variables_not_available" in report_answers["422"]["description"] report_rerun = spec["components"]["schemas"]["ReportRerunRequest"] - assert set(report_rerun["properties"]) == {"force", "include_cliffs"} + assert set(report_rerun["properties"]) == {"force", "include_cliffs", "variables"} assert ( "requestBody" not in spec["paths"]["/simulations/{simulation_id}/runs"]["post"] ) @@ -660,8 +667,8 @@ def test_a_report_request_is_an_economy_report_a_budget_window_or_a_household(): def test_a_household_report_names_its_household_and_each_sides_policy(): schemas = create_app().openapi()["components"]["schemas"] - # No year, region, dataset, version or record ID, and no option: a - # household report always adds the household's missing variables. + # No year, region, dataset, version or record ID, and no option but the + # variables to calculate: without them, every variable. household_report = schemas["HouseholdReportRequest"] assert set(household_report["properties"]) == { "country", @@ -671,6 +678,7 @@ def test_a_household_report_names_its_household_and_each_sides_policy(): "household_id", "baseline", "reform", + "variables", } assert set(household_report["required"]) == { "country", @@ -779,6 +787,7 @@ def test_a_report_without_a_run_takes_a_reports_body_and_declares_its_answers(): assert "modal_call_refused" not in responses["503"]["description"] assert "manifest" in responses["503"]["description"] assert "cliffs_not_available" in responses["422"]["description"] + assert "variables_not_available" in responses["422"]["description"] created = schemas["ReportWithoutRunCreated"] assert set(created["properties"]) == { "report_id", @@ -803,3 +812,75 @@ def test_a_report_without_a_run_takes_a_reports_body_and_declares_its_answers(): "baseline_simulation_id", "reform_simulation_id", } + + +EXTRA_CALCULATIONS_PATH = ( + "/reports/{report_id}/runs/{report_run_id}/household-calculations" +) + + +def test_a_household_runs_extra_calculations_declare_every_answer(): + spec = create_app().openapi() + error = {"$ref": "#/components/schemas/EconomyError"} + unprocessable = {"$ref": "#/components/schemas/EconomyRequestUnprocessable"} + responses = _responses(spec, "post", EXTRA_CALCULATIONS_PATH) + + # 400 is a household report re-run's: a row the stored report names is + # missing. + assert set(responses) == { + "201", + "400", + "403", + "404", + "409", + "422", + "500", + "503", + } + assert _response_schema(responses["201"]) == { + "$ref": "#/components/schemas/HouseholdRunCalculationsCreated" + } + for status_code in ("400", "404", "409", "500", "503"): + assert _response_schema(responses[status_code]) == error + assert _response_schema(responses["422"]) == unprocessable + assert responses["503"]["headers"]["Retry-After"]["schema"] == {"type": "integer"} + assert {"unknown_report", "unknown_report_run"} <= set( + responses["404"]["description"].replace(",", " ").replace(")", " ").split() + ) + assert "report_run_not_current" in responses["409"]["description"] + assert "report_run_failed" in responses["409"]["description"] + assert "household_calculations_not_available" in responses["422"]["description"] + assert "household_not_calculable" in responses["422"]["description"] + codes = set( + spec["components"]["schemas"]["EconomyError"]["properties"]["code"]["enum"] + ) + assert { + "unknown_report_run", + "report_run_not_current", + "report_run_failed", + } <= codes + names = operation_ids(cast("OpenAPIDocument", spec)) + assert names[("POST", EXTRA_CALCULATIONS_PATH)] == ( + "create_household_run_calculations" + ) + + +def test_an_extra_calculation_names_its_variables_and_any_axes(): + schemas = create_app().openapi()["components"]["schemas"] + + request = schemas["HouseholdRunCalculationRequest"] + assert set(request["properties"]) == {"variables", "axes"} + assert request["required"] == ["variables"] + assert request["additionalProperties"] is False + created = schemas["HouseholdRunCalculationsCreated"] + assert set(created["properties"]) == { + "report_id", + "report_run_id", + "baseline", + "reform", + } + assert set(schemas["HouseholdRunCalculationState"]["properties"]) == { + "household_run_calculation_id", + "simulation_run_id", + "status", + } 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 676f0a3df..c09a485d7 100644 --- a/projects/policyengine-simulation-entry/tests/test_reports_without_run.py +++ b/projects/policyengine-simulation-entry/tests/test_reports_without_run.py @@ -265,6 +265,23 @@ def test_a_report_without_a_run_asking_for_cliffs_is_refused_before_any_read() - assert (store.report_reads, store.reports_without_run) == ([], []) +def test_a_household_report_without_a_run_listing_variables_is_refused() -> None: + """A list is recorded on a run, and none is created, as cliffs are refused.""" + store = FakeHouseholdStoreWithoutRun() + + with pytest.raises(EconomySubmissionUnprocessableError) as refused: + asyncio.run( + _household_service(store).create_report_without_run( + household_report_request(variables=["household_net_income"]) + ) + ) + + assert refused.value.code == "variables_not_available" + (reason,) = refused.value.reasons + assert reason.loc == ("body", "variables") + assert (store.reads, store.reports_without_run) == ([], []) + + def test_a_report_without_a_run_needs_the_version_manifest() -> None: store = FakeEconomyStoreWithoutRun() workers = FakeWorkers(failure=VersionManifestUnavailableError("unreadable")) diff --git a/projects/policyengine-simulation-executor/README.md b/projects/policyengine-simulation-executor/README.md index a67875461..5d584172a 100644 --- a/projects/policyengine-simulation-executor/README.md +++ b/projects/policyengine-simulation-executor/README.md @@ -164,8 +164,8 @@ with its own mechanism, separate from the v1 routing jobs above: while the stored manifest is still what it wrote (`--restore-plan`). In a deployment from `main`, the same job then deploys the unversioned stuck-run sweep (`src/modal/run_sweep_app.py`), which fails the report - runs, simulation runs, household jobs and simulation runs' cliff results - nothing will finish, and whose + runs, simulation runs, household jobs, simulation runs' cliff results and + household runs' extra calculations nothing will finish, and whose schedule starts as soon as it deploys; a failed sweep deploy, including a failed build of its image, fails the job and so puts the previous default back. It then runs the sweep application's `delete_replaced_inline_household_jobs` once with diff --git a/projects/policyengine-simulation-executor/src/modal/run_sweep_app.py b/projects/policyengine-simulation-executor/src/modal/run_sweep_app.py index 8af150b3f..6d2a4a052 100644 --- a/projects/policyengine-simulation-executor/src/modal/run_sweep_app.py +++ b/projects/policyengine-simulation-executor/src/modal/run_sweep_app.py @@ -1,9 +1,10 @@ """A scheduled Modal function that fails the runs nothing will finish. Every ten minutes it lists API v1's report runs, simulation runs, -household jobs and simulation runs' cliff results that have been pending or -running for at least ten minutes, counted from a run's or cliff result's -first claim or, while it is pending, from its creation (a budget window's +household jobs, simulation runs' cliff results and household runs' extra +calculations that have been pending or running for at least ten minutes, +counted from a run's, cliff result's or extra calculation's first claim or, +while it is pending, from its creation (a budget window's year from when its call was recorded), and from a household job's creation. It asks Modal for the status of each recorded call and marks a run or job failed once its call has ended, and fails a pending one that has no call @@ -12,7 +13,8 @@ longer than any Modal call of it can run, whatever Modal reports. A failed year of a budget window fails its window, and a window no year has advanced for ten minutes is finished from its years, or failed as stalled. -Its result counts runs, household jobs and cliff results together, and the +Its result counts runs, household jobs, cliff results and extra calculations +together, and the windows it finished. It connects as the Modal worker role, from the same Modal secret the v2 coordinator, workers and household functions use. This application is not versioned with the .py bundle: one @@ -93,7 +95,7 @@ secrets=[modal_worker_database_secret], ) def sweep_stuck_runs() -> dict: - """Fail the runs, household jobs, cliff results and windows nothing will finish.""" + """Fail stuck runs, jobs, cliff results, extra calculations and windows.""" from policyengine_simulation_executor.stage12_runtime import ( # noqa: PLC0415 # Modal function body: loaded in the container, not at deploy time report_run_access, run_sweep, diff --git a/projects/policyengine-simulation-executor/src/modal/v2_app.py b/projects/policyengine-simulation-executor/src/modal/v2_app.py index 5acce809e..4ee1198a8 100644 --- a/projects/policyengine-simulation-executor/src/modal/v2_app.py +++ b/projects/policyengine-simulation-executor/src/modal/v2_app.py @@ -570,7 +570,8 @@ def coordinate_report( # Household function sizing. A call holds one country model and a simulation # of the household, under one policy, at every axis point; a household report # run's call calculates its baseline and then its reform, which the -# simulation service builds without axes. Each container +# simulation service builds without axes, and an extra calculation's call +# calculates one side's household, with or without axes. Each container # reserves 4 GiB and may use up to 16 GiB before Modal stops it, so a large # household calculated with every variable at many axis points still fits. # The timeout (stage12_timeouts.HOUSEHOLD_FUNCTION_TIMEOUT_SECONDS) is three @@ -608,13 +609,14 @@ def _build_household_runtime(country: CountryId) -> ObservabilityRuntime: } -def _run_household_calculation( +def _run_household_calculation( # noqa: PLR0913 # the country, the payload and each row a call may name country: CountryId, payload: dict, *, observability_context: dict | None, household_job_id: str | None, household_report_run_id: str | None = None, + household_run_calculation_id: str | None = None, ) -> dict: """Calculate one household request for ``country`` and return its outcome. @@ -628,9 +630,12 @@ def _run_household_calculation( report run and each side's simulation run it can, calculates and records those sides, waits for a side another call holds, and returns the runs' statuses - (``stage12_runtime.run_household_report``). A call names at most one of - the two; without either, the call touches no database. The call uses its - container's observability runtime and leaves it open. + (``stage12_runtime.run_household_report``). With + ``household_run_calculation_id``, the call claims that extra calculation + of a household run and records the outcome on it, as for a household + job (``stage12_runtime.run_household_run_calculation``). A call names at + most one of the three; without any, the call touches no database. The + call uses its container's observability runtime and leaves it open. """ from policyengine_simulation_contract.household_execution import ( # noqa: PLC0415 # Modal function body: loaded in the worker container, not at deploy time HouseholdExecutionRequest, @@ -660,24 +665,21 @@ def calculate_request( def calculate() -> HouseholdExecutionResult | HouseholdExecutionFailure: return calculate_request(HouseholdExecutionRequest.model_validate(payload)) - if household_job_id is not None and household_report_run_id is not None: - msg = "a household call names either a household job or a report run" + row_ids = [household_job_id, household_report_run_id, household_run_calculation_id] + if sum(row_id is not None for row_id in row_ids) > 1: + msg = "a household call names at most one of a job, report run or calculation" raise ValueError(msg) propagated = normalize_observability_context(observability_context) modal_call_id = modal.current_function_call_id() # A household report run is a ``report_runs`` row. - record_attributes = ( - stage12_runtime.operation_record_attributes( - "report_runs", - stage12_runtime.row_id_or_none(household_report_run_id), - modal_call_id, - ) - if household_report_run_id is not None - else stage12_runtime.operation_record_attributes( - "household_jobs", - stage12_runtime.row_id_or_none(household_job_id), - modal_call_id, - ) + if household_report_run_id is not None: + table, row_id = "report_runs", household_report_run_id + elif household_run_calculation_id is not None: + table, row_id = "household_run_calculations", household_run_calculation_id + else: + table, row_id = "household_jobs", household_job_id + record_attributes = stage12_runtime.operation_record_attributes( + table, stage12_runtime.row_id_or_none(row_id), modal_call_id ) result = None with runtime.operation( @@ -695,6 +697,16 @@ def calculate() -> HouseholdExecutionResult | HouseholdExecutionFailure: modal_call_id=modal_call_id, runtime=runtime, ) + elif household_run_calculation_id is not None: + # As for a report run, the payload is validated once the call + # holds the calculation. + result = stage12_runtime.run_household_run_calculation( + UUID(household_run_calculation_id), + payload, + calculate_request, + modal_call_id=modal_call_id, + runtime=runtime, + ) elif household_job_id is None: result = calculate().model_dump(mode="json") else: @@ -726,12 +738,15 @@ def calculate_household_us( observability_context: dict | None = None, household_job_id: str | None = None, household_report_run_id: str | None = None, + household_run_calculation_id: str | None = None, ) -> dict: """Calculate one US household under the request's policy. With ``household_job_id``, record the calculation on that household job. With ``household_report_run_id``, ``payload`` is that household report run's calculation: calculate and record each side, then the report run. + With ``household_run_calculation_id``, record the calculation on that + extra calculation of a household run. """ return _run_household_calculation( "us", @@ -739,6 +754,7 @@ def calculate_household_us( observability_context=observability_context, household_job_id=household_job_id, household_report_run_id=household_report_run_id, + household_run_calculation_id=household_run_calculation_id, ) @@ -758,12 +774,15 @@ def calculate_household_uk( observability_context: dict | None = None, household_job_id: str | None = None, household_report_run_id: str | None = None, + household_run_calculation_id: str | None = None, ) -> dict: """Calculate one UK household under the request's policy. With ``household_job_id``, record the calculation on that household job. With ``household_report_run_id``, ``payload`` is that household report run's calculation: calculate and record each side, then the report run. + With ``household_run_calculation_id``, record the calculation on that + extra calculation of a household run. """ return _run_household_calculation( "uk", @@ -771,4 +790,5 @@ def calculate_household_uk( observability_context=observability_context, household_job_id=household_job_id, household_report_run_id=household_report_run_id, + household_run_calculation_id=household_run_calculation_id, ) diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/__init__.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/__init__.py index f8b574159..039f6044e 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/__init__.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/__init__.py @@ -28,6 +28,7 @@ ) from .household_job_recording import run_household_job from .household_report_recording import run_household_report +from .household_run_calculation_recording import run_household_run_calculation from .operation_records import ( operation_record_attributes, report_run_named_by, @@ -92,6 +93,7 @@ "row_id_or_none", "run_household_job", "run_household_report", + "run_household_run_calculation", "run_segmented_simulation", "run_single_simulation", "should_segment_simulation", diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/household_report_recording.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/household_report_recording.py index eaebc73d7..a67063828 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/household_report_recording.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/household_report_recording.py @@ -30,6 +30,10 @@ (``HOUSEHOLD_SIDE_WAIT_SECONDS`` from the call's start) fails the report run and is left to its call. A run named on both sides is calculated once. A failing call fails only the runs it holds. + +Since a shared run may be another request's, a side calculates the variables +its run records, not the payload's: a run that records none calculates every +variable, adding the household's missing ones. """ from __future__ import annotations @@ -128,6 +132,12 @@ def get_simulation_run(self, simulation_run_id: UUID) -> SimulationRunState: """Return a simulation run's state, with its recorded call and failure.""" ... + def household_run_variables( + self, simulation_run_id: UUID + ) -> tuple[str, ...] | None: + """Return the variables the run records, or None for every variable.""" + ... + def complete_household_simulation_run( self, simulation_run_id: UUID, @@ -261,7 +271,7 @@ def side( if state.status in {RunStatus.PENDING, RunStatus.RUNNING}: return None return _finished_side(side, run_id, state) - outcome = calculate(request) + outcome = calculate(self._recorded_request(request)) document = outcome.model_dump(mode="json") if isinstance(outcome, HouseholdExecutionFailure): summary = household_failure_summary(outcome) @@ -299,6 +309,15 @@ def side( side=side, simulation_run_id=run_id, status=recorded.status, reason=reason ) + def _recorded_request( + self, request: HouseholdExecutionRequest + ) -> HouseholdExecutionRequest: + """Return the side's request for the variables its run records.""" + recorded = self.writer.household_run_variables(request.calculation_id) + return request.model_copy( + update={"variables": recorded, "add_missing_variables": recorded is None} + ) + def waited_side( # noqa: PLR0913 # the side, its calculation, then the wait self, side: HouseholdReportSide, diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/household_run_calculation_recording.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/household_run_calculation_recording.py new file mode 100644 index 000000000..ba64c74d6 --- /dev/null +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/household_run_calculation_recording.py @@ -0,0 +1,208 @@ +"""Recording the extra calculation of a household run a household function is given. + +An extra calculation calculates other variables of a household report's +simulation run, or its household across axes, under the run's household, +policy, dynamic, year and versions. The simulation service inserts it +pending with no Modal call, starts a household function with its ID and its +household contract request, then records the call's ID on it. The function +claims the calculation under its own Modal call ID, calculates the request, +and records the outcome, as the Modal worker role: the +``HouseholdExecutionResult`` as the calculation's result, or the +``HouseholdExecutionFailure``'s one-line summary as its error. A calculation +another call holds, or one already finished, is not calculated again. As for +a household job, a pre-emption records nothing, since Modal runs the call +again under the same call ID, and any other error or Modal's cancellation +fails the calculation with a generic summary. +""" + +from __future__ import annotations + +import logging +from dataclasses import dataclass +from datetime import UTC, datetime +from functools import partial +from typing import TYPE_CHECKING, Any, Protocol + +from policyengine_simulation_contract.household_execution import ( + HouseholdExecutionFailure, + HouseholdExecutionRequest, +) + +from .failure_recording import persist_failure_record +from .household_job_recording import ( + household_failure_summary, + unexpected_failure_summary, +) +from .household_report_recording import household_report_run_store + +if TYPE_CHECKING: + from collections.abc import Mapping + from uuid import UUID + + from policyengine_observability import ObservabilityRuntime + from policyengine_stage12_persistence import RunStatus, RunWrite + + from .household_report_recording import HouseholdCalculation + +logger = logging.getLogger(__name__) + + +class HouseholdRunCalculationWriter(Protocol): + """An extra calculation's writes; ``HouseholdReportRunStore`` implements them. + + Each write is conditional on the calculation's status and recorded Modal + call, and returns whether it changed the calculation, and its status + afterwards. + """ + + def claim_household_run_calculation( + self, calculation_id: UUID, *, modal_call_id: str, claimed_at: datetime + ) -> RunWrite: + """Mark a pending or running calculation that records no other call running.""" + ... + + def complete_household_run_calculation( + self, + calculation_id: UUID, + *, + modal_call_id: str, + result: Mapping[str, Any], + completed_at: datetime, + ) -> RunWrite: + """Mark the calculation succeeded with ``result`` while this call holds it.""" + ... + + def fail_household_run_calculation( + self, + calculation_id: UUID, + *, + modal_call_id: str, + error_message: str, + failed_at: datetime, + ) -> RunWrite: + """Mark the calculation failed while ``modal_call_id`` holds it.""" + ... + + +@dataclass(frozen=True) +class _CalculationCall: + """A household function's writes to the calculation it is given, under its call.""" + + writer: HouseholdRunCalculationWriter + calculation_id: UUID + modal_call_id: str + + def claim(self) -> RunWrite: + """Mark the calculation running under this call, unless another holds it.""" + return self.writer.claim_household_run_calculation( + self.calculation_id, + modal_call_id=self.modal_call_id, + claimed_at=datetime.now(UTC), + ) + + def complete(self, result: Mapping[str, Any]) -> RunWrite: + """Mark the calculation succeeded with its result document.""" + return self.writer.complete_household_run_calculation( + self.calculation_id, + modal_call_id=self.modal_call_id, + result=result, + completed_at=datetime.now(UTC), + ) + + def fail(self, error_message: str) -> RunWrite: + """Mark the calculation failed with its one-line summary.""" + return self.writer.fail_household_run_calculation( + self.calculation_id, + modal_call_id=self.modal_call_id, + error_message=error_message, + failed_at=datetime.now(UTC), + ) + + def fail_quietly( + self, error_message: str, *, runtime: ObservabilityRuntime | None + ) -> None: + """Fail the calculation, logging rather than raising a failed write.""" + persist_failure_record( + partial(self.fail, error_message), + runtime=runtime, + failure_scope="household_run_calculation", + ) + + +def run_household_run_calculation( # noqa: PLR0913 # the calculation, its payload and the call's seams + calculation_id: UUID, + payload: Mapping[str, Any], + calculate: HouseholdCalculation, + *, + modal_call_id: str | None, + runtime: ObservabilityRuntime | None = None, + writer: HouseholdRunCalculationWriter | None = None, +) -> dict[str, Any]: + """Claim the calculation, calculate ``payload`` with ``calculate``, record it. + + ``payload`` is the calculation's ``HouseholdExecutionRequest`` as JSON, + whose ``calculation_id`` is the calculation's. Returns the outcome as + JSON, or, for a calculation another call holds or one already finished, + a summary of it without calculating. ``writer`` defaults to the store the + Modal worker role's database URL names. Once the call holds the + calculation, a payload the contract refuses or that names another + calculation (ValueError), any other error, or Modal's cancellation fails + it with a generic summary, then propagates; a pre-emption doesn't. Raises + RuntimeError, before any write, when ``modal_call_id`` is None. + """ + if modal_call_id is None: + msg = "Modal household function call identifier is unavailable" + raise RuntimeError(msg) + call = _CalculationCall( + writer=writer or household_report_run_store(runtime), + calculation_id=calculation_id, + modal_call_id=modal_call_id, + ) + try: + claimed = call.claim() + if not claimed.changed: + return _calculation_summary(calculation_id, claimed.status) + outcome = calculate(_calculation_request(payload, calculation_id)) + document = outcome.model_dump(mode="json") + if isinstance(outcome, HouseholdExecutionFailure): + recorded = call.fail(household_failure_summary(outcome)) + else: + recorded = call.complete(document) + except KeyboardInterrupt: + # Pre-emption: Modal runs the call again, and it resumes this claim. + raise + except BaseException as error: + call.fail_quietly(unexpected_failure_summary(error), runtime=runtime) + raise + if not recorded.changed: + logger.warning( + "Household run calculation %s was %s before its outcome was recorded", + calculation_id, + recorded.status.value, + ) + return document + + +def _calculation_request( + payload: Mapping[str, Any], calculation_id: UUID +) -> HouseholdExecutionRequest: + """Return the payload's request; raise ValueError for one of another calculation. + + A payload the contract refuses raises its ValidationError, a ValueError. + """ + request = HouseholdExecutionRequest.model_validate(payload) + if request.calculation_id != calculation_id: + msg = ( + f"The payload names another calculation, {request.calculation_id}, " + f"than the call's, {calculation_id}" + ) + raise ValueError(msg) + return request + + +def _calculation_summary(calculation_id: UUID, status: RunStatus) -> dict[str, Any]: + return { + "deduplicated": True, + "household_run_calculation_id": str(calculation_id), + "status": status.value, + } diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/operation_records.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/operation_records.py index 366069de9..11cb89035 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/operation_records.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/operation_records.py @@ -7,7 +7,8 @@ - ``database_table``: the table holding that row, ``household_jobs``, ``report_runs`` (a report run, or a household report run), - ``simulation_runs`` or ``cliff_impacts``; + ``simulation_runs``, ``cliff_impacts`` or ``household_run_calculations`` + (a household run's extra calculation); - ``database_row_id``: the row's UUID; - ``modal_call_id``: the function's own Modal function call ID. @@ -33,7 +34,11 @@ # The tables a v2 Modal function's call works on. OperationTable = Literal[ - "cliff_impacts", "household_jobs", "report_runs", "simulation_runs" + "cliff_impacts", + "household_jobs", + "household_run_calculations", + "report_runs", + "simulation_runs", ] diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/run_sweep.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/run_sweep.py index 49a48b55f..30f96b769 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/run_sweep.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/run_sweep.py @@ -1,4 +1,4 @@ -"""The sweep that fails runs, household jobs and cliff results nothing will finish. +"""The sweep that fails runs, household jobs and calculations nothing will finish. A coordinator or worker records the Modal call running each run it claims, and the simulation service is to record the call it starts on a pending @@ -34,7 +34,9 @@ simulation service starts and a worker claims, is judged as a run is, from its first claim or, while pending, its creation. No run names it, so it is judged last; once failed it never counts, and the next request for its -run's cliffs starts another calculation. +run's cliffs starts another calculation. A household run's extra +calculation, which the simulation service starts and a household function +claims, is judged the same way, after the cliff results. A budget window's years are report runs naming its budget-window run. A year still pending with no call, in a window that hasn't finished, waits @@ -166,18 +168,20 @@ def settle_idle_window( # The order the sweep judges each kind in: report runs before simulation # runs, which are listed only once no unfinished report run names them, then -# household jobs and simulation runs' cliff results, which no run names. +# household jobs, simulation runs' cliff results and household runs' extra +# calculations, which no run names. SWEPT_KINDS = ( RunKind.REPORT_RUN, RunKind.SIMULATION_RUN, RunKind.HOUSEHOLD_JOB, RunKind.CLIFF_RESULT, + RunKind.HOUSEHOLD_RUN_CALCULATION, ) @dataclass(frozen=True) class SweepSummary: - """What the sweep did with the runs, household jobs and cliff results it listed. + """What the sweep did with the runs, jobs, cliff results and extra calculations. ``checked`` runs were judged after the minimum age: ``failed`` because their call ended, ``failed_without_call`` because they stayed pending with @@ -344,9 +348,10 @@ def sweep_stuck_runs( # noqa: PLR0913 # the stores, then keyword-only seams an ) -> SweepSummary: """Fail every listed run whose recorded Modal call has ended or was never started. - Household jobs and cliff results are judged as runs are. Runs older - than ``maximum_age`` are failed first, report runs, then simulation - runs, then household jobs, then cliff results, before any Modal lookup + Household jobs, cliff results and extra calculations are judged as runs + are. Runs older than ``maximum_age`` are failed first, report runs, then + simulation runs, then household jobs, then cliff results, then extra + calculations, before any Modal lookup can use up the scheduled function's time. Then, in the same order, so a dead coordinator's simulation runs are listed in the same sweep, each run older than ``minimum_age`` is judged: diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_household_reports.py b/projects/policyengine-simulation-executor/tests/test_stage12_household_reports.py index 5a3de84c0..ba0a430be 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_household_reports.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_household_reports.py @@ -142,6 +142,9 @@ class FakeHouseholdReportRuns: # Simulation runs whose claim raises, by run ID. simulation_claim_errors: dict[UUID, Exception] = field(default_factory=dict) record_result: RunWrite | None = None + # The variables each simulation run records; a run with none calculates + # every variable. + recorded_variables: dict[UUID, tuple[str, ...]] = field(default_factory=dict) writes: list[dict[str, Any]] = field(default_factory=list) def claim_report_run(self, report_run_id, *, modal_call_id, claimed_at): @@ -169,6 +172,9 @@ def claim_simulation_run(self, simulation_run_id, *, modal_call_id, claimed_at): def get_simulation_run(self, simulation_run_id): return self.simulation_states[simulation_run_id] + def household_run_variables(self, simulation_run_id): + return self.recorded_variables.get(simulation_run_id) + def complete_household_simulation_run( self, simulation_run_id, *, modal_call_id, household_result, completed_at ): @@ -350,6 +356,38 @@ def test_a_report_of_the_baseline_alone_calculates_one_side() -> None: assert len(answer["simulation_runs"]) == 1 +def test_each_side_calculates_the_variables_its_run_records() -> None: + """Identical requests share runs, so a run's list is the one it recorded. + + The payload's own list may be another request's: a run with none recorded + calculates every variable. + """ + runs = FakeHouseholdReportRuns( + recorded_variables={BASELINE_RUN_ID: ("age", "marginal_tax_rate")} + ) + payload = _calculation().model_dump(mode="json") + for side in ("baseline", "reform"): + payload[side]["variables"] = ["household_net_income"] + calculated: dict[UUID, tuple[tuple[str, ...] | None, bool]] = {} + + def calculate(request: HouseholdExecutionRequest) -> HouseholdExecutionResult: + calculated[request.calculation_id] = ( + request.variables, + request.add_missing_variables, + ) + return _succeeded(request) + + answer = household_report_recording.run_household_report( + REPORT_RUN_ID, payload, calculate, modal_call_id=CALL_ID, writer=runs + ) + + assert answer["status"] == "succeeded" + assert calculated == { + BASELINE_RUN_ID: (("age", "marginal_tax_rate"), False), + REFORM_RUN_ID: (None, True), + } + + def test_a_failed_side_is_recorded_and_fails_the_report_run_after_both_sides() -> None: runs = FakeHouseholdReportRuns() diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_household_run_calculations.py b/projects/policyengine-simulation-executor/tests/test_stage12_household_run_calculations.py new file mode 100644 index 000000000..35a2ebe7b --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_stage12_household_run_calculations.py @@ -0,0 +1,268 @@ +"""A household function records the extra calculation of a household run it is given. + +The simulation service inserts an extra calculation of a household report's +simulation run pending, and starts a household function with its ID and its +household contract request. The function claims the calculation under its +Modal call ID, calculates the request, and records the calculated household +as its result, or the failure's one-line summary. A calculation another call +holds, or one already finished, is not calculated again. Modal pre-empts a +call with SIGINT, which a synchronous function receives as +``KeyboardInterrupt``, and runs it again under the same call ID, so a +pre-emption records nothing. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any +from uuid import UUID + +import pytest +from policyengine_simulation_contract.household_execution import ( + HouseholdCalculationError, + HouseholdExecutionFailure, + HouseholdExecutionRequest, + HouseholdExecutionResult, + HouseholdWorkerIdentity, +) +from policyengine_simulation_executor.stage12_runtime import ( + household_run_calculation_recording, +) +from policyengine_stage12_persistence import RunStatus, RunWrite + +CALCULATION_ID = UUID("00000000-0000-4000-8000-0000000000e1") +OTHER_CALCULATION_ID = UUID("00000000-0000-4000-8000-0000000000e2") +CALL_ID = "fc-extra-calculation" +WORKER = HouseholdWorkerIdentity( + application_name="policyengine-simulation-v2-py6-17-1", + function_name="calculate_household_us", +) +BUNDLE = { + "policyengine_version": "6.17.1", + "core_package_version": "3.33.0", + "country_package_name": "policyengine-us", + "country_package_version": "1.764.6", + "bundle_manifest_sha256": "a" * 64, +} +CHANGED = { + "running": RunWrite(changed=True, status=RunStatus.RUNNING), + "succeeded": RunWrite(changed=True, status=RunStatus.SUCCEEDED), + "failed": RunWrite(changed=True, status=RunStatus.FAILED), +} + + +def _payload(calculation_id: UUID = CALCULATION_ID) -> dict[str, Any]: + return { + "calculation_id": str(calculation_id), + "country": "us", + "year": "2026", + "household": { + "people": {"you": {"age": {"2026": 40}}}, + "axes": [ + [{"name": "employment_income", "count": 3, "min": 0, "max": 60_000}] + ], + }, + "policy": {"parameters": {}}, + "variables": ["marginal_tax_rate"], + "bundle": BUNDLE, + } + + +def _succeeded(request: HouseholdExecutionRequest) -> HouseholdExecutionResult: + return HouseholdExecutionResult.model_validate( + { + "calculation_id": str(request.calculation_id), + "output": { + "country": "us", + "bundle": BUNDLE, + "household": {"people": {"you": {"age": {"2026": 40}}}}, + }, + "worker": WORKER.model_dump(), + } + ) + + +def _failed(request: HouseholdExecutionRequest) -> HouseholdExecutionFailure: + return HouseholdExecutionFailure( + calculation_id=request.calculation_id, + error=HouseholdCalculationError( + code="invalid_inputs", message="Unrecognized\nvariable: x" + ), + worker=WORKER, + ) + + +@dataclass +class FakeCalculationWrites: + """Records each write; a test sets what the claim returns or raises.""" + + claim: RunWrite = CHANGED["running"] + claim_error: Exception | None = None + writes: list[dict[str, Any]] = field(default_factory=list) + + def claim_household_run_calculation( + self, calculation_id, *, modal_call_id, claimed_at + ): + self.writes.append( + {"write": "claim", "id": calculation_id, "call": modal_call_id} + ) + if self.claim_error is not None: + raise self.claim_error + return self.claim + + def complete_household_run_calculation( + self, calculation_id, *, modal_call_id, result, completed_at + ): + self.writes.append( + { + "write": "complete", + "id": calculation_id, + "call": modal_call_id, + "result": result, + } + ) + return CHANGED["succeeded"] + + def fail_household_run_calculation( + self, calculation_id, *, modal_call_id, error_message, failed_at + ): + self.writes.append( + { + "write": "fail", + "id": calculation_id, + "call": modal_call_id, + "error_message": error_message, + } + ) + return CHANGED["failed"] + + @property + def kinds(self) -> list[str]: + return [write["write"] for write in self.writes] + + +def _run(writes, calculate, *, payload=None, modal_call_id=CALL_ID): + return household_run_calculation_recording.run_household_run_calculation( + CALCULATION_ID, + payload or _payload(), + calculate, + modal_call_id=modal_call_id, + writer=writes, + ) + + +def test_a_calculation_is_claimed_calculated_and_its_result_recorded() -> None: + writes = FakeCalculationWrites() + calculated: list[HouseholdExecutionRequest] = [] + + def calculate(request: HouseholdExecutionRequest) -> HouseholdExecutionResult: + calculated.append(request) + return _succeeded(request) + + answer = _run(writes, calculate) + + (request,) = calculated + assert request == HouseholdExecutionRequest.model_validate(_payload()) + document = _succeeded(request).model_dump(mode="json") + assert writes.writes == [ + {"write": "claim", "id": CALCULATION_ID, "call": CALL_ID}, + { + "write": "complete", + "id": CALCULATION_ID, + "call": CALL_ID, + "result": document, + }, + ] + assert answer == document + + +def test_a_failed_calculation_records_its_one_line_summary() -> None: + """The row's result is set only when it succeeded, so the summary is all.""" + writes = FakeCalculationWrites() + + answer = _run(writes, _failed) + + assert writes.kinds == ["claim", "fail"] + assert writes.writes[1]["error_message"] == ( + "invalid_inputs: Unrecognized variable: x" + ) + assert answer["status"] == "failed" + + +@pytest.mark.parametrize("status", [RunStatus.RUNNING, RunStatus.SUCCEEDED]) +def test_a_calculation_another_call_holds_or_that_finished_is_not_calculated( + status: RunStatus, +) -> None: + writes = FakeCalculationWrites(claim=RunWrite(changed=False, status=status)) + + def calculate(request: HouseholdExecutionRequest) -> HouseholdExecutionResult: + msg = "a calculation this call doesn't hold was calculated" + raise AssertionError(msg) + + answer = _run(writes, calculate) + + assert writes.kinds == ["claim"] + assert answer == { + "deduplicated": True, + "household_run_calculation_id": str(CALCULATION_ID), + "status": status.value, + } + + +def test_a_payload_for_another_calculation_fails_the_one_it_claimed() -> None: + writes = FakeCalculationWrites() + + with pytest.raises(ValueError, match="another calculation"): + _run(writes, _succeeded, payload=_payload(OTHER_CALCULATION_ID)) + + assert writes.kinds == ["claim", "fail"] + assert writes.writes[1]["error_message"] == ( + "household_function_error: The household function raised ValueError." + ) + + +def test_a_payload_the_contract_refuses_fails_the_calculation_it_claimed() -> None: + writes = FakeCalculationWrites() + payload = {**_payload(), "variables": ["age", "age"]} + + with pytest.raises(ValueError, match="distinct"): + _run(writes, _succeeded, payload=payload) + + assert writes.kinds == ["claim", "fail"] + + +def test_an_unexpected_error_fails_the_calculation_then_propagates() -> None: + writes = FakeCalculationWrites() + + def calculate(request: HouseholdExecutionRequest) -> HouseholdExecutionResult: + msg = "out of memory" + raise RuntimeError(msg) + + with pytest.raises(RuntimeError, match="out of memory"): + _run(writes, calculate) + + assert writes.kinds == ["claim", "fail"] + assert writes.writes[1]["error_message"] == ( + "household_function_error: The household function raised RuntimeError." + ) + + +def test_a_preemption_records_nothing_and_propagates() -> None: + writes = FakeCalculationWrites() + + def calculate(request: HouseholdExecutionRequest) -> HouseholdExecutionResult: + raise KeyboardInterrupt + + with pytest.raises(KeyboardInterrupt): + _run(writes, calculate) + + assert writes.kinds == ["claim"] + + +def test_a_call_without_a_modal_call_id_writes_nothing() -> None: + writes = FakeCalculationWrites() + + with pytest.raises(RuntimeError, match="call identifier"): + _run(writes, _succeeded, modal_call_id=None) + + assert writes.writes == [] diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_modal_app.py b/projects/policyengine-simulation-executor/tests/test_stage12_modal_app.py index f0db7a59f..47f0216b6 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_modal_app.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_modal_app.py @@ -1010,7 +1010,11 @@ def run_household_report(report_run_id, payload, calculate_side, **keywords): def test_a_household_function_refuses_a_job_and_a_report_run_together( monkeypatch, ) -> None: - from policyengine_simulation_executor import stage12_runtime + # Imported first: its imports register their own exit handlers once. + from policyengine_simulation_executor import ( # noqa: F401 + household_calculation, + stage12_runtime, + ) module = _load(monkeypatch) runtime = RecordingRuntime() @@ -1024,7 +1028,7 @@ def refuse(*_args, **_keywords): monkeypatch.setattr(stage12_runtime, "run_household_report", refuse) - with pytest.raises(ValueError, match="either a household job or a report run"): + with pytest.raises(ValueError, match="at most one of"): module.calculate_household_us( _household_report_payload("us"), household_job_id="00000000-0000-4000-8000-00000000a001", diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_modal_household_run_calculations.py b/projects/policyengine-simulation-executor/tests/test_stage12_modal_household_run_calculations.py new file mode 100644 index 000000000..54b93d76e --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_stage12_modal_household_run_calculations.py @@ -0,0 +1,130 @@ +"""The v2 household functions' calls that name an extra calculation (D2 · 3b). + +A household function called with ``household_run_calculation_id`` claims +that extra calculation of a household report run's simulation run and +records its outcome on it (``stage12_runtime.run_household_run_calculation``), +in one operation naming the row. A call names at most one of a household +job, a report run and an extra calculation. +""" + +from __future__ import annotations + +from uuid import UUID + +import pytest +from test_stage12_modal_app import ( + OPERATION_RECORD_KEYS, + RecordingRuntime, + _household_payload, + _load, + _observability_context, + _record_exit_handlers, + _refuse_household_jobs, +) + +HOUSEHOLD_RUN_CALCULATION_ID = "00000000-0000-4000-8000-00000000a003" + + +@pytest.mark.parametrize("country", ["us", "uk"]) +def test_household_functions_record_the_extra_calculation_their_call_names( + monkeypatch, country +) -> None: + from policyengine_simulation_contract.household_execution import ( + HouseholdExecutionRequest, + ) + from policyengine_simulation_executor import ( + household_calculation, + stage12_runtime, + ) + + module = _load(monkeypatch) + runtime = RecordingRuntime() + monkeypatch.setattr(module, "init_process_observability", lambda **_: runtime) + exit_handlers = _record_exit_handlers(monkeypatch) + monkeypatch.setattr( + module.modal, + "current_function_call_id", + lambda: "fc-extra-calculation", + raising=False, + ) + _refuse_household_jobs(monkeypatch) + calculated: list[dict] = [] + recorded: list[dict] = [] + + def calculate(request, **keywords): + calculated.append({"request": request, **keywords}) + return request.calculation_id + + def run_household_run_calculation( + calculation_id, payload, calculate_request, **keywords + ): + recorded.append( + {"calculation_id": calculation_id, "payload": payload, **keywords} + ) + request = HouseholdExecutionRequest.model_validate(payload) + return {"status": "succeeded", "outcome": str(calculate_request(request))} + + monkeypatch.setattr(household_calculation, "calculate_household", calculate) + monkeypatch.setattr( + stage12_runtime, "run_household_run_calculation", run_household_run_calculation + ) + + result = getattr(module, f"calculate_household_{country}")( + _household_payload(country), + observability_context=_observability_context(), + household_run_calculation_id=HOUSEHOLD_RUN_CALCULATION_ID, + ) + + assert result == { + "status": "succeeded", + "outcome": "00000000-0000-4000-8000-0000000000c1", + } + (calculation,) = recorded + assert calculation == { + "calculation_id": UUID(HOUSEHOLD_RUN_CALCULATION_ID), + # The recording code validates the payload once it holds the row. + "payload": _household_payload(country), + "modal_call_id": "fc-extra-calculation", + "runtime": runtime, + } + (call,) = calculated + assert call["required_country"] == country + (operation,) = runtime.operations + assert operation["name"] == "v2_household_execution" + assert {key: operation["attributes"][key] for key in OPERATION_RECORD_KEYS} == { + "database_table": "household_run_calculations", + "database_row_id": HOUSEHOLD_RUN_CALCULATION_ID, + "modal_call_id": "fc-extra-calculation", + } + # The container's runtime stays open for its next call. + assert runtime.shutdown_calls == 0 + assert exit_handlers == [runtime.shutdown] + + +@pytest.mark.parametrize( + "records", + [ + {"household_job_id": "00000000-0000-4000-8000-00000000a001"}, + {"household_report_run_id": "00000000-0000-4000-8000-00000000a002"}, + ], + ids=["job", "report-run"], +) +def test_a_household_function_refuses_an_extra_calculation_beside_another_row( + monkeypatch, records +) -> None: + # Imported first: its imports register their own exit handlers once. + from policyengine_simulation_executor import household_calculation # noqa: F401 + + module = _load(monkeypatch) + runtime = RecordingRuntime() + monkeypatch.setattr(module, "init_process_observability", lambda **_: runtime) + exit_handlers = _record_exit_handlers(monkeypatch) + + with pytest.raises(ValueError, match="at most one of"): + module.calculate_household_us( + _household_payload("us"), + household_run_calculation_id=HOUSEHOLD_RUN_CALCULATION_ID, + **records, + ) + assert runtime.shutdown_calls == 0 + assert exit_handlers == [runtime.shutdown] diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_run_sweep.py b/projects/policyengine-simulation-executor/tests/test_stage12_run_sweep.py index c66dcbbf2..49f4b209b 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_run_sweep.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_run_sweep.py @@ -149,20 +149,25 @@ def test_the_sweep_lists_runs_older_than_its_minimum_age() -> None: minimum_age=timedelta(minutes=15), ) - # Report runs, simulation runs, household jobs and cliff results. - assert store.cutoffs == [NOW - timedelta(minutes=15)] * 4 + # Report runs, simulation runs, household jobs, cliff results and + # household runs' extra calculations. + assert store.cutoffs == [NOW - timedelta(minutes=15)] * 5 def test_report_runs_are_swept_before_simulation_runs_are_listed() -> None: # A simulation run is listed only once no report run naming it is # running, so failing a dead coordinator's report run first lets the same # sweep reach its children. Household jobs and simulation runs' cliff - # calculations, which no run names, follow. + # calculations and household runs' extra calculations, which no run + # names, follow. report_run = _run("fc-coordinator", RunKind.REPORT_RUN) simulation_run = _run("fc-worker") household_job = _run("fc-household", RunKind.HOUSEHOLD_JOB) cliff_result = _run("fc-cliffs", RunKind.CLIFF_RESULT) - store = FakeSweepStore([cliff_result, household_job, simulation_run, report_run]) + extra = _run("fc-extra", RunKind.HOUSEHOLD_RUN_CALCULATION) + store = FakeSweepStore( + [extra, cliff_result, household_job, simulation_run, report_run] + ) sweep_stuck_runs(store, call_state=lambda _: CallState.ENDED, now=NOW) @@ -171,6 +176,7 @@ def test_report_runs_are_swept_before_simulation_runs_are_listed() -> None: "list-expired:simulation_run", "list-expired:household_job", "list-expired:cliff_result", + "list-expired:household_run_calculation", "list:report_run", "fail:report_run", "list:simulation_run", @@ -179,9 +185,31 @@ def test_report_runs_are_swept_before_simulation_runs_are_listed() -> None: "fail:household_job", "list:cliff_result", "fail:cliff_result", + "list:household_run_calculation", + "fail:household_run_calculation", ] +def test_household_run_calculations_are_judged_as_cliff_results_are() -> None: + """A dead extra calculation fails, so a later request starts another one.""" + kind = RunKind.HOUSEHOLD_RUN_CALCULATION + never_started = _run(None, kind, RunStatus.PENDING) + ended_running = _run("fc-ended", kind) + still_running = _run("fc-running", kind) + store = FakeSweepStore([never_started, ended_running, still_running]) + states = {"fc-ended": CallState.ENDED, "fc-running": CallState.RUNNING} + + summary = sweep_stuck_runs(store, call_state=states.__getitem__, now=NOW) + + failed = {run: message for run, message, _ in store.failed} + assert set(failed) == {never_started, ended_running} + assert failed[never_started].startswith("run_not_started: ") + assert failed[ended_running].startswith("modal_call_ended: ") + assert summary == SweepSummary( + checked=3, failed=1, running=1, unknown=0, failed_without_call=1 + ) + + def test_cliff_results_are_judged_as_runs_are() -> None: """A dead cliff calculation fails, so a later request starts another one.""" # The simulation service stopped before starting the call. @@ -440,9 +468,9 @@ def test_the_age_limit_fails_a_simulation_run_whatever_report_runs_name_it() -> sweep_stuck_runs(store, call_state=lambda _: CallState.ENDED, now=NOW) assert [run for run, _, _ in store.failed] == [expired, judged] - # The age limit's four listings and its failure ignore report runs; the - # minimum age's four listings and failure don't. - assert store.listed_regardless == [True] * 4 + [False] * 4 + # The age limit's five listings and its failure ignore report runs; the + # minimum age's five listings and failure don't. + assert store.listed_regardless == [True] * 5 + [False] * 5 assert store.failed_regardless == [True, False] @@ -474,8 +502,8 @@ def call_state(call_id): maximum_age=timedelta(hours=24), ) - assert store.expired_cutoffs == [NOW - timedelta(hours=24)] * 4 - assert store.cutoffs == [NOW - timedelta(minutes=10)] * 4 + assert store.expired_cutoffs == [NOW - timedelta(hours=24)] * 5 + assert store.cutoffs == [NOW - timedelta(minutes=10)] * 5 # Every kind's age check comes before any lookup. assert asked == [ ( @@ -485,6 +513,7 @@ def call_state(call_id): "list-expired:simulation_run", "list-expired:household_job", "list-expired:cliff_result", + "list-expired:household_run_calculation", "list:report_run", ], ) diff --git a/rules/fixtures/sim.persistence.missing-privileges-reported/bad_grants.txt b/rules/fixtures/sim.persistence.missing-privileges-reported/bad_grants.txt index fbf6fa48d..d19409f44 100644 --- a/rules/fixtures/sim.persistence.missing-privileges-reported/bad_grants.txt +++ b/rules/fixtures/sim.persistence.missing-privileges-reported/bad_grants.txt @@ -1,50 +1,7 @@ -# Proof fixture: the grants with INSERT on simulation_runs left out, as when -# a role was set up before the table existed, and UPDATE on -# report_runs.modal_call_id, as when a column was added after the grants. -INSERT simulations -SELECT simulations -INSERT reports -SELECT reports -SELECT simulation_runs -INSERT report_runs -SELECT report_runs -INSERT budget_window_runs -SELECT budget_window_runs -INSERT household_jobs -SELECT household_jobs -INSERT cliff_impacts -SELECT cliff_impacts -SELECT policies -SELECT households -SELECT tax_benefit_models -SELECT tax_benefit_model_versions -SELECT regions -SELECT datasets -SELECT parameters -SELECT parameter_values -SELECT dynamics -SELECT dynamic_parameters -SELECT dynamic_parameter_values -UPDATE simulation_runs completed_at -UPDATE simulation_runs error_message -UPDATE simulation_runs modal_call_id -UPDATE simulation_runs status -UPDATE simulation_runs updated_at -UPDATE report_runs completed_at -UPDATE report_runs error_message -UPDATE report_runs status -UPDATE report_runs updated_at -UPDATE budget_window_runs completed_at -UPDATE budget_window_runs error_message -UPDATE budget_window_runs status -UPDATE budget_window_runs updated_at -UPDATE household_jobs completed_at -UPDATE household_jobs error_message -UPDATE household_jobs modal_call_id -UPDATE household_jobs status -UPDATE household_jobs updated_at -UPDATE cliff_impacts completed_at -UPDATE cliff_impacts error_message -UPDATE cliff_impacts modal_call_id -UPDATE cliff_impacts status -UPDATE cliff_impacts updated_at +# Proof fixture: the grants left out of every privilege the simulation +# service needs, one per line as `
[]`: INSERT on +# simulation_runs, as when a role was set up before the table existed, and +# UPDATE on report_runs.modal_call_id, as when a column was added after the +# grants. +INSERT simulation_runs +UPDATE report_runs modal_call_id diff --git a/rules/fixtures/sim.persistence.missing-privileges-reported/good_grants.txt b/rules/fixtures/sim.persistence.missing-privileges-reported/good_grants.txt index fe1869957..f644cfa38 100644 --- a/rules/fixtures/sim.persistence.missing-privileges-reported/good_grants.txt +++ b/rules/fixtures/sim.persistence.missing-privileges-reported/good_grants.txt @@ -1,50 +1,3 @@ -# Proof fixture: every privilege the simulation service needs, one per line. -INSERT simulations -SELECT simulations -INSERT reports -SELECT reports -INSERT simulation_runs -SELECT simulation_runs -INSERT report_runs -SELECT report_runs -INSERT budget_window_runs -SELECT budget_window_runs -INSERT household_jobs -SELECT household_jobs -INSERT cliff_impacts -SELECT cliff_impacts -SELECT policies -SELECT households -SELECT tax_benefit_models -SELECT tax_benefit_model_versions -SELECT regions -SELECT datasets -SELECT parameters -SELECT parameter_values -SELECT dynamics -SELECT dynamic_parameters -SELECT dynamic_parameter_values -UPDATE simulation_runs completed_at -UPDATE simulation_runs error_message -UPDATE simulation_runs modal_call_id -UPDATE simulation_runs status -UPDATE simulation_runs updated_at -UPDATE report_runs completed_at -UPDATE report_runs error_message -UPDATE report_runs modal_call_id -UPDATE report_runs status -UPDATE report_runs updated_at -UPDATE budget_window_runs completed_at -UPDATE budget_window_runs error_message -UPDATE budget_window_runs status -UPDATE budget_window_runs updated_at -UPDATE household_jobs completed_at -UPDATE household_jobs error_message -UPDATE household_jobs modal_call_id -UPDATE household_jobs status -UPDATE household_jobs updated_at -UPDATE cliff_impacts completed_at -UPDATE cliff_impacts error_message -UPDATE cliff_impacts modal_call_id -UPDATE cliff_impacts status -UPDATE cliff_impacts updated_at +# Proof fixture: the grants left out of every privilege the simulation +# service needs, one per line as `
[]`. None are +# left out, so the role lacks nothing.