From fc318fa36e0f9f783ba7931179d99a09afe01eec Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 4 Dec 2026 01:57:47 +0400 Subject: [PATCH 01/12] Add tests for household reports' variables, which fail before the change The tests cover the variables list on POST /v2/reports for a household report and on POST /v2/reports/{id}/runs: the list's limits, the check against the running catalog version, the request bodies sent to the simulation service, the refusal of a list for an economy report or a budget window, and the 1 MiB request size limit. Co-Authored-By: Claude Opus 5.5 --- tests/unit/v2/report_run_support.py | 6 +- .../v2/test_household_report_variables.py | 624 ++++++++++++++++++ tests/unit/v2/test_report_run_routes.py | 5 +- 3 files changed, 632 insertions(+), 3 deletions(-) create mode 100644 tests/unit/v2/test_household_report_variables.py diff --git a/tests/unit/v2/report_run_support.py b/tests/unit/v2/report_run_support.py index efe1beee3..d8fa1e87a 100644 --- a/tests/unit/v2/report_run_support.py +++ b/tests/unit/v2/report_run_support.py @@ -25,6 +25,8 @@ ) if TYPE_CHECKING: + from collections.abc import Sequence + from policyengine_api.services.v2.identity.types import AccountPrincipal from policyengine_api.services.v2.stored_reports.types import ( StoredReportRead, @@ -110,13 +112,14 @@ class FakeReportRunService(FakeReportService): runs: StoredReportRunsRead = field(default_factory=report_runs_read) rerun: StoredReportRead | None = None - def rerun_report( + def rerun_report( # noqa: PLR0913 # the report service protocol's keyword arguments self, *, country_id: str, report_id: UUID, force: bool, include_cliffs: bool = False, + variables: Sequence[str] | None = None, requester: AccountPrincipal | None = None, ) -> StoredReportRead: self.requesters.append(requester) @@ -126,6 +129,7 @@ def rerun_report( report_id=report_id, force=force, include_cliffs=include_cliffs, + variables=None if variables is None else list(variables), ) return self.report if self.rerun is None else self.rerun diff --git a/tests/unit/v2/test_household_report_variables.py b/tests/unit/v2/test_household_report_variables.py new file mode 100644 index 000000000..1d902fa4a --- /dev/null +++ b/tests/unit/v2/test_household_report_variables.py @@ -0,0 +1,624 @@ +"""A household report's list of variables: its limits, its checks, what is sent. + +Creating a household report (``POST /v2/reports``, kind ``household``) or +running one again (``POST /v2/reports/{id}/runs``) may list the variables each +side's run calculates (``variables``). Leaving the list out, or null, +calculates every variable, as every household report did before. A list holds +1 to 10,000 distinct names of 1 to 255 characters with no NUL character, as +``/v2/household-calculations`` takes them, except that an empty list is +refused: a household run records the variables it calculated, and an empty +record would read back as every variable. Each name must be a variable of the +running catalog version, checked after the household, policies and dynamics. +Only a household report takes a list. Both routes take bodies of up to 1 MiB, +so a list of the most names fits. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any + +import pytest +from pydantic import BaseModel, ValidationError + +from policyengine_api.fastapi_routes.v2.reports.run_models import ( + ReportRerunRequest, +) +from policyengine_api.libs.simulation_report_reruns import report_rerun_request +from policyengine_api.libs.simulation_reports import household_report_request +from policyengine_api.services.v2.dynamics.validators import DynamicNotFoundError +from policyengine_api.services.v2.household_calculations.validators import ( + HouseholdCalculationStorageError, + HouseholdCalculationVariablesUnknownError, +) +from policyengine_api.services.v2.simulation_service.services import ( + SimulationSubmissionService, +) +from policyengine_api.services.v2.simulation_service.types import ( + HouseholdReportCreationInput, + ReportRerunInput, + StartedReportRun, +) +from policyengine_api.services.v2.simulation_service.validators import ( + SubmissionStorageError, +) +from policyengine_api.services.v2.stored_reports.database_session import ( + StoredReportDatabaseSession, +) +from policyengine_api.services.v2.stored_reports.services import V2StoredReportService +from tests.unit.v2.report_run_support import FakeReportRunService +from tests.unit.v2.stored_report_support import ( + REPORT_ID, + FakeReportService, + report_route_client, +) +from tests.unit.v2.test_household_report_reads import ( + current_versions, + sessions, # noqa: F401 # the fixture the service tests use + store_economy_report, + store_household_report, + succeeded_run, +) +from tests.unit.v2.test_household_report_routes import ( + household_body, + household_report_read, +) +from tests.unit.v2.test_household_report_submissions import ( + RecordingHouseholdReportService, + StoredHouseholds, + household_report_input, + unconfigured_client, +) +from tests.unit.v2.test_simulation_submissions import ( + SERVED_COUNTRIES, + STORED_POLICY_ID, + StoredCountries, + StoredDynamics, + StoredPolicies, +) + +if TYPE_CHECKING: + from collections.abc import Sequence + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + +REPORTS = "/v2/reports?country_id=us" +RUNS = f"/v2/reports/{REPORT_ID}/runs?country_id=us" +SUMMARY_VARIABLES = ["household_net_income", "snap", "employment_income"] +MAXIMUM_LISTED_VARIABLES = 10_000 +MAXIMUM_VARIABLE_NAME_LENGTH = 255 +# The most names a list may hold, each 60 characters long: about 615 KiB of +# JSON, which a body limited to 16 KiB could never carry. +LONGEST_LIST = [ + f"variable_{index:05d}_".ljust(60, "x") for index in range(MAXIMUM_LISTED_VARIABLES) +] +ONE_MEBIBYTE = 1024 * 1024 +UNKNOWN_VARIABLES_ANSWER = { + "status": "error", + "message": ( + "The calculation lists variables the running catalog version does not " + "have: removed_benefit, snep" + ), + "code": "unknown_variables", + "unknown_variables": ["removed_benefit", "snep"], +} + + +def _report_fields(**changes: object) -> dict[str, object]: + fields: dict[str, object] = { + "country_id": "us", + "kind": "household", + "household_id": "00000000-0000-0000-0000-00000000e001", + "baseline": {}, + "reform": None, + } + fields.update(changes) + return fields + + +def _rerun_fields(**changes: object) -> dict[str, object]: + return dict(changes) + + +# Each model that takes a household report's list, and a body of that model. +MODELS = { + "create": (HouseholdReportCreationInput, _report_fields), + "rerun": (ReportRerunRequest, _rerun_fields), +} + + +def _refusals(model: type[BaseModel], fields: dict[str, object]) -> list[Any]: + """Return the validation errors refusing ``fields``, none when they are accepted.""" + try: + model.model_validate(fields) + except ValidationError as refusal: + return refusal.errors(include_url=False, include_input=False) + return [] + + +@pytest.mark.parametrize("model", list(MODELS)) +def test_a_report_lists_its_variables_in_the_order_given(model: str) -> None: + model_type, fields = MODELS[model] + + validated = model_type.model_validate(fields(variables=SUMMARY_VARIABLES)) + + assert getattr(validated, "variables", "absent") == SUMMARY_VARIABLES + + +@pytest.mark.parametrize("model", list(MODELS)) +@pytest.mark.parametrize("given", [{}, {"variables": None}], ids=["omitted", "null"]) +def test_a_report_without_a_list_calculates_every_variable( + model: str, given: dict[str, object] +) -> None: + model_type, fields = MODELS[model] + + validated = model_type.model_validate(fields(**given)) + + assert getattr(validated, "variables", "absent") is None + + +@pytest.mark.parametrize("model", list(MODELS)) +def test_an_empty_list_is_refused(model: str) -> None: + model_type, fields = MODELS[model] + + refusals = _refusals(model_type, fields(variables=[])) + + assert [refusal["type"] for refusal in refusals] == ["too_short"] + assert refusals[0]["loc"] == ("variables",) + + +@pytest.mark.parametrize("model", list(MODELS)) +def test_a_list_of_the_most_names_is_accepted(model: str) -> None: + model_type, fields = MODELS[model] + + assert _refusals(model_type, fields(variables=LONGEST_LIST)) == [] + + +@pytest.mark.parametrize("model", list(MODELS)) +def test_a_list_longer_than_the_most_names_is_refused(model: str) -> None: + model_type, fields = MODELS[model] + + refusals = _refusals(model_type, fields(variables=[*LONGEST_LIST, "snap"])) + + assert [refusal["type"] for refusal in refusals] == ["too_long"] + assert refusals[0]["loc"] == ("variables",) + + +@pytest.mark.parametrize("model", list(MODELS)) +def test_a_variable_listed_twice_is_refused_by_name(model: str) -> None: + model_type, fields = MODELS[model] + + refusals = _refusals( + model_type, fields(variables=["snap", "household_net_income", "snap"]) + ) + + assert len(refusals) == 1 + assert refusals[0]["loc"] == ("variables",) + assert "snap more than once" in refusals[0]["msg"] + + +@pytest.mark.parametrize("model", list(MODELS)) +def test_a_name_holding_a_nul_character_is_refused(model: str) -> None: + model_type, fields = MODELS[model] + + refusals = _refusals(model_type, fields(variables=["snap", "net\x00income"])) + + assert len(refusals) == 1 + assert refusals[0]["loc"] == ("variables",) + assert "NUL character" in refusals[0]["msg"] + + +@pytest.mark.parametrize("model", list(MODELS)) +@pytest.mark.parametrize( + ("name", "refusal_type"), + [ + ("", "string_too_short"), + ("x" * (MAXIMUM_VARIABLE_NAME_LENGTH + 1), "string_too_long"), + ], + ids=["empty", "too-long"], +) +def test_a_name_the_simulation_service_cannot_take_is_refused( + model: str, name: str, refusal_type: str +) -> None: + model_type, fields = MODELS[model] + + refusals = _refusals(model_type, fields(variables=["snap", name])) + + assert [refusal["type"] for refusal in refusals] == [refusal_type] + assert refusals[0]["loc"] == ("variables", 1) + + +def test_a_name_of_the_most_characters_is_accepted() -> None: + name = "x" * MAXIMUM_VARIABLE_NAME_LENGTH + + assert ( + _refusals(HouseholdReportCreationInput, _report_fields(variables=[name])) == [] + ) + + +def test_listed_variables_are_sent_to_the_simulation_service() -> None: + report = household_report_input(variables=["snap", "household_net_income"]) + rerun = ReportRerunInput( + country_id="us", + report_id=REPORT_ID, + kind="household", + force=False, + policy_ids=(None,), + variables=("snap", "household_net_income"), + ) + + assert household_report_request(report)["variables"] == [ + "snap", + "household_net_income", + ] + assert report_rerun_request(rerun) == { + "force": False, + "variables": ["snap", "household_net_income"], + } + + +def test_a_report_without_a_list_sends_none() -> None: + rerun = ReportRerunInput( + country_id="us", + report_id=REPORT_ID, + kind="household", + force=False, + policy_ids=(None,), + ) + + assert "variables" not in household_report_request(household_report_input()) + assert report_rerun_request(rerun) == {"force": False} + + +@dataclass +class RunningCatalogVariables: + """The running catalog version's variables: ``known`` in every country. + + Each check is recorded; a name outside ``known`` is refused as unknown, + and with ``error`` every check raises it, as a catalog that cannot be + read does. + """ + + known: frozenset[str] = frozenset(SUMMARY_VARIABLES) + error: Exception | None = None + checked: list[tuple[str, tuple[str, ...]]] = field(default_factory=list) + + def require_known_variables( + self, *, country_id: str, variables: Sequence[str] + ) -> None: + self.checked.append((country_id, tuple(variables))) + if self.error is not None: + raise self.error + unknown = tuple(sorted(set(variables) - self.known)) + if unknown: + raise HouseholdCalculationVariablesUnknownError(unknown) + + +def _submissions( + client_factory: Any, + variables: RunningCatalogVariables, + *, + dynamics: StoredDynamics | None = None, +) -> SimulationSubmissionService: + return SimulationSubmissionService( + countries=StoredCountries(countries=SERVED_COUNTRIES), + households=StoredHouseholds(), + policies=StoredPolicies(), + dynamics=dynamics or StoredDynamics(), + variables=variables, + client_factory=client_factory, + ) + + +def test_a_household_reports_variables_are_checked_then_sent() -> None: + client = RecordingHouseholdReportService() + variables = RunningCatalogVariables() + report = household_report_input(variables=SUMMARY_VARIABLES) + + _submissions(lambda: client, variables).submit_household_report(report) + + assert variables.checked == [("us", tuple(SUMMARY_VARIABLES))] + assert client.household_reports == [report] + + +def test_a_household_report_listing_unknown_variables_is_refused_by_name() -> None: + variables = RunningCatalogVariables() + report = household_report_input(variables=["snap", "snep", "removed_benefit"]) + + with pytest.raises(HouseholdCalculationVariablesUnknownError) as refused: + _submissions(unconfigured_client, variables).submit_household_report(report) + + assert refused.value.unknown_variables == ("removed_benefit", "snep") + + +def test_a_household_reports_variables_are_checked_after_its_dynamics() -> None: + variables = RunningCatalogVariables() + dynamics = StoredDynamics() + report = household_report_input( + variables=["snep"], + reform={"policy_id": str(STORED_POLICY_ID), "dynamic_id": str(REPORT_ID)}, + ) + + with pytest.raises(DynamicNotFoundError): + _submissions( + unconfigured_client, variables, dynamics=dynamics + ).submit_household_report(report) + + assert dynamics.asked + assert variables.checked == [] + + +def test_a_household_report_without_a_list_checks_no_variables() -> None: + client = RecordingHouseholdReportService() + variables = RunningCatalogVariables() + + _submissions(lambda: client, variables).submit_household_report( + household_report_input() + ) + + assert variables.checked == [] + assert len(client.household_reports) == 1 + + +def test_a_variable_check_that_cannot_read_storage_is_a_storage_failure() -> None: + variables = RunningCatalogVariables( + error=HouseholdCalculationStorageError( + "V2 household calculation storage is unavailable" + ) + ) + report = household_report_input(variables=SUMMARY_VARIABLES) + + with pytest.raises(SubmissionStorageError) as refused: + _submissions(unconfigured_client, variables).submit_household_report(report) + + assert isinstance(refused.value.__cause__, HouseholdCalculationStorageError) + + +@dataclass +class RecordingRerunService: + """The simulation service's client, recording each re-run it is sent.""" + + started: StartedReportRun + reruns: list[ReportRerunInput] = field(default_factory=list) + + def rerun_report(self, rerun: ReportRerunInput) -> StartedReportRun: + self.reruns.append(rerun) + return self.started + + +def _rerun(**changes: Any) -> ReportRerunInput: + values: dict[str, Any] = { + "country_id": "us", + "report_id": REPORT_ID, + "kind": "household", + "force": False, + "policy_ids": (None, STORED_POLICY_ID), + "variables": tuple(SUMMARY_VARIABLES), + } + return ReportRerunInput(**{**values, **changes}) + + +def test_a_household_reports_rerun_checks_its_variables_then_sends_them() -> None: + client = RecordingRerunService(StartedReportRun(report_run_id=REPORT_ID)) + variables = RunningCatalogVariables() + + _submissions(lambda: client, variables).rerun_report(_rerun()) + + assert variables.checked == [("us", tuple(SUMMARY_VARIABLES))] + assert client.reruns == [_rerun()] + + +def test_a_rerun_listing_unknown_variables_is_refused_by_name() -> None: + variables = RunningCatalogVariables() + + with pytest.raises(HouseholdCalculationVariablesUnknownError) as refused: + _submissions(unconfigured_client, variables).rerun_report( + _rerun(variables=("snap", "snep")) + ) + + assert refused.value.unknown_variables == ("snep",) + + +def test_a_rerun_without_a_list_checks_no_variables() -> None: + client = RecordingRerunService(StartedReportRun(report_run_id=REPORT_ID)) + variables = RunningCatalogVariables() + + _submissions(lambda: client, variables).rerun_report(_rerun(variables=None)) + + assert variables.checked == [] + assert len(client.reruns) == 1 + + +def test_a_household_reports_rerun_passes_on_the_variables_it_lists( + sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above +) -> None: + with sessions() as session: + stored = store_household_report(session, run=succeeded_run()) + assert stored.report_run_id is not None + client = RecordingRerunService(StartedReportRun(report_run_id=stored.report_run_id)) + reports = V2StoredReportService( + StoredReportDatabaseSession(sessions), + current_versions=current_versions, + submissions=client, + ) + + reports.rerun_report( + country_id="us", + report_id=stored.report_id, + force=False, + variables=["snap", "household_net_income"], + ) + reports.rerun_report(country_id="us", report_id=stored.report_id, force=False) + + assert [rerun.variables for rerun in client.reruns] == [ + ("snap", "household_net_income"), + None, + ] + + +def test_a_rerun_listing_variables_of_an_economy_report_is_refused_unsent( + sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above +) -> None: + # Imported here because the change these tests precede adds it. + from policyengine_api.services.v2.stored_reports.validators import ( + VariablesNotAvailableError, + ) + + with sessions() as session: + report_id = store_economy_report(session) + client = RecordingRerunService(StartedReportRun(report_run_id=REPORT_ID)) + reports = V2StoredReportService( + StoredReportDatabaseSession(sessions), + current_versions=current_versions, + submissions=client, + ) + + with pytest.raises(VariablesNotAvailableError) as refused: + reports.rerun_report( + country_id="us", report_id=report_id, force=False, variables=["snap"] + ) + + assert str(refused.value) == ( + "Only a household report lists the variables to calculate; this report " + "is an economy report" + ) + assert client.reruns == [] + + +def test_a_household_report_passes_on_the_variables_it_lists() -> None: + service = FakeReportService(report=household_report_read()) + + response = report_route_client(reports=service).post( + REPORTS, json=household_body(variables=SUMMARY_VARIABLES) + ) + + assert response.status_code == 201, response.text + ((name, arguments),) = service.calls + assert name == "create_report" + assert arguments["report_input"].variables == SUMMARY_VARIABLES + + +def test_a_household_report_of_the_longest_list_is_accepted() -> None: + service = FakeReportService(report=household_report_read()) + + response = report_route_client(reports=service).post( + REPORTS, json=household_body(variables=LONGEST_LIST) + ) + + assert response.status_code == 201, response.text + ((_, arguments),) = service.calls + assert arguments["report_input"].variables == LONGEST_LIST + + +def test_a_report_body_over_1_mib_is_refused() -> None: + service = FakeReportService(report=household_report_read()) + + response = report_route_client(reports=service).post( + REPORTS, json=household_body(padding="x" * ONE_MEBIBYTE) + ) + + assert response.status_code == 413 + assert service.calls == [] + + +def test_a_household_report_listing_unknown_variables_answers_422_naming_them() -> None: + service = FakeReportService( + error=HouseholdCalculationVariablesUnknownError(("removed_benefit", "snep")) + ) + + response = report_route_client(reports=service).post( + REPORTS, json=household_body(variables=["snap", "snep", "removed_benefit"]) + ) + + assert response.status_code == 422 + assert response.json() == UNKNOWN_VARIABLES_ANSWER + + +def test_running_a_household_report_again_passes_on_its_variables() -> None: + service = FakeReportRunService(report=household_report_read()) + + response = report_route_client(reports=service).post( + RUNS, json={"variables": SUMMARY_VARIABLES} + ) + + assert response.status_code == 201, response.text + assert service.calls == [ + ( + "rerun_report", + { + "country_id": "us", + "report_id": REPORT_ID, + "force": False, + "include_cliffs": False, + "variables": SUMMARY_VARIABLES, + }, + ) + ] + + +def test_a_rerun_of_the_longest_list_is_accepted() -> None: + service = FakeReportRunService(report=household_report_read()) + + response = report_route_client(reports=service).post( + RUNS, json={"variables": LONGEST_LIST} + ) + + assert response.status_code == 201, response.text + ((_, arguments),) = service.calls + assert arguments["variables"] == LONGEST_LIST + + +def test_a_rerun_listing_unknown_variables_answers_422_naming_them() -> None: + service = FakeReportRunService( + error=HouseholdCalculationVariablesUnknownError(("removed_benefit", "snep")) + ) + + response = report_route_client(reports=service).post( + RUNS, json={"variables": ["snap", "snep", "removed_benefit"]} + ) + + assert response.status_code == 422 + assert response.json() == UNKNOWN_VARIABLES_ANSWER + + +def test_a_rerun_listing_variables_of_a_report_that_takes_none_answers_422() -> None: + # Imported here because the change these tests precede adds it. + from policyengine_api.services.v2.stored_reports.validators import ( + VariablesNotAvailableError, + ) + + service = FakeReportRunService(error=VariablesNotAvailableError("budget_window")) + + response = report_route_client(reports=service).post( + RUNS, json={"variables": ["snap"]} + ) + + assert response.status_code == 422 + assert response.json() == { + "status": "error", + "message": ( + "Only a household report lists the variables to calculate; this " + "report is a budget window" + ), + } + + +def test_the_openapi_document_describes_the_list_its_limit_and_its_refusal() -> None: + document = report_route_client().get("/openapi.json").json() + schemas = document["components"]["schemas"] + create = document["paths"]["/v2/reports"]["post"]["responses"] + rerun = document["paths"]["/v2/reports/{report_id}/runs"]["post"]["responses"] + + for schema_name in ("HouseholdReportCreateRequest", "ReportRerunRequest"): + listed = schemas[schema_name]["properties"]["variables"] + (array,) = [option for option in listed["anyOf"] if option["type"] == "array"] + assert (array["minItems"], array["maxItems"]) == (1, MAXIMUM_LISTED_VARIABLES) + assert array["items"]["maxLength"] == MAXIMUM_VARIABLE_NAME_LENGTH + for responses in (create, rerun): + assert responses["413"]["description"] == "The request body exceeds 1 MiB." + refusals = responses["422"]["content"]["application/json"]["schema"] + assert {"$ref": "#/components/schemas/V2UnknownVariablesErrorResponse"} in ( + refusals["anyOf"] + ) + assert "unknown_variables" in responses["422"]["description"] diff --git a/tests/unit/v2/test_report_run_routes.py b/tests/unit/v2/test_report_run_routes.py index 0760fa244..482e8bc2f 100644 --- a/tests/unit/v2/test_report_run_routes.py +++ b/tests/unit/v2/test_report_run_routes.py @@ -248,6 +248,7 @@ def test_running_a_report_again_answers_the_report_with_its_new_run( "report_id": REPORT_ID, "force": force, "include_cliffs": False, + "variables": None, }, ) ] @@ -326,11 +327,11 @@ def test_a_rerun_needs_a_country() -> None: assert service.calls == [] -def test_a_rerun_body_over_16_kib_is_refused() -> None: +def test_a_rerun_body_over_1_mib_is_refused() -> None: service = FakeReportRunService() response = report_route_client(reports=service).post( - RUNS_PATH, json={"force": True, "padding": "x" * (17 * 1024)} + RUNS_PATH, json={"force": True, "padding": "x" * (1024 * 1024)} ) assert response.status_code == 413 From 123cce33a01b0f266faac108a189ca97c9367c3e Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 4 Dec 2026 01:59:16 +0400 Subject: [PATCH 02/12] Read the OpenAPI document from the path the app serves it at Co-Authored-By: Claude Opus 5.5 --- tests/unit/v2/test_household_report_variables.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/v2/test_household_report_variables.py b/tests/unit/v2/test_household_report_variables.py index 1d902fa4a..36157f390 100644 --- a/tests/unit/v2/test_household_report_variables.py +++ b/tests/unit/v2/test_household_report_variables.py @@ -605,7 +605,7 @@ def test_a_rerun_listing_variables_of_a_report_that_takes_none_answers_422() -> def test_the_openapi_document_describes_the_list_its_limit_and_its_refusal() -> None: - document = report_route_client().get("/openapi.json").json() + document = report_route_client().get("/v2/openapi.json").json() schemas = document["components"]["schemas"] create = document["paths"]["/v2/reports"]["post"]["responses"] rerun = document["paths"]["/v2/reports/{report_id}/runs"]["post"]["responses"] From 34475d3fefa7e2ed87a0dca5c0e2bc34b1ddf352 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 4 Dec 2026 02:05:30 +0400 Subject: [PATCH 03/12] Take a list of variables on household reports and their re-runs POST /v2/reports (kind household) and POST /v2/reports/{id}/runs take an optional variables list: 1 to 10,000 distinct names of 1 to 255 characters with no NUL character. Null or omitted calculates every variable, as before; an empty list is refused, because a run stores the list it calculated and stores none for every variable. Each name is checked against the running catalog version after the household, policies and dynamics, through the household calculation service's check, and unknown names answer 422 with code unknown_variables. A re-run listing variables for an economy report or budget window answers 422. The list is sent to the simulation service only when given. Both routes now take bodies of up to 1 MiB, so a list of 10,000 typical names fits. Co-Authored-By: Claude Opus 5.5 --- .../fastapi_routes/dependencies.py | 12 ++++ .../resource_service_protocols.py | 8 ++- .../v2/reports/response_models.py | 17 +++-- .../fastapi_routes/v2/reports/routes.py | 15 +++- .../fastapi_routes/v2/reports/run_models.py | 29 ++++++-- .../v2/simulation_resources_support.py | 12 +++- .../libs/simulation_report_reruns.py | 6 +- policyengine_api/libs/simulation_reports.py | 8 ++- .../v2/household_calculations/services.py | 19 +++-- .../v2/household_calculations/types.py | 47 ++++++++---- .../v2/simulation_service/services.py | 72 ++++++++++++++----- .../services/v2/simulation_service/types.py | 42 ++++++++--- .../services/v2/stored_reports/services.py | 10 ++- .../services/v2/stored_reports/validators.py | 33 +++++++++ tests/unit/v2/test_report_create_routes.py | 4 +- 15 files changed, 262 insertions(+), 72 deletions(-) diff --git a/policyengine_api/fastapi_routes/dependencies.py b/policyengine_api/fastapi_routes/dependencies.py index 6d69e581f..fad10700c 100644 --- a/policyengine_api/fastapi_routes/dependencies.py +++ b/policyengine_api/fastapi_routes/dependencies.py @@ -63,6 +63,9 @@ from policyengine_api.services.v2.associations.types import ( LegacyReferenceChecker, ) + from policyengine_api.services.v2.household_calculations.services import ( + V2HouseholdCalculationService, + ) from policyengine_api.services.v2.identity.types import ( AccountPrincipal, ) @@ -221,6 +224,14 @@ def _default_v2_household_service_factory() -> V2HouseholdResourceService: def _default_v2_household_calculation_service_factory() -> ( V2HouseholdCalculationResourceService ): + return _default_v2_household_calculation_service() + + +def _default_v2_household_calculation_service() -> V2HouseholdCalculationService: + """Build the household calculation service on the v2 database. + + Household report submissions check their variables through it too. + """ from policyengine_api.data.v2.database import ( get_v2_session_factory, ) @@ -272,6 +283,7 @@ def _default_simulation_submissions() -> SimulationServiceClient: households=_default_v2_household_service_factory(), policies=_default_v2_policy_service_factory(), dynamics=_default_v2_dynamic_service_factory(), + variables=_default_v2_household_calculation_service(), client_factory=process_simulation_service_client, ) diff --git a/policyengine_api/fastapi_routes/resource_service_protocols.py b/policyengine_api/fastapi_routes/resource_service_protocols.py index 009906c79..284291966 100644 --- a/policyengine_api/fastapi_routes/resource_service_protocols.py +++ b/policyengine_api/fastapi_routes/resource_service_protocols.py @@ -336,13 +336,14 @@ def create_report( """ ... - def rerun_report( + def rerun_report( # noqa: PLR0913 # the report, then each option the body gives self, *, country_id: str, report_id: UUID, force: bool, include_cliffs: bool = False, + variables: Sequence[str] | None = None, requester: AccountPrincipal | None = None, ) -> StoredReportRead: """Run the country's report again; return it with the run the request ended on. @@ -351,6 +352,11 @@ def rerun_report( With ``include_cliffs``, it also starts the cliff calculations an economy report run's simulation runs lack; ``CliffsNotAvailableError`` is raised, before anything is asked, for any other kind. + ``variables`` lists the variables a household report's new runs + calculate, None every variable; ``VariablesNotAvailableError`` is + raised, before anything is asked, for a list on any other kind, and + ``HouseholdCalculationVariablesUnknownError`` for names the running + catalog version lacks. With a ``requester``, the request is recorded for its user once the simulation service has answered, and ``StandardUserRequiresSignInError`` is raised, before anything is diff --git a/policyengine_api/fastapi_routes/v2/reports/response_models.py b/policyengine_api/fastapi_routes/v2/reports/response_models.py index 9ac394a02..ecace767e 100644 --- a/policyengine_api/fastapi_routes/v2/reports/response_models.py +++ b/policyengine_api/fastapi_routes/v2/reports/response_models.py @@ -11,6 +11,7 @@ from policyengine_api.fastapi_routes.v2.errors_support import ( V2ErrorResponse, V2MissingParametersErrorResponse, + V2UnknownVariablesErrorResponse, ) from policyengine_api.fastapi_routes.v2.household_calculations.response_models import ( HouseholdCalculationOutputItem, @@ -544,20 +545,26 @@ class ReportRunNotRecordedResponse(V2ErrorResponse): "A policy or dynamic the report names, or a household report's " "household, is not stored in the country." ), - 413: error_response("The request body exceeds 16 KiB."), + 413: error_response("The request body exceeds 1 MiB."), 422: { - "model": V2MissingParametersErrorResponse | V2ErrorResponse, + "model": V2MissingParametersErrorResponse + | V2UnknownVariablesErrorResponse + | V2ErrorResponse, "description": ( "The request does not match the schema (such as a budget window of " - "fewer than 1 or more than 75 years, or one ending after 2200); the " + "fewer than 1 or more than 75 years, or one ending after 2200, or " + "a household report's empty list of variables, or one naming a " + "variable twice); the " "country has no economy reports (such as a household-only country), " "for an economy report or budget window, or no household " "calculations, for a household report; a household " "report's household has no default year; a policy or dynamic the " "report names sets parameters the running catalog version does not " "have (code missing_parameters, which names them; the policies are " - "checked before the dynamics, the baseline's first); or the " - "simulation service cannot run the report: its " + "checked before the dynamics, the baseline's first); a household " + "report lists variables the running catalog version does not have " + "(code unknown_variables, which names them; checked after the " + "dynamics); or the simulation service cannot run the report: its " "422, or its 400 for a region, dynamic or dataset it does not have. The " "message says which; for the simulation service's refusal, it gives " "the service's code, when it gave one, and its reason, but not its " diff --git a/policyengine_api/fastapi_routes/v2/reports/routes.py b/policyengine_api/fastapi_routes/v2/reports/routes.py index 7d2bd2a1a..fed79ce88 100644 --- a/policyengine_api/fastapi_routes/v2/reports/routes.py +++ b/policyengine_api/fastapi_routes/v2/reports/routes.py @@ -110,11 +110,15 @@ ReportStorageError, RerunReportUnreadableError, StoredReportNotFoundError, + VariablesNotAvailableError, ) -MAXIMUM_REPORT_REQUEST_BYTES = 16 * 1024 +# A household report's list of variables holds up to 10,000 names: a list +# of that many names of 60 characters is about 615 KiB of JSON, within the +# limit, though one of that many 255-character names (about 2.5 MiB) is not. +MAXIMUM_REPORT_REQUEST_BYTES = 1024 * 1024 enforce_report_request_size = request_size_limit( - MAXIMUM_REPORT_REQUEST_BYTES, label="16 KiB" + MAXIMUM_REPORT_REQUEST_BYTES, label="1 MiB" ) ReportCreateQueryDependency = Annotated[ ReportCreateQuery, Depends(query_dependency(ReportCreateQuery)) @@ -136,6 +140,7 @@ BudgetWindowYearNotFoundError, ForcedRerunRequiresAdminError, CliffsNotAvailableError, + VariablesNotAvailableError, NotABudgetWindowError, *SUBMISSION_REFUSALS, ) @@ -149,7 +154,10 @@ 404, ), V2ErrorMapping((ForcedRerunRequiresAdminError,), 403), - V2ErrorMapping((CliffsNotAvailableError, NotABudgetWindowError), 422), + V2ErrorMapping( + (CliffsNotAvailableError, VariablesNotAvailableError, NotABudgetWindowError), + 422, + ), *SUBMISSION_ERROR_MAPPINGS, V2ErrorMapping( ( @@ -386,6 +394,7 @@ def _rerun_report( report_id=report_id, force=body.force, include_cliffs=body.include_cliffs, + variables=body.variables, requester=requester, ) except (StandardUserRequiresSignInError, ForcedRerunRequiresSignInError) as error: diff --git a/policyengine_api/fastapi_routes/v2/reports/run_models.py b/policyengine_api/fastapi_routes/v2/reports/run_models.py index 700436df9..513eba3dd 100644 --- a/policyengine_api/fastapi_routes/v2/reports/run_models.py +++ b/policyengine_api/fastapi_routes/v2/reports/run_models.py @@ -10,6 +10,7 @@ from policyengine_api.fastapi_routes.v2.errors_support import ( V2ErrorResponse, V2MissingParametersErrorResponse, + V2UnknownVariablesErrorResponse, ) from policyengine_api.fastapi_routes.v2.reports.response_models import ( MACHINE_REQUESTER, @@ -25,6 +26,9 @@ from policyengine_api.fastapi_routes.v2.simulation_resources_support import ( error_response, ) +from policyengine_api.services.v2.household_calculations.types import ( + NonEmptyVariableNames, +) from policyengine_api.services.v2.simulation_service.types import ( StrictSubmissionModel, ) @@ -51,11 +55,16 @@ class ReportRerunRequest(StrictSubmissionModel): economy report has cliffs: a household report or budget window asking for them is refused with 422. A simulation service that doesn't calculate cliffs per simulation run refuses ``include_cliffs: true`` with - 422 and starts no run. + 422 and starts no run. ``variables`` lists the variables a household + report's new runs calculate, as a new household report lists them: 1 to + 10,000 distinct names of 1 to 255 characters, each a variable of the + running catalog version. Null, or omitted, calculates every variable. + Any other report listing variables is refused with 422. """ force: StrictBool = False include_cliffs: StrictBool = False + variables: NonEmptyVariableNames | None = None class ReportRunListResult(StrictReportAPIModel): @@ -182,15 +191,21 @@ class RerunReportUnreadableResponse(V2ErrorResponse): "(rerun_not_supported)." ), }, - 413: error_response("The request body exceeds 16 KiB."), + 413: error_response("The request body exceeds 1 MiB."), 422: { - "model": V2MissingParametersErrorResponse | V2ErrorResponse, + "model": V2MissingParametersErrorResponse + | V2UnknownVariablesErrorResponse + | V2ErrorResponse, "description": ( - "The request does not match the schema; a household report or " + "The request does not match the schema (such as an empty list of " + "variables, or one naming a variable twice); a household report or " "budget window asks for cliffs (include_cliffs), which only an " - "economy report has; a simulation service that doesn't calculate " - "cliffs per simulation run refuses include_cliffs: true; the country " - "has no economy " + "economy report has; an economy report or budget window lists " + "variables, which only a household report takes; a household " + "report lists variables the running catalog version does not have " + "(code unknown_variables, which names them); a simulation service " + "that doesn't calculate cliffs per simulation run refuses " + "include_cliffs: true; the country has no economy " "reports, or no household calculations for a household report; a " "policy of the report's simulations sets " "parameters the running catalog version does not have (code " diff --git a/policyengine_api/fastapi_routes/v2/simulation_resources_support.py b/policyengine_api/fastapi_routes/v2/simulation_resources_support.py index 36e517939..43f91f763 100644 --- a/policyengine_api/fastapi_routes/v2/simulation_resources_support.py +++ b/policyengine_api/fastapi_routes/v2/simulation_resources_support.py @@ -21,10 +21,12 @@ V2ErrorResponse, run_v2_operation, v2_missing_parameters_response, + v2_unknown_variables_response, ) from policyengine_api.services.v2.dynamics.validators import DynamicNotFoundError from policyengine_api.services.v2.household_calculations.validators import ( HouseholdCalculationCountryError, + HouseholdCalculationVariablesUnknownError, HouseholdCalculationYearError, ) from policyengine_api.services.v2.households.validators import HouseholdNotFoundError @@ -159,9 +161,11 @@ def simulation_resource_operation( """Run one service call and answer its failure with a typed v2 error. A policy or dynamic that sets parameters the running catalog version - lacks answers 422 with code ``missing_parameters``, naming them, whatever - the route. A failure of a type in ``refusals`` is the caller's to act on - and is not logged, nor is that 422; any other is logged under ``event``. + lacks answers 422 with code ``missing_parameters``, naming them, and a + household report listing variables it lacks answers 422 with code + ``unknown_variables``, naming those, whatever the route. A failure of a + type in ``refusals`` is the caller's to act on and is not logged, nor is + either 422; any other is logged under ``event``. """ def logged() -> OperationT | JSONResponse: @@ -169,6 +173,8 @@ def logged() -> OperationT | JSONResponse: return operation() except PolicyParametersMissingError as error: return v2_missing_parameters_response(str(error), error.missing_parameters) + except HouseholdCalculationVariablesUnknownError as error: + return v2_unknown_variables_response(str(error), error.unknown_variables) except Exception as error: if not isinstance(error, refusals): _log_failure(event, error) diff --git a/policyengine_api/libs/simulation_report_reruns.py b/policyengine_api/libs/simulation_report_reruns.py index bec260efb..2951939ef 100644 --- a/policyengine_api/libs/simulation_report_reruns.py +++ b/policyengine_api/libs/simulation_report_reruns.py @@ -147,11 +147,15 @@ def report_rerun_request(rerun: ReportRerunInput) -> dict[str, Any]: ``include_cliffs`` is sent only when true: a simulation service that doesn't calculate cliffs per simulation run refuses the field, so a - re-run that doesn't ask for cliffs isn't refused for it. + re-run that doesn't ask for cliffs isn't refused for it. ``variables`` + is sent only for a household report's re-run that lists them, for the + same reason. """ body: dict[str, Any] = {"force": rerun.force} if rerun.include_cliffs: body["include_cliffs"] = True + if rerun.variables is not None: + body["variables"] = list(rerun.variables) return body diff --git a/policyengine_api/libs/simulation_reports.py b/policyengine_api/libs/simulation_reports.py index 496e74e25..198bb0b00 100644 --- a/policyengine_api/libs/simulation_reports.py +++ b/policyengine_api/libs/simulation_reports.py @@ -299,9 +299,10 @@ def household_report_request(report: HouseholdReportCreationInput) -> dict[str, """Return the simulation service's request body for the household report. ``reform`` is null for a report of the baseline alone. Each side names - its dynamic only when it has one. + its dynamic only when it has one. ``variables`` is sent only for a + report that lists them; without it each side calculates every variable. """ - return { + body: dict[str, Any] = { "country": report.country_id, "report_type": report.kind, "household_id": str(report.household_id), @@ -310,6 +311,9 @@ def household_report_request(report: HouseholdReportCreationInput) -> dict[str, None if report.reform is None else _household_policy_choice(report.reform) ), } + if report.variables is not None: + body["variables"] = list(report.variables) + return body def _refusal(answer: SimulationAnswer) -> _Refusal | None: diff --git a/policyengine_api/services/v2/household_calculations/services.py b/policyengine_api/services/v2/household_calculations/services.py index e6d8be53b..eaa769e17 100644 --- a/policyengine_api/services/v2/household_calculations/services.py +++ b/policyengine_api/services/v2/household_calculations/services.py @@ -85,7 +85,7 @@ ) if TYPE_CHECKING: - from collections.abc import Callable, Iterator + from collections.abc import Callable, Iterator, Sequence from uuid import UUID from policyengine_api.services.v2.household_calculations.database_session import ( @@ -185,7 +185,9 @@ def _submit_inline_calculation( ) ) require_inline_policy_parameters_present(missing_parameters) - self._require_known_variables(country_id, calculation.variables) + self.require_known_variables( + country_id=country_id, variables=calculation.variables + ) accepted = self._simulation_factory().submit(calculation) return household_calculation_submitted( calculation, accepted, year=calculation.year @@ -224,18 +226,23 @@ def _submit_stored_calculation( country_id=country_id, dynamic_ids=(calculation.dynamic_id,), ) - self._require_known_variables(country_id, calculation.variables) + self.require_known_variables( + country_id=country_id, variables=calculation.variables + ) accepted = self._simulation_factory().submit(calculation) return household_calculation_submitted(calculation, accepted, year=year) - def _require_known_variables( - self, country_id: str, variables: list[str] | None + def require_known_variables( + self, *, country_id: str, variables: Sequence[str] | None ) -> None: """Raise HouseholdCalculationVariablesUnknownError for unknown listed names. The names are checked against the running catalog version; nothing is read for a calculation listing none, and nothing is checked when the - running .py version has no published catalog for the country. + running .py version has no published catalog for the country. A + household report's submission checks its list through this method + too. HouseholdCalculationStorageError means the database or catalog + could not be read. """ if not variables: return diff --git a/policyengine_api/services/v2/household_calculations/types.py b/policyengine_api/services/v2/household_calculations/types.py index e57d12fe4..3e16abd43 100644 --- a/policyengine_api/services/v2/household_calculations/types.py +++ b/policyengine_api/services/v2/household_calculations/types.py @@ -9,6 +9,7 @@ from uuid import UUID from pydantic import ( + AfterValidator, BaseModel, ConfigDict, Field, @@ -45,6 +46,36 @@ # contract takes variable names. ListedVariableName = Annotated[str, Field(min_length=1, max_length=255)] + +def require_usable_variable_names(variables: list[str]) -> list[str]: + """Refuse a list naming a variable with a NUL character, or one twice. + + PostgreSQL text can't hold a NUL character, so no catalog variable has + such a name, and the catalog query would fail on it. The simulation + service refuses a list naming one variable twice. + """ + if any("\x00" in name for name in variables): + msg = "variables can't name a variable with a NUL character" + raise ValueError(msg) + repeated = sorted(name for name, count in Counter(variables).items() if count > 1) + if repeated: + msg = f"variables names {', '.join(repeated)} more than once" + raise ValueError(msg) + return variables + + +# The variables a household report's run, or an extra calculation of one, +# calculates: 1 to MAXIMUM_LISTED_VARIABLES distinct names, as +# /v2/household-calculations takes them except that the list can't be +# empty. household_run_variables and household_run_calculations store each +# list and refuse an empty one; a run with no list calculates every +# variable. +NonEmptyVariableNames = Annotated[ + list[ListedVariableName], + Field(min_length=1, max_length=MAXIMUM_LISTED_VARIABLES), + AfterValidator(require_usable_variable_names), +] + # A household job's status, as household_jobs stores it: the simulation # service inserts the job pending, its household function sets it running, # then succeeded or failed. @@ -159,9 +190,8 @@ def refuse_repeated_or_redundant_variables( ``add_missing_variables`` calculates every variable, which a list would contradict, as the simulation service refuses it. A name - holding a NUL character is refused too: PostgreSQL text can't hold - one, so no catalog variable has such a name, and the catalog query - would fail on it. + holding a NUL character is refused too, as + ``require_usable_variable_names`` says. """ if variables is None: return None @@ -171,16 +201,7 @@ def refuse_repeated_or_redundant_variables( "which calculates every variable" ) raise ValueError(msg) - if any("\x00" in name for name in variables): - msg = "variables can't name a variable with a NUL character" - raise ValueError(msg) - repeated = sorted( - name for name, count in Counter(variables).items() if count > 1 - ) - if repeated: - msg = f"variables names {', '.join(repeated)} more than once" - raise ValueError(msg) - return variables + return require_usable_variable_names(variables) @field_validator("spm", mode="before") @classmethod diff --git a/policyengine_api/services/v2/simulation_service/services.py b/policyengine_api/services/v2/simulation_service/services.py index 40a777d56..902253e36 100644 --- a/policyengine_api/services/v2/simulation_service/services.py +++ b/policyengine_api/services/v2/simulation_service/services.py @@ -21,14 +21,17 @@ and the household it names must be stored in the country, through the same service as ``/v2/households``, with a default year, which the report calculates; the household is checked before the policies, and the policies -before the dynamics. These are the checks ``/v2/household-calculations`` -makes, with the same errors. +before the dynamics. Last, every variable the report lists must be a +variable of the running catalog version, unless that version has no +published catalog for the country. These are the checks +``/v2/household-calculations`` makes, with the same errors. Running a stored report again (``POST /reports/{report_id}/runs``) checks its country as a new report of its kind is checked, then the policies its -simulations name. Its dynamics are not checked again: each was checked to be -the country's when the report was created, and the simulation service refuses -a re-run whose dynamic sets parameters its catalog version lacks. +simulations name, then the variables a household report's re-run lists. +Its dynamics are not checked again: each was checked to be the country's +when the report was created, and the simulation service refuses a re-run +whose dynamic sets parameters its catalog version lacks. """ from __future__ import annotations @@ -46,6 +49,7 @@ require_dynamic_parameters_present, ) from policyengine_api.services.v2.household_calculations.validators import ( + HouseholdCalculationStorageError, require_default_year, require_household_country, ) @@ -58,7 +62,7 @@ ) if TYPE_CHECKING: - from collections.abc import Callable, Iterable, Iterator + from collections.abc import Callable, Iterable, Iterator, Sequence from uuid import UUID from policyengine_api.services.v2.countries.types import CountryRead @@ -80,6 +84,7 @@ SubmittedBudgetWindow, SubmittedReport, SubmittedSimulation, + VariableSource, ) # A check of a country's row, raising unless it allows a kind of calculation. @@ -91,8 +96,9 @@ def _storage_failures() -> Iterator[None]: """Raise SubmissionStorageError for a read that failed. That includes the policy and dynamic checks' catalog query, which their - services report as MetadataCatalogUnavailableError, and the dynamic - service's DynamicStorageError. + services report as MetadataCatalogUnavailableError, the dynamic + service's DynamicStorageError, and the variable check's + HouseholdCalculationStorageError. """ try: yield @@ -100,6 +106,7 @@ def _storage_failures() -> Iterator[None]: SQLAlchemyError, MetadataCatalogUnavailableError, DynamicStorageError, + HouseholdCalculationStorageError, ) as error: msg = "V2 storage is unavailable to check the submission" raise SubmissionStorageError(msg) from error @@ -154,7 +161,7 @@ def require_runnable_dynamics( class SimulationSubmissionService: """Check submissions, then send them to the simulation service.""" - def __init__( + def __init__( # noqa: PLR0913 # each source a check reads, then the client self, *, countries: CountrySource, @@ -162,20 +169,41 @@ def __init__( policies: PolicySource, dynamics: DynamicSource, client_factory: Callable[[], SimulationServiceClient], + variables: VariableSource | None = None, ) -> None: """Check through these sources; send through ``client_factory``'s client. - ``households`` is read only for a household report, and ``dynamics`` - only for a submission that names a dynamic. The client is built only - once a submission passes the checks, so a refused submission gets its - own answer even when the simulation service is not configured. + ``households`` is read only for a household report, ``dynamics`` + only for a submission that names a dynamic, and ``variables`` only + for a household report or re-run that lists variables; without + ``variables`` the names a list holds are sent unchecked. The client + is built only once a submission passes the checks, so a refused + submission gets its own answer even when the simulation service is + not configured. """ self._countries = countries self._households = households self._policies = policies self._dynamics = dynamics + self._variables = variables self._client_factory = client_factory + def _require_known_variables( + self, country_id: str, variables: Sequence[str] | None + ) -> None: + """Raise for listed names the running catalog version doesn't have. + + Raise HouseholdCalculationVariablesUnknownError naming them, and + SubmissionStorageError when the catalog cannot be read. Nothing is + read for no list, or without a variable source. + """ + if variables is None or self._variables is None: + return + with _storage_failures(): + self._variables.require_known_variables( + country_id=country_id, variables=variables + ) + def _check( self, country_id: str, @@ -239,9 +267,11 @@ def submit_household_report( HouseholdCalculationYearError for one with no default year, then the policy checks' errors, then the dynamic checks' errors (in each, the baseline's first, and only the baseline's for a report of the - baseline alone), SubmissionStorageError when the database or its - catalog cannot be read, and then the simulation service's errors. - Each side keeps its own dynamic: nothing requires the two to match. + baseline alone), then HouseholdCalculationVariablesUnknownError + naming the listed variables the running catalog version lacks, + SubmissionStorageError when the database or its catalog cannot be + read, and then the simulation service's errors. Each side keeps its + own dynamic: nothing requires the two to match. """ country_id = report.country_id with _storage_failures(): @@ -263,6 +293,7 @@ def submit_household_report( country_id=country_id, dynamic_ids=[side.dynamic_id for side in sides], ) + self._require_known_variables(country_id, report.variables) return self._client_factory().submit_household_report(report) def submit_budget_window( @@ -292,15 +323,18 @@ def rerun_report(self, rerun: ReportRerunInput) -> StartedReportRun: household report's country must allow household calculations (raise HouseholdCalculationCountryError otherwise); its household is not read again, since it stays stored while a report names it. Any other - report's country must allow economy calculations. Raise the checks' - errors, SubmissionStorageError when the database or its catalog - cannot be read, then the simulation service's errors. + report's country must allow economy calculations. The variables a + household report's re-run lists are checked last, as a new household + report's are. Raise the checks' errors, SubmissionStorageError when + the database or its catalog cannot be read, then the simulation + service's errors. """ self._check( rerun.country_id, rerun.policy_ids, require_country=_country_check(rerun.kind), ) + self._require_known_variables(rerun.country_id, rerun.variables) return self._client_factory().rerun_report(rerun) diff --git a/policyengine_api/services/v2/simulation_service/types.py b/policyengine_api/services/v2/simulation_service/types.py index 2cf40112e..dbe6ddd7d 100644 --- a/policyengine_api/services/v2/simulation_service/types.py +++ b/policyengine_api/services/v2/simulation_service/types.py @@ -36,9 +36,13 @@ from policyengine_api.data.v2.models.reports import LAST_YEAR, MAX_BUDGET_WINDOW_YEARS from policyengine_api.query_parameters import CountryId, ResourceId +from policyengine_api.services.v2.household_calculations.types import ( + NonEmptyVariableNames, +) from policyengine_api.spm import SPMSelection if TYPE_CHECKING: + from collections.abc import Sequence from uuid import UUID from policyengine_api.services.v2.countries.types import CountryRead @@ -321,13 +325,16 @@ class HouseholdReportFields(StrictSubmissionModel): year, the year its values name, as a household calculation does. ``reform`` is null, or omitted, for a report of the baseline alone. Each side names its own policy and dynamic, and nothing requires the two - sides' dynamics to match, as for an economy report. Each - simulation calculates every yearly, monthly and eternal variable the - household lacks, as ``/calculate-full`` does, so the report gives every - value; there is no option to fill in only the values the household asks - for, as ``/v2/household-calculations`` has. ``label`` and - ``description`` are optional and stored nowhere, as for an economy - report. + sides' dynamics to match, as for an economy report. ``variables`` + lists the variables each side's run calculates: 1 to 10,000 distinct + names of 1 to 255 characters with no NUL character, each a variable of + the running catalog version unless that version has no published + catalog for the country. Null, or omitted, calculates every yearly, + monthly and eternal variable the household lacks, as ``/calculate-full`` + does; an empty list is refused, because a run records the list it + calculated and stores none for every variable. A request that joins a + run already stored keeps that run's list. ``label`` and ``description`` + are optional and stored nowhere, as for an economy report. """ kind: Literal["household"] @@ -340,6 +347,7 @@ class HouseholdReportFields(StrictSubmissionModel): household_id: ResourceId baseline: HouseholdPolicyChoice reform: HouseholdPolicyChoice | None = None + variables: NonEmptyVariableNames | None = None class HouseholdReportCreationInput(HouseholdReportFields): @@ -447,7 +455,10 @@ class ReportRerunInput: report, asks the service to start a cliff calculation for each side's simulation run that has none, or whose newest one failed; it is sent only when true, and a service that doesn't calculate cliffs per - simulation run refuses it. + simulation run refuses it. ``variables``, only for a household report, + lists the variables each new run calculates, checked against the + running catalog version; None calculates every variable and is not + sent. """ country_id: str @@ -456,6 +467,7 @@ class ReportRerunInput: force: bool policy_ids: tuple[UUID | None, ...] include_cliffs: bool = False + variables: tuple[str, ...] | None = None class SimulationServiceClient(Protocol): @@ -557,3 +569,17 @@ class DynamicSource(Protocol): def get_dynamic(self, *, country_id: str, dynamic_id: UUID) -> CheckedDynamicRead: """Return the country's dynamic, or raise ``DynamicNotFoundError``.""" ... + + +class VariableSource(Protocol): + """The running catalog version's variables, which a household report lists.""" + + def require_known_variables( + self, *, country_id: str, variables: Sequence[str] | None + ) -> None: + """Raise for listed names the running catalog version doesn't have. + + Raise ``HouseholdCalculationVariablesUnknownError`` naming them, or + ``HouseholdCalculationStorageError`` when the catalog cannot be read. + """ + ... diff --git a/policyengine_api/services/v2/stored_reports/services.py b/policyengine_api/services/v2/stored_reports/services.py index 95f50e066..ced5064de 100644 --- a/policyengine_api/services/v2/stored_reports/services.py +++ b/policyengine_api/services/v2/stored_reports/services.py @@ -136,6 +136,7 @@ require_reform_run, require_report, require_report_run, + require_variables_available, require_window_year_run, ) @@ -660,13 +661,14 @@ def create_report( country_id=report_input.country_id, ) from error - def rerun_report( + def rerun_report( # noqa: PLR0913 # the report, then each option the body gives self, *, country_id: str, report_id: UUID, force: bool, include_cliffs: bool = False, + variables: Sequence[str] | None = None, requester: AccountPrincipal | None = None, ) -> StoredReportRead: """Run the country's report again; return it with the run the request ended on. @@ -679,7 +681,8 @@ def rerun_report( window's new run then recalculates each year). A household report's sides are always calculated again. Only an admin user may force a re-run; ``include_cliffs`` asks for an economy report run's cliffs - too. With a ``requester``, it is + too, and ``variables`` lists the variables a household report's new + runs calculate (None: every variable). With a ``requester``, it is checked before the simulation service is asked, and the request is recorded for its user (trigger ``manual``, forced or not) once the service has answered: that run, or each year's report run of a budget @@ -687,6 +690,7 @@ def rerun_report( report, ForcedRerunRequiresSignInError for a forced re-run naming no user, ForcedRerunRequiresAdminError for one by a user below admin and CliffsNotAvailableError for a household report's or window's cliffs, + VariablesNotAvailableError for another report's list of variables, each before the simulation service is asked, ReportStorageError when it cannot be read, the recorder's check's errors, the submission's checks' and the simulation service's errors @@ -705,6 +709,7 @@ def rerun_report( if force: require_admin_to_force(None if recording is None else recording.requester) require_cliffs_available(kind, include_cliffs=include_cliffs) + require_variables_available(kind, variables) started = submissions.rerun_report( ReportRerunInput( country_id=country_id, @@ -713,6 +718,7 @@ def rerun_report( force=force, policy_ids=report_policy_ids(stored), include_cliffs=include_cliffs, + variables=None if variables is None else tuple(variables), ) ) if kind != "budget_window": diff --git a/policyengine_api/services/v2/stored_reports/validators.py b/policyengine_api/services/v2/stored_reports/validators.py index 1d17b118a..d1a51b852 100644 --- a/policyengine_api/services/v2/stored_reports/validators.py +++ b/policyengine_api/services/v2/stored_reports/validators.py @@ -87,6 +87,39 @@ class CliffsNotAvailableError(ValueError): """ +# How a refusal names each kind of report. +_REPORT_KIND_NAMES: dict[ReportKind, str] = { + "economy": "an economy report", + "household": "a household report", + "budget_window": "a budget window", +} + + +class VariablesNotAvailableError(ValueError): + """A re-run listed variables to calculate for a report that takes no list. + + Only a household report's simulation runs calculate a household, so only + its re-run may list the variables to calculate: an economy report's and a + budget window's calculate a region's data. + """ + + def __init__(self, kind: ReportKind) -> None: + """Name the report's kind, ``kind``, in the message.""" + super().__init__( + "Only a household report lists the variables to calculate; this " + f"report is {_REPORT_KIND_NAMES[kind]}" + ) + self.kind = kind + + +def require_variables_available( + kind: ReportKind, variables: Sequence[str] | None +) -> None: + """Raise VariablesNotAvailableError when a re-run of a ``kind`` lists variables.""" + if variables is not None and kind != "household": + raise VariablesNotAvailableError(kind) + + def require_budget_window_year(report: Report, *, kind: ReportKind, year: int) -> None: """Allow a read of ``year`` of the report only for a year of its budget window. diff --git a/tests/unit/v2/test_report_create_routes.py b/tests/unit/v2/test_report_create_routes.py index ba9cd6ca6..335aa99ea 100644 --- a/tests/unit/v2/test_report_create_routes.py +++ b/tests/unit/v2/test_report_create_routes.py @@ -177,12 +177,12 @@ def test_a_malformed_report_is_refused_before_the_service( assert service.calls == [] -def test_a_report_body_over_16_kib_is_refused() -> None: +def test_a_report_body_over_1_mib_is_refused() -> None: service = FakeReportService() response = report_route_client(reports=service).post( "/v2/reports?country_id=us", - json=report_body(description="x" * (17 * 1024)), + json=report_body(description="x" * (1024 * 1024)), ) assert response.status_code == 413 From 575bea73ab50fb5da2b4072c39b4db2549124de9 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 4 Dec 2026 02:10:46 +0400 Subject: [PATCH 04/12] Add tests for reading household runs' variables and extra calculations, which fail before the change The household report read gives calculated_variables: each side's listed variables from household_run_variables, null for a side that calculated every variable, and null with no run. GET /v2/household-run-calculations/{calculation_id} reads one extra calculation of a household report's run: its status, variables, axes, calculated household or error message; another country's is not found. Co-Authored-By: Claude Opus 5.5 --- ...t_household_report_calculated_variables.py | 233 ++++++++++ .../test_household_run_calculation_reads.py | 412 ++++++++++++++++++ tests/unit/v2/test_metadata_routes.py | 1 + 3 files changed, 646 insertions(+) create mode 100644 tests/unit/v2/test_household_report_calculated_variables.py create mode 100644 tests/unit/v2/test_household_run_calculation_reads.py diff --git a/tests/unit/v2/test_household_report_calculated_variables.py b/tests/unit/v2/test_household_report_calculated_variables.py new file mode 100644 index 000000000..4c3e4cd16 --- /dev/null +++ b/tests/unit/v2/test_household_report_calculated_variables.py @@ -0,0 +1,233 @@ +"""A household report's read names the variables each side's run calculated. + +A household report's request may list the variables its runs calculate. The +simulation service records each list, sorted, in ``household_run_variables`` +for each side's simulation run; a run with no row calculated every variable, +as every run did before lists existed. Reading a household report gives +``calculated_variables``: each side's list, null for a side that calculated +every variable, and null as a whole for a report with no run. App v3 +compares it with the variables its views read and asks for any others as an +extra calculation. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from policyengine_api.data.v2.models import ( + HouseholdRunVariables, + ReportRunStatus, +) +from tests.unit.v2.stored_report_support import ( + REPORT_ID, + FakeReportService, + report_route_client, +) +from tests.unit.v2.test_household_report_reads import ( + RunToStore, + reports, # noqa: F401 # the fixture the service tests use + sessions, # noqa: F401 # the fixture the service tests use + store_household_report, + succeeded_run, +) +from tests.unit.v2.test_household_report_routes import household_report_read + +if TYPE_CHECKING: + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + from policyengine_api.services.v2.stored_reports.services import ( + V2StoredReportService, + ) + from tests.unit.v2.test_household_report_reads import StoredHouseholdReport + +SUMMARY_VARIABLES = ["employment_income", "household_net_income", "snap"] +REFORM_VARIABLES = ["household_net_income", "snap"] + + +def _record_variables( + session: Session, stored: StoredHouseholdReport, *, side: str, variables: list[str] +) -> None: + """Record the variables one side's run calculated, as the service records them.""" + run_id = stored.baseline_run_id if side == "baseline" else stored.reform_run_id + simulation_id = ( + stored.baseline_simulation_id + if side == "baseline" + else stored.reform_simulation_id + ) + assert run_id is not None + assert simulation_id is not None + session.add( + HouseholdRunVariables( + simulation_run_id=run_id, simulation_id=simulation_id, variables=variables + ) + ) + session.commit() + + +def _calculated_variables(read: object) -> Any: + calculated = getattr(read, "calculated_variables", "absent") + if calculated is None or calculated == "absent": + return calculated + return {"baseline": calculated.baseline, "reform": calculated.reform} + + +def test_a_household_report_reads_each_sides_listed_variables( + sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above + reports: V2StoredReportService, # noqa: F811 # the fixture imported above +) -> None: + with sessions() as session: + stored = store_household_report(session, run=succeeded_run()) + _record_variables(session, stored, side="baseline", variables=SUMMARY_VARIABLES) + _record_variables(session, stored, side="reform", variables=REFORM_VARIABLES) + + read = reports.get_report(country_id="us", report_id=stored.report_id) + + assert _calculated_variables(read) == { + "baseline": tuple(SUMMARY_VARIABLES), + "reform": tuple(REFORM_VARIABLES), + } + + +def test_a_side_whose_run_lists_no_variables_calculated_every_variable( + sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above + reports: V2StoredReportService, # noqa: F811 # the fixture imported above +) -> None: + with sessions() as session: + stored = store_household_report(session, run=succeeded_run()) + _record_variables(session, stored, side="baseline", variables=SUMMARY_VARIABLES) + + read = reports.get_report(country_id="us", report_id=stored.report_id) + + assert _calculated_variables(read) == { + "baseline": tuple(SUMMARY_VARIABLES), + "reform": None, + } + + +def test_a_report_stored_before_lists_existed_calculated_every_variable( + sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above + reports: V2StoredReportService, # noqa: F811 # the fixture imported above +) -> None: + with sessions() as session: + stored = store_household_report(session, run=succeeded_run()) + + read = reports.get_report(country_id="us", report_id=stored.report_id) + + assert _calculated_variables(read) == {"baseline": None, "reform": None} + + +def test_a_report_of_the_baseline_alone_has_no_reform_variables( + sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above + reports: V2StoredReportService, # noqa: F811 # the fixture imported above +) -> None: + with sessions() as session: + stored = store_household_report( + session, with_reform=False, run=succeeded_run(reform_result=None) + ) + _record_variables(session, stored, side="baseline", variables=SUMMARY_VARIABLES) + + read = reports.get_report(country_id="us", report_id=stored.report_id) + + assert _calculated_variables(read) == { + "baseline": tuple(SUMMARY_VARIABLES), + "reform": None, + } + + +def test_an_unfinished_run_names_the_variables_it_will_calculate( + sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above + reports: V2StoredReportService, # noqa: F811 # the fixture imported above +) -> None: + with sessions() as session: + stored = store_household_report( + session, run=RunToStore(status=ReportRunStatus.RUNNING) + ) + _record_variables(session, stored, side="baseline", variables=SUMMARY_VARIABLES) + _record_variables(session, stored, side="reform", variables=REFORM_VARIABLES) + + read = reports.get_report(country_id="us", report_id=stored.report_id) + + assert _calculated_variables(read) == { + "baseline": tuple(SUMMARY_VARIABLES), + "reform": tuple(REFORM_VARIABLES), + } + + +def test_a_report_with_no_run_names_no_calculated_variables( + sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above + reports: V2StoredReportService, # noqa: F811 # the fixture imported above +) -> None: + with sessions() as session: + stored = store_household_report(session, run=None) + + read = reports.get_report(country_id="us", report_id=stored.report_id) + + assert _calculated_variables(read) is None + + +def _calculated(baseline: list[str] | None, reform: list[str] | None) -> Any: + # Imported here because the change these tests precede adds it. + from policyengine_api.services.v2.stored_reports.household_results.types import ( + CalculatedVariables, + ) + + return CalculatedVariables( + baseline=None if baseline is None else tuple(baseline), + reform=None if reform is None else tuple(reform), + ) + + +def _read_item(**changes: Any) -> dict[str, Any]: + service = FakeReportService(report=household_report_read(**changes)) + response = report_route_client(reports=service).get( + f"/v2/reports/{REPORT_ID}?country_id=us" + ) + assert response.status_code == 200, response.text + return response.json()["result"]["item"] + + +def test_the_report_read_answers_each_sides_calculated_variables() -> None: + item = _read_item( + calculated_variables=_calculated(SUMMARY_VARIABLES, REFORM_VARIABLES) + ) + + assert item.get("calculated_variables", "absent") == { + "baseline": SUMMARY_VARIABLES, + "reform": REFORM_VARIABLES, + } + + +def test_a_side_that_calculated_every_variable_answers_null() -> None: + item = _read_item(calculated_variables=_calculated(None, REFORM_VARIABLES)) + + assert item.get("calculated_variables", "absent") == { + "baseline": None, + "reform": REFORM_VARIABLES, + } + + +def test_a_report_with_no_run_answers_null_calculated_variables() -> None: + item = _read_item(calculated_variables=None, run=None, status="pending") + + assert item.get("calculated_variables", "absent") is None + + +def test_the_openapi_document_describes_the_calculated_variables() -> None: + document = report_route_client().get("/v2/openapi.json").json() + schemas = document["components"]["schemas"] + + item = schemas["HouseholdReportItem"] + assert "calculated_variables" in item.get("required", []) + options = item["properties"]["calculated_variables"]["anyOf"] + (reference,) = [option["$ref"] for option in options if "$ref" in option] + sides = schemas[reference.rsplit("/", 1)[-1]] + assert set(sides["properties"]) == {"baseline", "reform"} + assert set(sides["required"]) == {"baseline", "reform"} + for side in ("baseline", "reform"): + (listed,) = [ + option + for option in sides["properties"][side]["anyOf"] + if option.get("type") == "array" + ] + assert listed["items"]["type"] == "string" diff --git a/tests/unit/v2/test_household_run_calculation_reads.py b/tests/unit/v2/test_household_run_calculation_reads.py new file mode 100644 index 000000000..e6d43bb45 --- /dev/null +++ b/tests/unit/v2/test_household_run_calculation_reads.py @@ -0,0 +1,412 @@ +"""Read an extra calculation of a household report's run. + +A household report's other views ask for more than its run calculated, such +as ``marginal_tax_rate`` or an earnings variation: each is an extra +calculation of one side's simulation run, a row of +``household_run_calculations``, which the simulation service inserts and its +household function completes. ``GET +/v2/household-run-calculations/{calculation_id}?country_id=`` reads one, for +following it until it finishes: its status, the variables and axes it +calculates, the calculated household once it has succeeded, and the error +message once it has failed. A calculation of another country's run is not +found. The read never calls the simulation service. +""" + +from __future__ import annotations + +import hashlib +from dataclasses import dataclass, field +from datetime import UTC, datetime, timedelta +from typing import TYPE_CHECKING, Any +from uuid import UUID, uuid4 + +import pytest +from fastapi.testclient import TestClient +from flask import Flask + +from policyengine_api.asgi_factory import create_asgi_app +from policyengine_api.data.v2.models import ( + HouseholdRunCalculation, + SimulationStatus, +) +from policyengine_api.fastapi_routes.dependencies import NativeRouteDependencies +from policyengine_api.migration_flags import ( + RouteImplementation, + RouteImplementationSettings, +) +from policyengine_api.services.v2.household_calculations.types import ( + HouseholdCalculationOutput, +) +from tests.unit.v2.test_household_report_reads import ( + sessions, # noqa: F401 # the fixture the service tests use + store_household_report, + succeeded_document, + succeeded_run, +) + +if TYPE_CHECKING: + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + from tests.unit.v2.test_household_report_reads import StoredHouseholdReport + +CALCULATION_ID = UUID("00000000-0000-0000-0000-00000000c001") +STARTED_AT = datetime(2026, 12, 4, 9, tzinfo=UTC) +COMPLETED_AT = STARTED_AT + timedelta(seconds=40) +VARIABLES = ["employment_income", "household_net_income", "marginal_tax_rate"] +EARNINGS_VARIATION = [ + [{"name": "employment_income", "count": 401, "min": 0, "max": 200_000}] +] +CALCULATED_HOUSEHOLD = { + "people": {"you": {"marginal_tax_rate": {"2026": [0.0, 0.153, 0.3]}}} +} +FAILURE_MESSAGE = "calculation_failed: The household function raised" +PATH = f"/v2/household-run-calculations/{CALCULATION_ID}?country_id=us" + + +def _store_calculation( # noqa: PLR0913 # the session and report, then each column a test varies + session: Session, + stored: StoredHouseholdReport, + *, + status: SimulationStatus = SimulationStatus.PENDING, + result: dict[str, Any] | None = None, + error_message: str | None = None, + axes: list[Any] | None = None, +) -> UUID: + """Store an extra calculation of the baseline's run, as the service stores one.""" + assert stored.baseline_run_id is not None + finished = status in {SimulationStatus.SUCCEEDED, SimulationStatus.FAILED} + calculation = HouseholdRunCalculation( + simulation_run_id=stored.baseline_run_id, + simulation_id=stored.baseline_simulation_id, + variables=VARIABLES, + axes=axes, + key_version=1, + calculation_key=hashlib.sha256(uuid4().bytes).hexdigest(), + status=status, + modal_call_id="fc-extra-calculation", + error_message=error_message, + result=result, + started_at=None if status is SimulationStatus.PENDING else STARTED_AT, + completed_at=COMPLETED_AT if finished else None, + ) + session.add(calculation) + session.commit() + return calculation.id + + +def _service(session_factory: sessionmaker[Session]) -> Any: + # Imported here because the change these tests precede adds them. + from policyengine_api.services.v2.household_run_calculations.database_session import ( # noqa: E501 # a module path can't be split across lines + HouseholdRunCalculationDatabaseSession, + ) + from policyengine_api.services.v2.household_run_calculations.services import ( + V2HouseholdRunCalculationService, + ) + + return V2HouseholdRunCalculationService( + HouseholdRunCalculationDatabaseSession(session_factory) + ) + + +def _validators() -> Any: + # Imported here because the change these tests precede adds it. + from policyengine_api.services.v2.household_run_calculations import validators + + return validators + + +def test_a_pending_calculation_reads_what_it_calculates_and_no_result( + sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above +) -> None: + with sessions() as session: + stored = store_household_report(session, run=succeeded_run()) + calculation_id = _store_calculation(session, stored, axes=EARNINGS_VARIATION) + + read = _service(sessions).get_calculation( + country_id="us", calculation_id=calculation_id + ) + + assert read.id == calculation_id + assert read.status == "pending" + assert read.variables == tuple(VARIABLES) + assert read.axes == EARNINGS_VARIATION + assert read.result is None + assert read.error_message is None + assert read.completed_at is None + + +def test_a_succeeded_calculation_reads_its_calculated_household( + sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above +) -> None: + with sessions() as session: + stored = store_household_report(session, run=succeeded_run()) + calculation_id = _store_calculation( + session, + stored, + status=SimulationStatus.SUCCEEDED, + result=succeeded_document( + CALCULATED_HOUSEHOLD, + warnings=["ignored_input"], + spm_config={"geography_kind": "national"}, + spm_provenance={"scenario": "baseline"}, + ), + ) + + read = _service(sessions).get_calculation( + country_id="us", calculation_id=calculation_id + ) + + assert read.status == "succeeded" + assert read.axes is None + assert read.result == HouseholdCalculationOutput( + household=CALCULATED_HOUSEHOLD, + warnings=("ignored_input",), + spm_config={"geography_kind": "national"}, + spm_provenance={"scenario": "baseline"}, + ) + assert read.error_message is None + assert read.completed_at is not None + + +def test_a_failed_calculation_reads_its_error_message( + sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above +) -> None: + with sessions() as session: + stored = store_household_report(session, run=succeeded_run()) + calculation_id = _store_calculation( + session, + stored, + status=SimulationStatus.FAILED, + error_message=FAILURE_MESSAGE, + ) + + read = _service(sessions).get_calculation( + country_id="us", calculation_id=calculation_id + ) + + assert read.status == "failed" + assert read.result is None + assert read.error_message == FAILURE_MESSAGE + + +def test_an_unknown_calculation_is_not_found( + sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above +) -> None: + with pytest.raises(_validators().HouseholdRunCalculationNotFoundError): + _service(sessions).get_calculation( + country_id="us", calculation_id=CALCULATION_ID + ) + + +def test_a_calculation_of_another_countrys_run_is_not_found( + sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above +) -> None: + with sessions() as session: + stored = store_household_report(session, country="uk", run=succeeded_run()) + calculation_id = _store_calculation(session, stored) + + with pytest.raises(_validators().HouseholdRunCalculationNotFoundError): + _service(sessions).get_calculation( + country_id="us", calculation_id=calculation_id + ) + + +def test_a_succeeded_calculation_whose_result_cannot_be_read_is_unreadable( + sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above +) -> None: + with sessions() as session: + stored = store_household_report(session, run=succeeded_run()) + calculation_id = _store_calculation( + session, + stored, + status=SimulationStatus.SUCCEEDED, + result={"status": "succeeded", "schema_version": 1}, + ) + + with pytest.raises(_validators().HouseholdRunCalculationResultUnreadableError): + _service(sessions).get_calculation( + country_id="us", calculation_id=calculation_id + ) + + +def calculation_read(**changes: Any) -> Any: + """Return the service's read of a succeeded extra calculation of a variation.""" + # Imported here because the change these tests precede adds it. + from policyengine_api.services.v2.household_run_calculations.types import ( + HouseholdRunCalculationRead, + ) + + fields: dict[str, Any] = { + "id": CALCULATION_ID, + "status": "succeeded", + "variables": tuple(VARIABLES), + "axes": EARNINGS_VARIATION, + "result": HouseholdCalculationOutput( + household=CALCULATED_HOUSEHOLD, + warnings=(), + spm_config=None, + spm_provenance=None, + ), + "error_message": None, + "created_at": STARTED_AT, + "completed_at": COMPLETED_AT, + **changes, + } + return HouseholdRunCalculationRead(**fields) + + +@dataclass +class FakeCalculationService: + """Answer with ``calculation`` or raise ``error``, recording each read.""" + + calculation: Any = None + error: Exception | None = None + reads: list[tuple[str, UUID]] = field(default_factory=list) + + def get_calculation(self, *, country_id: str, calculation_id: UUID) -> Any: + self.reads.append((country_id, calculation_id)) + if self.error is not None: + raise self.error + return self.calculation + + +def calculation_route_client(service: FakeCalculationService | None = None) -> Any: + """Serve the routes, with ``service`` reading extra calculations.""" + factories: dict[str, Any] = {} + if service is not None: + factories["v2_household_run_calculation_service_factory"] = lambda: service + dependencies = NativeRouteDependencies( + readiness_probe=lambda: True, + gateway_client_factory=lambda: None, + metadata_reader_factory=lambda: None, + **factories, + ) + settings = RouteImplementationSettings( + health=RouteImplementation.FLASK_FALLBACK, + specification=RouteImplementation.FLASK_FALLBACK, + metadata=RouteImplementation.FLASK_FALLBACK, + ) + return TestClient( + create_asgi_app( + Flask(__name__), dependencies=dependencies, route_settings=settings + ) + ) + + +def test_reading_a_calculation_answers_it_with_its_result() -> None: + service = FakeCalculationService(calculation=calculation_read()) + + response = calculation_route_client(service).get(PATH) + + assert response.status_code == 200, response.text + assert response.json() == { + "status": "ok", + "message": None, + "result": { + "item": { + "id": str(CALCULATION_ID), + "status": "succeeded", + "variables": VARIABLES, + "axes": EARNINGS_VARIATION, + "result": { + "household": CALCULATED_HOUSEHOLD, + "warnings": [], + "spm_config": None, + "spm_provenance": None, + }, + "error_message": None, + "created_at": "2026-12-04T09:00:00Z", + "completed_at": "2026-12-04T09:00:40Z", + } + }, + } + assert service.reads == [("us", CALCULATION_ID)] + + +def test_reading_a_failed_calculation_answers_its_error_message() -> None: + service = FakeCalculationService( + calculation=calculation_read( + status="failed", result=None, error_message=FAILURE_MESSAGE + ) + ) + + response = calculation_route_client(service).get(PATH) + + assert response.status_code == 200, response.text + item = response.json()["result"]["item"] + assert (item["status"], item["result"], item["error_message"]) == ( + "failed", + None, + FAILURE_MESSAGE, + ) + + +def test_reading_an_unknown_calculation_answers_404() -> None: + errors = _validators() + service = FakeCalculationService( + error=errors.HouseholdRunCalculationNotFoundError( + f"Household run calculation {CALCULATION_ID} not found." + ) + ) + + response = calculation_route_client(service).get(PATH) + + assert response.status_code == 404 + assert response.json() == { + "status": "error", + "message": f"Household run calculation {CALCULATION_ID} not found.", + } + + +@pytest.mark.parametrize( + ("error_name", "status_code"), + [ + ("HouseholdRunCalculationStorageError", 503), + ("HouseholdRunCalculationResultUnreadableError", 500), + ], + ids=["storage", "unreadable"], +) +def test_a_read_that_fails_answers_its_status( + error_name: str, status_code: int +) -> None: + error = getattr(_validators(), error_name)("an internal detail") + service = FakeCalculationService(error=error) + + response = calculation_route_client(service).get(PATH) + + assert response.status_code == status_code + assert response.json()["status"] == "error" + assert "an internal detail" not in response.json()["message"] + + +def test_a_read_naming_no_country_is_refused() -> None: + service = FakeCalculationService(calculation=calculation_read()) + + response = calculation_route_client(service).get( + f"/v2/household-run-calculations/{CALCULATION_ID}" + ) + + assert response.status_code == 422 + assert service.reads == [] + + +def test_the_openapi_document_describes_the_read() -> None: + document = calculation_route_client().get("/v2/openapi.json").json() + schemas = document["components"]["schemas"] + + read = document["paths"]["/v2/household-run-calculations/{calculation_id}"]["get"] + assert {"200", "404", "422", "500", "503"} <= set(read["responses"]) + success = read["responses"]["200"]["content"]["application/json"]["schema"] + assert success["$ref"].rsplit("/", 1)[-1] == "HouseholdRunCalculationResponse" + item = schemas["HouseholdRunCalculationItem"] + assert set(item["required"]) == { + "id", + "status", + "variables", + "axes", + "result", + "error_message", + "created_at", + "completed_at", + } diff --git a/tests/unit/v2/test_metadata_routes.py b/tests/unit/v2/test_metadata_routes.py index 66ecd3130..7ade5daf6 100644 --- a/tests/unit/v2/test_metadata_routes.py +++ b/tests/unit/v2/test_metadata_routes.py @@ -343,6 +343,7 @@ def test_openapi_references_explicit_resource_response_schemas() -> None: "/v2/households/{household_id}", "/v2/household-calculations", "/v2/household-calculations/{calculation_id}", + "/v2/household-run-calculations/{calculation_id}", "/v2/policies", "/v2/policies/{policy_id}", "/v2/reports", From 6cae7965295e2c0741b407500b72bf575116fe0e Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 4 Dec 2026 02:16:20 +0400 Subject: [PATCH 05/12] Read household runs' variables and their extra calculations The household report read gives calculated_variables: each side's list from household_run_variables, null for a side whose run calculated every variable, and null for a report with no run. The household outcome read moves to stored_reports/household_results/services.py, which keeps the report service under the file length limit. GET /v2/household-run-calculations/{calculation_id}?country_id= reads one extra calculation of a household report's run from household_run_calculations: its status, variables, axes, calculated household once it has succeeded and error message once it has failed. A calculation of another country's run is not found; the read never calls the simulation service. The route is in the report route group and the detailed-save reports workflow contract, and the contract files are regenerated. Co-Authored-By: Claude Opus 5.5 --- docs/engineering/migration-contracts.md | 5 +- docs/generated/migration_contracts.json | 22 +++- .../fastapi_routes/dependencies.py | 26 ++++ .../resource_service_protocols.py | 21 ++++ .../v2/household_run_calculations/__init__.py | 1 + .../response_models.py | 90 ++++++++++++++ .../v2/household_run_calculations/routes.py | 115 ++++++++++++++++++ .../v2/reports/response_models.py | 20 ++- policyengine_api/fastapi_routes/v2/routes.py | 4 + policyengine_api/migration_registry.py | 1 + policyengine_api/query_parameters.py | 4 + .../v2/household_run_calculations/__init__.py | 1 + .../database_connectors/__init__.py | 1 + .../database_connectors/reads.py | 46 +++++++ .../database_session.py | 30 +++++ .../v2/household_run_calculations/services.py | 81 ++++++++++++ .../transformations.py | 31 +++++ .../v2/household_run_calculations/types.py | 46 +++++++ .../household_run_calculations/validators.py | 61 ++++++++++ .../reads_household_results.py | 36 +++++- .../household_results/services.py | 68 +++++++++++ .../household_results/transformations.py | 24 +++- .../stored_reports/household_results/types.py | 32 ++++- .../services/v2/stored_reports/services.py | 36 ++---- .../v2/stored_reports/transformations.py | 13 +- .../services/v2/stored_reports/types.py | 5 +- pyproject.toml | 4 + tests/contract/registry.py | 18 +++ tests/unit/test_migration_flags.py | 4 + tests/unit/v2/test_household_report_routes.py | 1 + 30 files changed, 802 insertions(+), 45 deletions(-) create mode 100644 policyengine_api/fastapi_routes/v2/household_run_calculations/__init__.py create mode 100644 policyengine_api/fastapi_routes/v2/household_run_calculations/response_models.py create mode 100644 policyengine_api/fastapi_routes/v2/household_run_calculations/routes.py create mode 100644 policyengine_api/services/v2/household_run_calculations/__init__.py create mode 100644 policyengine_api/services/v2/household_run_calculations/database_connectors/__init__.py create mode 100644 policyengine_api/services/v2/household_run_calculations/database_connectors/reads.py create mode 100644 policyengine_api/services/v2/household_run_calculations/database_session.py create mode 100644 policyengine_api/services/v2/household_run_calculations/services.py create mode 100644 policyengine_api/services/v2/household_run_calculations/transformations.py create mode 100644 policyengine_api/services/v2/household_run_calculations/types.py create mode 100644 policyengine_api/services/v2/household_run_calculations/validators.py create mode 100644 policyengine_api/services/v2/stored_reports/household_results/services.py diff --git a/docs/engineering/migration-contracts.md b/docs/engineering/migration-contracts.md index 3884be55f..7a25e98e4 100644 --- a/docs/engineering/migration-contracts.md +++ b/docs/engineering/migration-contracts.md @@ -8,7 +8,7 @@ Generated from `policyengine_api/migration_registry.py` and `tests/contract/regi | --- | ---: | | route group count | 9 | | workflow count | 20 | -| request count | 119 | +| request count | 120 | | db entity count | 6 | | sim flow count | 3 | @@ -23,7 +23,7 @@ Generated from `policyengine_api/migration_registry.py` and `tests/contract/regi | `household` | `household`, `households`, `household-calculations`, `user-household`, `user-households`, `calculate`, `calculate-full` | `household` | `household` | | `economy` | `economy` | `simulation` | `economy` | | `simulation` | `simulation`, `simulations`, `user-simulations` | `simulation` | `economy` | -| `report` | `report`, `reports`, `user-reports`, `shared-reports`, `published-reports` | `report` | `report` | +| `report` | `report`, `reports`, `household-run-calculations`, `user-reports`, `shared-reports`, `published-reports` | `report` | `report` | | `user_profile` | `user-profile`, `me`, `admin` | `user` | `none` | ## App V2 Workflow Contracts @@ -239,6 +239,7 @@ Generated from `policyengine_api/migration_registry.py` and `tests/contract/regi | `GET` | `/v2/reports/{report_id}?country_id=us` | 200 | `report` | none | `status`, `message`, `result.item.id`, `result.item.kind`, `result.item.status`, `result.item.run`, `result.item.current_versions`, `result.item.result` | | `POST` | `/v2/reports/{report_id}/runs?country_id=us` | 201 | `report` | none | `status`, `message`, `result.item.id`, `result.item.status`, `result.item.run`, `result.item.current_versions` | | `GET` | `/v2/reports/{report_id}/runs?country_id=us` | 200 | `report` | none | `status`, `message`, `result.report_id`, `result.kind`, `result.items`, `result.current_versions` | +| `GET` | `/v2/household-run-calculations/{calculation_id}?country_id=us` | 200 | `report` | none | `status`, `message`, `result.item.id`, `result.item.status`, `result.item.variables`, `result.item.axes`, `result.item.result`, `result.item.error_message`, `result.item.created_at`, `result.item.completed_at` | | `POST` | `/v2/simulations?country_id=us` | 201 | `simulation` | none | `status`, `message`, `result.item.id`, `result.item.kind`, `result.item.status`, `result.item.run` | | `GET` | `/v2/simulations/{simulation_id}?country_id=us` | 200 | `simulation` | none | `status`, `message`, `result.item.id`, `result.item.status`, `result.item.run`, `result.item.current_versions` | diff --git a/docs/generated/migration_contracts.json b/docs/generated/migration_contracts.json index 503b92e3b..104c0bf96 100644 --- a/docs/generated/migration_contracts.json +++ b/docs/generated/migration_contracts.json @@ -1,7 +1,7 @@ { "metadata": { "db_entity_count": 6, - "request_count": 119, + "request_count": 120, "route_group_count": 9, "sim_flow_count": 3, "workflow_count": 20 @@ -98,6 +98,7 @@ "path_segments": [ "report", "reports", + "household-run-calculations", "user-reports", "shared-reports", "published-reports" @@ -1722,6 +1723,25 @@ "result.current_versions" ] }, + { + "expected_status": 200, + "headers": [], + "method": "GET", + "path": "/v2/household-run-calculations/{calculation_id}?country_id=us", + "route_group": "report", + "stable_response_fields": [ + "status", + "message", + "result.item.id", + "result.item.status", + "result.item.variables", + "result.item.axes", + "result.item.result", + "result.item.error_message", + "result.item.created_at", + "result.item.completed_at" + ] + }, { "expected_status": 201, "headers": [], diff --git a/policyengine_api/fastapi_routes/dependencies.py b/policyengine_api/fastapi_routes/dependencies.py index fad10700c..b0df900b8 100644 --- a/policyengine_api/fastapi_routes/dependencies.py +++ b/policyengine_api/fastapi_routes/dependencies.py @@ -21,6 +21,7 @@ V2DynamicResourceService, V2HouseholdCalculationResourceService, V2HouseholdResourceService, + V2HouseholdRunCalculationResourceService, V2PolicyResourceService, V2PublishedReportResourceService, V2StoredReportResourceService, @@ -84,6 +85,7 @@ "V2DynamicResourceService", "V2HouseholdCalculationResourceService", "V2HouseholdResourceService", + "V2HouseholdRunCalculationResourceService", "V2MetadataResourceReader", "V2PolicyResourceService", "V2PublishedReportResourceService", @@ -227,6 +229,24 @@ def _default_v2_household_calculation_service_factory() -> ( return _default_v2_household_calculation_service() +def _default_v2_household_run_calculation_service_factory() -> ( + V2HouseholdRunCalculationResourceService +): + from policyengine_api.data.v2.database import ( + get_v2_session_factory, + ) + from policyengine_api.services.v2.household_run_calculations.database_session import ( # noqa: E501 # a module path can't be split across lines + HouseholdRunCalculationDatabaseSession, + ) + from policyengine_api.services.v2.household_run_calculations.services import ( + V2HouseholdRunCalculationService, + ) + + return V2HouseholdRunCalculationService( + HouseholdRunCalculationDatabaseSession(get_v2_session_factory()) + ) + + def _default_v2_household_calculation_service() -> V2HouseholdCalculationService: """Build the household calculation service on the v2 database. @@ -642,6 +662,9 @@ class NativeRouteDependencies: v2_household_calculation_service_factory: ( Callable[[], V2HouseholdCalculationResourceService] | None ) = None + v2_household_run_calculation_service_factory: ( + Callable[[], V2HouseholdRunCalculationResourceService] | None + ) = None v2_stored_report_service_factory: ( Callable[[], V2StoredReportResourceService] | None ) = None @@ -697,6 +720,9 @@ def defaults(cls) -> NativeRouteDependencies: v2_household_calculation_service_factory=( _default_v2_household_calculation_service_factory ), + v2_household_run_calculation_service_factory=( + _default_v2_household_run_calculation_service_factory + ), v2_stored_report_service_factory=_default_v2_stored_report_service_factory, v2_stored_simulation_service_factory=( _default_v2_stored_simulation_service_factory diff --git a/policyengine_api/fastapi_routes/resource_service_protocols.py b/policyengine_api/fastapi_routes/resource_service_protocols.py index 284291966..1c912b16e 100644 --- a/policyengine_api/fastapi_routes/resource_service_protocols.py +++ b/policyengine_api/fastapi_routes/resource_service_protocols.py @@ -28,6 +28,9 @@ HouseholdCalculationSubmission, HouseholdCalculationSubmitted, ) + from policyengine_api.services.v2.household_run_calculations.types import ( + HouseholdRunCalculationRead, + ) from policyengine_api.services.v2.households.types import ( HouseholdPage, HouseholdRead, @@ -231,6 +234,24 @@ def get_calculation(self, calculation_id: UUID) -> HouseholdCalculationRead: ... +class V2HouseholdRunCalculationResourceService(Protocol): + """Route-independent operations on extra calculations of household report runs.""" + + def get_calculation( + self, *, country_id: str, calculation_id: UUID + ) -> HouseholdRunCalculationRead: + """Return the country's extra calculation of a household report's run. + + Raise ``HouseholdRunCalculationNotFoundError`` when no calculation of + that ID is of one of the country's runs, + ``HouseholdRunCalculationResultUnreadableError`` when a succeeded + one's result cannot be read, and + ``HouseholdRunCalculationStorageError`` when the database cannot be + read. + """ + ... + + class V2StoredReportResourceService(Protocol): """Route-independent report operations for one request.""" diff --git a/policyengine_api/fastapi_routes/v2/household_run_calculations/__init__.py b/policyengine_api/fastapi_routes/v2/household_run_calculations/__init__.py new file mode 100644 index 000000000..17755c5c1 --- /dev/null +++ b/policyengine_api/fastapi_routes/v2/household_run_calculations/__init__.py @@ -0,0 +1 @@ +"""Native API v2 routes reading extra calculations of household report runs.""" diff --git a/policyengine_api/fastapi_routes/v2/household_run_calculations/response_models.py b/policyengine_api/fastapi_routes/v2/household_run_calculations/response_models.py new file mode 100644 index 000000000..bb00360b0 --- /dev/null +++ b/policyengine_api/fastapi_routes/v2/household_run_calculations/response_models.py @@ -0,0 +1,90 @@ +"""Strict HTTP response models for extra calculations of household report runs.""" + +from __future__ import annotations + +from datetime import datetime +from typing import TYPE_CHECKING, Any, Literal +from uuid import UUID + +from pydantic import JsonValue + +from policyengine_api.fastapi_routes.v2.errors_support import V2ErrorResponse +from policyengine_api.fastapi_routes.v2.household_calculations.response_models import ( + HouseholdCalculationOutputItem, + HouseholdCalculationSuccessResponse, + StrictHouseholdCalculationAPIModel, +) + +if TYPE_CHECKING: + from policyengine_api.services.v2.household_run_calculations.types import ( + HouseholdRunCalculationRead, + ) + + +class HouseholdRunCalculationItem(StrictHouseholdCalculationAPIModel): + """One extra calculation of a side of a household report's run. + + It calculates ``variables`` (sorted, distinct names) for the side's + stored household, policy, dynamic and year, on its run's versions: + for the household as entered when ``axes`` is null, or varied along + ``axes``, as ``/v2/household-calculations`` takes them. Read it again + until ``status`` is ``succeeded`` or ``failed``. ``result`` is the + calculated household once it has succeeded, with one value per period + for each listed variable, or one list per period when varied along + axes, and null otherwise; ``error_message`` says why it failed, as + ``code: message``, and is null otherwise. ``completed_at`` is null until + it has finished. + """ + + id: UUID + status: Literal["pending", "running", "succeeded", "failed"] + variables: list[str] + axes: list[list[dict[str, JsonValue]]] | None + result: HouseholdCalculationOutputItem | None + error_message: str | None + created_at: datetime + completed_at: datetime | None + + @classmethod + def from_read( + cls, read: HouseholdRunCalculationRead + ) -> HouseholdRunCalculationItem: + """Build the item from the service's read of the calculation.""" + return cls.model_validate(read) + + +class HouseholdRunCalculationResult(StrictHouseholdCalculationAPIModel): + """Result holding one extra calculation in ``item``.""" + + item: HouseholdRunCalculationItem + + +class HouseholdRunCalculationResponse( + HouseholdCalculationSuccessResponse[HouseholdRunCalculationResult] +): + """Success response holding one extra calculation.""" + + +HOUSEHOLD_RUN_CALCULATION_READ_RESPONSES: dict[int | str, dict[str, Any]] = { + 404: { + "model": V2ErrorResponse, + "description": ( + "No extra calculation of that ID is of one of the country's household runs." + ), + }, + 422: { + "model": V2ErrorResponse, + "description": "The request does not match the schema.", + }, + 500: { + "model": V2ErrorResponse, + "description": ( + "A succeeded calculation's stored result cannot be read, or the " + "read failed unexpectedly." + ), + }, + 503: { + "model": V2ErrorResponse, + "description": "The v2 database is not configured or cannot be read.", + }, +} diff --git a/policyengine_api/fastapi_routes/v2/household_run_calculations/routes.py b/policyengine_api/fastapi_routes/v2/household_run_calculations/routes.py new file mode 100644 index 000000000..1231490d7 --- /dev/null +++ b/policyengine_api/fastapi_routes/v2/household_run_calculations/routes.py @@ -0,0 +1,115 @@ +"""Native FastAPI route reading extra calculations of household report runs. + +An extra calculation calculates more of one side of a household report's +run, such as ``marginal_tax_rate`` or an earnings variation. The simulation +service inserts it in ``household_run_calculations`` and its household +function completes it; reading one reads the row and never calls the +simulation service. No account is needed, as for reading a report. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Annotated +from uuid import UUID + +from fastapi import APIRouter, Depends +from starlette.responses import JSONResponse + +from policyengine_api.data.v2.settings import V2ConfigurationError +from policyengine_api.fastapi_routes.dependencies import ( + _default_v2_household_run_calculation_service_factory, +) +from policyengine_api.fastapi_routes.query_parameters import query_dependency +from policyengine_api.fastapi_routes.v2.errors_support import ( + V2ErrorMapping, + run_v2_operation, +) +from policyengine_api.fastapi_routes.v2.household_run_calculations.response_models import ( # noqa: E501 # a module path can't be split across lines + HOUSEHOLD_RUN_CALCULATION_READ_RESPONSES, + HouseholdRunCalculationItem, + HouseholdRunCalculationResponse, + HouseholdRunCalculationResult, +) +from policyengine_api.query_parameters import HouseholdRunCalculationQuery +from policyengine_api.services.v2.household_run_calculations.validators import ( + HouseholdRunCalculationNotFoundError, + HouseholdRunCalculationResultUnreadableError, + HouseholdRunCalculationStorageError, +) + +if TYPE_CHECKING: + from collections.abc import Callable + + from policyengine_api.fastapi_routes.dependencies import ( + NativeRouteDependencies, + V2HouseholdRunCalculationResourceService, + ) + +HouseholdRunCalculationQueryDependency = Annotated[ + HouseholdRunCalculationQuery, + Depends(query_dependency(HouseholdRunCalculationQuery)), +] +HOUSEHOLD_RUN_CALCULATION_ERROR_MAPPINGS = ( + V2ErrorMapping((HouseholdRunCalculationNotFoundError,), 404), + V2ErrorMapping( + (HouseholdRunCalculationResultUnreadableError,), + 500, + "Stored household run calculation result is unreadable", + ), + V2ErrorMapping( + (HouseholdRunCalculationStorageError, V2ConfigurationError), + 503, + "V2 household run calculation storage is unavailable", + ), +) + + +def _service_factory( + dependencies: NativeRouteDependencies, +) -> Callable[[], V2HouseholdRunCalculationResourceService]: + if dependencies.v2_household_run_calculation_service_factory is not None: + return dependencies.v2_household_run_calculation_service_factory + return _default_v2_household_run_calculation_service_factory + + +def build_v2_household_run_calculation_router( + dependencies: NativeRouteDependencies, +) -> APIRouter: + """Build the extra calculation read route without opening any connection.""" + router = APIRouter(prefix="/v2") + service_factory = _service_factory(dependencies) + + @router.get( + "/household-run-calculations/{calculation_id}", + response_model=HouseholdRunCalculationResponse, + responses=HOUSEHOLD_RUN_CALCULATION_READ_RESPONSES, + summary="Read an extra calculation of a household report's run", + description=( + "Reads one extra calculation of a side of a household report's run, " + "for following it until it finishes: its status, the variables and " + "axes it calculates, the calculated household once it has succeeded " + "and the error message once it has failed. A calculation of another " + "country's run is not found. Never calls the simulation service." + ), + ) + def get_household_run_calculation( + calculation_id: UUID, + query: HouseholdRunCalculationQueryDependency, + ) -> HouseholdRunCalculationResponse | JSONResponse: + def read() -> HouseholdRunCalculationResponse: + calculation = service_factory().get_calculation( + country_id=query.country_id, calculation_id=calculation_id + ) + return HouseholdRunCalculationResponse( + result=HouseholdRunCalculationResult( + item=HouseholdRunCalculationItem.from_read(calculation) + ) + ) + + return run_v2_operation( + read, + HOUSEHOLD_RUN_CALCULATION_ERROR_MAPPINGS, + fallback_message="V2 household run calculation read failed", + ) + + return router diff --git a/policyengine_api/fastapi_routes/v2/reports/response_models.py b/policyengine_api/fastapi_routes/v2/reports/response_models.py index ecace767e..848da7546 100644 --- a/policyengine_api/fastapi_routes/v2/reports/response_models.py +++ b/policyengine_api/fastapi_routes/v2/reports/response_models.py @@ -272,16 +272,34 @@ class HouseholdReportFailureItem(StrictReportAPIModel): reform: HouseholdReportSideFailureItem | None +class CalculatedVariablesItem(StrictReportAPIModel): + """The variables each side's simulation run calculates, sorted. + + A side is null when its run calculates every variable: one created before + a household report could list variables, or by a request that listed + none. ``reform`` is also null for a report of the baseline alone. A view + that reads a variable a side doesn't list asks for it as an extra + calculation of the run + (``POST /v2/reports/{report_id}/runs/{run_id}/household-calculations``). + """ + + baseline: list[str] | None + reform: list[str] | None + + class HouseholdReportItem(HouseholdReportSummaryItem): """A household report with its run's outcome. ``result`` holds the calculated households once the run read has succeeded, and ``failure`` each side's error once it has failed; each is - null otherwise. + null otherwise. ``calculated_variables`` names the variables each side's + run calculates, whatever its status, and is null for a report with no + run. """ result: HouseholdReportResultItem | None failure: HouseholdReportFailureItem | None + calculated_variables: CalculatedVariablesItem | None @classmethod def from_read(cls, read: HouseholdReportRead) -> HouseholdReportItem: diff --git a/policyengine_api/fastapi_routes/v2/routes.py b/policyengine_api/fastapi_routes/v2/routes.py index 385903eba..f763a3bd3 100644 --- a/policyengine_api/fastapi_routes/v2/routes.py +++ b/policyengine_api/fastapi_routes/v2/routes.py @@ -23,6 +23,9 @@ from policyengine_api.fastapi_routes.v2.household_calculations.routes import ( build_v2_household_calculation_router, ) +from policyengine_api.fastapi_routes.v2.household_run_calculations.routes import ( + build_v2_household_run_calculation_router, +) from policyengine_api.fastapi_routes.v2.households.routes import ( build_v2_household_router, ) @@ -104,6 +107,7 @@ def build_v2_router( router.include_router(build_v2_user_dynamic_router(dependencies)) router.include_router(build_v2_household_router(dependencies)) router.include_router(build_v2_household_calculation_router(dependencies)) + router.include_router(build_v2_household_run_calculation_router(dependencies)) router.include_router(build_v2_policy_router(dependencies)) router.include_router(build_v2_dynamic_router(dependencies)) router.include_router(build_v2_report_router(dependencies)) diff --git a/policyengine_api/migration_registry.py b/policyengine_api/migration_registry.py index ea4f0b58c..51932e465 100644 --- a/policyengine_api/migration_registry.py +++ b/policyengine_api/migration_registry.py @@ -99,6 +99,7 @@ class RouteGroupConfig: path_segments=( "report", "reports", + "household-run-calculations", "user-reports", "shared-reports", "published-reports", diff --git a/policyengine_api/query_parameters.py b/policyengine_api/query_parameters.py index a834d4785..7ba2c9992 100644 --- a/policyengine_api/query_parameters.py +++ b/policyengine_api/query_parameters.py @@ -540,6 +540,10 @@ class ReportRunsQuery(CountryQuery): """Query contract for a report's runs in a country: listing or starting one.""" +class HouseholdRunCalculationQuery(CountryQuery): + """Query contract for an extra calculation of one of a country's household runs.""" + + class ReportCollectionQuery(CountryQuery): """Query contract for listing chosen reports of a country, or finding them. diff --git a/policyengine_api/services/v2/household_run_calculations/__init__.py b/policyengine_api/services/v2/household_run_calculations/__init__.py new file mode 100644 index 000000000..9b97708a3 --- /dev/null +++ b/policyengine_api/services/v2/household_run_calculations/__init__.py @@ -0,0 +1 @@ +"""Application services for extra calculations of v2 household report runs.""" diff --git a/policyengine_api/services/v2/household_run_calculations/database_connectors/__init__.py b/policyengine_api/services/v2/household_run_calculations/database_connectors/__init__.py new file mode 100644 index 000000000..426eb8674 --- /dev/null +++ b/policyengine_api/services/v2/household_run_calculations/database_connectors/__init__.py @@ -0,0 +1 @@ +"""SQL-facing connector functions for extra calculations of household runs.""" diff --git a/policyengine_api/services/v2/household_run_calculations/database_connectors/reads.py b/policyengine_api/services/v2/household_run_calculations/database_connectors/reads.py new file mode 100644 index 000000000..a4c4cd1e9 --- /dev/null +++ b/policyengine_api/services/v2/household_run_calculations/database_connectors/reads.py @@ -0,0 +1,46 @@ +"""Database reads of extra calculations of household report runs.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from sqlmodel import col, select + +from policyengine_api.data.v2.models import ( + HouseholdRunCalculation, + Simulation, + TaxBenefitModel, + TaxBenefitModelVersion, +) + +if TYPE_CHECKING: + from uuid import UUID + + from sqlmodel import Session + + +def read_household_run_calculation( + session: Session, *, country_id: str, calculation_id: UUID +) -> HouseholdRunCalculation | None: + """Return the calculation if its simulation is of the country's model, in one query. + + A calculation has no country column: its simulation's catalog version's + model is the country's (``policyengine-``), as for a stored + simulation. + """ + statement = ( + select(HouseholdRunCalculation) + .join(Simulation, col(Simulation.id) == HouseholdRunCalculation.simulation_id) + .join( + TaxBenefitModelVersion, + col(TaxBenefitModelVersion.id) == Simulation.tax_benefit_model_version_id, + ) + .join( + TaxBenefitModel, col(TaxBenefitModel.id) == TaxBenefitModelVersion.model_id + ) + .where( + col(HouseholdRunCalculation.id) == calculation_id, + col(TaxBenefitModel.name) == f"policyengine-{country_id}", + ) + ) + return session.exec(statement).one_or_none() diff --git a/policyengine_api/services/v2/household_run_calculations/database_session.py b/policyengine_api/services/v2/household_run_calculations/database_session.py new file mode 100644 index 000000000..ade6739c2 --- /dev/null +++ b/policyengine_api/services/v2/household_run_calculations/database_session.py @@ -0,0 +1,30 @@ +"""Database session lifetime management for extra calculations of household runs.""" + +from __future__ import annotations + +from contextlib import contextmanager +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Iterator + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + +class HouseholdRunCalculationDatabaseSession: + """Open the read sessions the household run calculation service uses. + + API v1 only reads ``household_run_calculations``, which the simulation + service inserts and its household function completes. + """ + + def __init__(self, session_factory: sessionmaker[Session]) -> None: + """Use ``session_factory`` to open every session.""" + self._session_factory = session_factory + + @contextmanager + def read(self) -> Iterator[Session]: + """Yield a session for reads; nothing is committed.""" + with self._session_factory() as session: + yield session diff --git a/policyengine_api/services/v2/household_run_calculations/services.py b/policyengine_api/services/v2/household_run_calculations/services.py new file mode 100644 index 000000000..494f3882a --- /dev/null +++ b/policyengine_api/services/v2/household_run_calculations/services.py @@ -0,0 +1,81 @@ +"""Read extra calculations of household report runs. + +An extra calculation (``household_run_calculations``) calculates more of +one side's simulation run of a household report, such as +``marginal_tax_rate`` or an earnings variation. The simulation service +inserts it and its household function completes it; reading one reads the +row and never calls the simulation service. A calculation is read within its +country: one of another country's run is not found. +""" + +from __future__ import annotations + +from contextlib import contextmanager +from typing import TYPE_CHECKING + +from sqlalchemy.exc import SQLAlchemyError + +from policyengine_api.services.v2.household_run_calculations.database_connectors.reads import ( # noqa: E501 # a module path can't be split across lines + read_household_run_calculation, +) +from policyengine_api.services.v2.household_run_calculations.transformations import ( + household_run_calculation_read, +) +from policyengine_api.services.v2.household_run_calculations.validators import ( + HouseholdRunCalculationStorageError, + calculated_household, + require_calculation, +) + +if TYPE_CHECKING: + from collections.abc import Iterator + from uuid import UUID + + from policyengine_api.services.v2.household_run_calculations.database_session import ( # noqa: E501 # a module path can't be split across lines + HouseholdRunCalculationDatabaseSession, + ) + from policyengine_api.services.v2.household_run_calculations.types import ( + HouseholdRunCalculationRead, + ) + + +@contextmanager +def _storage_failures() -> Iterator[None]: + """Raise HouseholdRunCalculationStorageError for a failed database read.""" + try: + yield + except SQLAlchemyError as error: + msg = "V2 household run calculation storage is unavailable" + raise HouseholdRunCalculationStorageError(msg) from error + + +class V2HouseholdRunCalculationService: + """Read extra calculations of household report runs from the v2 tables.""" + + def __init__( + self, database_session: HouseholdRunCalculationDatabaseSession + ) -> None: + """Read through ``database_session``.""" + self._database_session = database_session + + def get_calculation( + self, *, country_id: str, calculation_id: UUID + ) -> HouseholdRunCalculationRead: + """Return the country's calculation, with its household once it has succeeded. + + Raise HouseholdRunCalculationNotFoundError when no calculation of that + ID is of one of the country's runs, + HouseholdRunCalculationResultUnreadableError when a succeeded one's + result cannot be read, and HouseholdRunCalculationStorageError when + the database cannot be read. + """ + with _storage_failures(), self._database_session.read() as session: + calculation = require_calculation( + read_household_run_calculation( + session, country_id=country_id, calculation_id=calculation_id + ), + calculation_id=calculation_id, + ) + return household_run_calculation_read( + calculation, calculated_household(calculation) + ) diff --git a/policyengine_api/services/v2/household_run_calculations/transformations.py b/policyengine_api/services/v2/household_run_calculations/transformations.py new file mode 100644 index 000000000..7ab48dc85 --- /dev/null +++ b/policyengine_api/services/v2/household_run_calculations/transformations.py @@ -0,0 +1,31 @@ +"""Turn stored extra calculations of household report runs into reads.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from policyengine_api.services.v2.household_run_calculations.types import ( + HouseholdRunCalculationRead, +) + +if TYPE_CHECKING: + from policyengine_api.data.v2.models import HouseholdRunCalculation + from policyengine_api.services.v2.household_calculations.types import ( + HouseholdCalculationOutput, + ) + + +def household_run_calculation_read( + calculation: HouseholdRunCalculation, result: HouseholdCalculationOutput | None +) -> HouseholdRunCalculationRead: + """Return the calculation, with ``result``, its calculated household, if read.""" + return HouseholdRunCalculationRead( + id=calculation.id, + status=calculation.status.value, + variables=tuple(calculation.variables), + axes=calculation.axes, + result=result, + error_message=calculation.error_message, + created_at=calculation.created_at, + completed_at=calculation.completed_at, + ) diff --git a/policyengine_api/services/v2/household_run_calculations/types.py b/policyengine_api/services/v2/household_run_calculations/types.py new file mode 100644 index 000000000..fba0140d0 --- /dev/null +++ b/policyengine_api/services/v2/household_run_calculations/types.py @@ -0,0 +1,46 @@ +"""Framework-independent data exchanged by the household run calculation layers. + +An extra calculation of a household report's run calculates more of one +side's simulation run than the run did: the variables it lists, for the +household as entered or varied along axes. The simulation service inserts +it in ``household_run_calculations`` and its household function completes +it; API v1 reads it. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Literal + +if TYPE_CHECKING: + from datetime import datetime + from uuid import UUID + + from policyengine_api.services.v2.household_calculations.types import ( + HouseholdCalculationOutput, + ) + +# A calculation's status, as household_run_calculations stores it. +HouseholdRunCalculationStatus = Literal["pending", "running", "succeeded", "failed"] + + +@dataclass(frozen=True) +class HouseholdRunCalculationRead: + """One extra calculation of a household simulation run. + + ``variables`` are the sorted, distinct names it calculates and ``axes`` + the variation, as ``/v2/household-calculations`` takes axes, or None for + the household as entered. ``result`` is the calculated household once it + has succeeded, with one value per period, or one list per period when + varied along axes; ``error_message`` says why it failed, as + ``code: message``. ``completed_at`` is set once it has finished. + """ + + id: UUID + status: HouseholdRunCalculationStatus + variables: tuple[str, ...] + axes: list[Any] | None + result: HouseholdCalculationOutput | None + error_message: str | None + created_at: datetime + completed_at: datetime | None diff --git a/policyengine_api/services/v2/household_run_calculations/validators.py b/policyengine_api/services/v2/household_run_calculations/validators.py new file mode 100644 index 000000000..b04df9f12 --- /dev/null +++ b/policyengine_api/services/v2/household_run_calculations/validators.py @@ -0,0 +1,61 @@ +"""Checks of the extra calculations of household report runs that API v1 reads.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from pydantic import ValidationError + +from policyengine_api.data.v2.models import SimulationStatus +from policyengine_api.services.v2.household_calculations.types import ( + StoredExecutionResult, +) + +if TYPE_CHECKING: + from uuid import UUID + + from policyengine_api.data.v2.models import HouseholdRunCalculation + from policyengine_api.services.v2.household_calculations.types import ( + HouseholdCalculationOutput, + ) + + +class HouseholdRunCalculationNotFoundError(LookupError): + """No extra calculation of that ID is of one of the country's runs.""" + + +class HouseholdRunCalculationStorageError(RuntimeError): + """The database could not be read.""" + + +class HouseholdRunCalculationResultUnreadableError(RuntimeError): + """A succeeded calculation's stored result is not a readable result document.""" + + +def require_calculation( + calculation: HouseholdRunCalculation | None, *, calculation_id: UUID +) -> HouseholdRunCalculation: + """Return the calculation, or raise HouseholdRunCalculationNotFoundError.""" + if calculation is None: + msg = f"Household run calculation {calculation_id} not found." + raise HouseholdRunCalculationNotFoundError(msg) + return calculation + + +def calculated_household( + calculation: HouseholdRunCalculation, +) -> HouseholdCalculationOutput | None: + """Return a succeeded calculation's household; None for any other status. + + A succeeded calculation holds the household function's version 1 result + document, as a household job does; raise + HouseholdRunCalculationResultUnreadableError when it does not. + """ + if calculation.status is not SimulationStatus.SUCCEEDED: + return None + try: + document = StoredExecutionResult.model_validate(calculation.result) + except ValidationError as error: + msg = f"Household run calculation {calculation.id} has an unreadable result." + raise HouseholdRunCalculationResultUnreadableError(msg) from error + return document.calculation_output() diff --git a/policyengine_api/services/v2/stored_reports/database_connectors/reads_household_results.py b/policyengine_api/services/v2/stored_reports/database_connectors/reads_household_results.py index 1a307836c..016548a5d 100644 --- a/policyengine_api/services/v2/stored_reports/database_connectors/reads_household_results.py +++ b/policyengine_api/services/v2/stored_reports/database_connectors/reads_household_results.py @@ -6,12 +6,14 @@ from sqlmodel import col, select -from policyengine_api.data.v2.models import SimulationRun +from policyengine_api.data.v2.models import HouseholdRunVariables, SimulationRun from policyengine_api.services.v2.stored_reports.household_results.types import ( HouseholdResultRows, ) if TYPE_CHECKING: + from uuid import UUID + from sqlmodel import Session from policyengine_api.data.v2.models import ReportRun @@ -25,10 +27,34 @@ def read_household_result_rows( Each simulation run the report run names maps to its ``household_result``; a run that does not exist is absent. """ - simulation_run_ids = [report_run.baseline_simulation_run_id] - if report_run.reform_simulation_run_id is not None: - simulation_run_ids.append(report_run.reform_simulation_run_id) statement = select( col(SimulationRun.id), col(SimulationRun.household_result) - ).where(col(SimulationRun.id).in_(simulation_run_ids)) + ).where(col(SimulationRun.id).in_(_simulation_run_ids(report_run))) return HouseholdResultRows(documents=dict(session.exec(statement).all())) + + +def read_household_run_variables( + session: Session, *, report_run: ReportRun +) -> dict[UUID, list[str]]: + """Return the variables the report run's simulation runs calculate, in one query. + + Each simulation run with a ``household_run_variables`` row maps to its + list; a run without one, which calculates every variable, is absent. + """ + statement = select( + col(HouseholdRunVariables.simulation_run_id), + col(HouseholdRunVariables.variables), + ).where( + col(HouseholdRunVariables.simulation_run_id).in_( + _simulation_run_ids(report_run) + ) + ) + return dict(session.exec(statement).all()) + + +def _simulation_run_ids(report_run: ReportRun) -> list[UUID]: + """Return the simulation runs the report run names, the baseline's first.""" + simulation_run_ids = [report_run.baseline_simulation_run_id] + if report_run.reform_simulation_run_id is not None: + simulation_run_ids.append(report_run.reform_simulation_run_id) + return simulation_run_ids diff --git a/policyengine_api/services/v2/stored_reports/household_results/services.py b/policyengine_api/services/v2/stored_reports/household_results/services.py new file mode 100644 index 000000000..05f6a114f --- /dev/null +++ b/policyengine_api/services/v2/stored_reports/household_results/services.py @@ -0,0 +1,68 @@ +"""Read what a household report's run gives beside the report's definition. + +``household_report_outcome`` reads, for the report run read, the variables +each side's simulation run calculates (``household_run_variables``), and, +once the run has finished, each side's calculated household or failure +(``simulation_runs.household_result``). The report service's household read +calls it; it moved here from +``policyengine_api.services.v2.stored_reports.services``, which keeps the +rest of the read. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from policyengine_api.data.v2.models import ReportRunStatus +from policyengine_api.services.v2.stored_reports.database_connectors import ( + reads_household_results as household_result_reads, +) +from policyengine_api.services.v2.stored_reports.household_results.transformations import ( # noqa: E501 # a module path can't be split across lines + calculated_variables, + household_report_failure, +) +from policyengine_api.services.v2.stored_reports.household_results.types import ( + HouseholdReportOutcome, +) +from policyengine_api.services.v2.stored_reports.household_results.validators import ( + require_household_report_result, +) + +if TYPE_CHECKING: + from sqlmodel import Session + + from policyengine_api.data.v2.models import ReportRun + + +def household_report_outcome( + session: Session, run: ReportRun | None +) -> HouseholdReportOutcome: + """Return the run's calculated variables, and its result or failure once finished. + + The variables are read whatever the run's status, since the simulation + service records them when it creates the run. The calculated households + are read once the run has succeeded, and each side's failure once it has + failed. A report with no run has none of these. Raise + HouseholdResultUnreadableError when a succeeded run's households cannot + be read. + """ + if run is None: + return HouseholdReportOutcome( + result=None, failure=None, calculated_variables=None + ) + variables = calculated_variables( + run, + household_result_reads.read_household_run_variables(session, report_run=run), + ) + result = failure = None + if run.status in {ReportRunStatus.SUCCEEDED, ReportRunStatus.FAILED}: + rows = household_result_reads.read_household_result_rows( + session, report_run=run + ) + if run.status is ReportRunStatus.SUCCEEDED: + result = require_household_report_result(run, rows) + else: + failure = household_report_failure(run, rows) + return HouseholdReportOutcome( + result=result, failure=failure, calculated_variables=variables + ) diff --git a/policyengine_api/services/v2/stored_reports/household_results/transformations.py b/policyengine_api/services/v2/stored_reports/household_results/transformations.py index eaa483a20..18a58c38c 100644 --- a/policyengine_api/services/v2/stored_reports/household_results/transformations.py +++ b/policyengine_api/services/v2/stored_reports/household_results/transformations.py @@ -1,4 +1,4 @@ -"""Read a failed household report run's failure documents.""" +"""Read a household report run's failure documents and calculated variables.""" from __future__ import annotations @@ -10,11 +10,13 @@ StoredExecutionFailure, ) from policyengine_api.services.v2.stored_reports.household_results.types import ( + CalculatedVariables, HouseholdReportFailure, HouseholdReportSideFailure, ) if TYPE_CHECKING: + from collections.abc import Mapping, Sequence from uuid import UUID from policyengine_api.data.v2.models import ReportRun @@ -56,3 +58,23 @@ def household_report_failure( baseline=_side_failure(rows, report_run.baseline_simulation_run_id), reform=_side_failure(rows, report_run.reform_simulation_run_id), ) + + +def calculated_variables( + report_run: ReportRun, listed: Mapping[UUID, Sequence[str]] +) -> CalculatedVariables: + """Return the variables each side's simulation run calculates. + + ``listed`` holds each simulation run's ``household_run_variables`` list; + a side whose run is absent from it calculates every variable (None). + """ + reform_run_id = report_run.reform_simulation_run_id + + def side(simulation_run_id: UUID | None) -> tuple[str, ...] | None: + names = None if simulation_run_id is None else listed.get(simulation_run_id) + return None if names is None else tuple(names) + + return CalculatedVariables( + baseline=side(report_run.baseline_simulation_run_id), + reform=side(reform_run_id), + ) diff --git a/policyengine_api/services/v2/stored_reports/household_results/types.py b/policyengine_api/services/v2/stored_reports/household_results/types.py index 8ce6187c1..a10f04c5e 100644 --- a/policyengine_api/services/v2/stored_reports/household_results/types.py +++ b/policyengine_api/services/v2/stored_reports/household_results/types.py @@ -1,7 +1,9 @@ """The result of a household report: each simulation's calculated household. A household report's simulations each calculate the report's stored -household under one policy. The household function stores each simulation +household under one policy. Each side's run calculates the variables its +report's request listed, which ``household_run_variables`` records, or +every variable, with no row there. The household function stores each simulation run's calculation in ``simulation_runs.household_result``, as the same result document a household calculation stores in ``household_jobs.result`` (``household_calculations.types.StoredExecutionResult``), or, for a @@ -73,6 +75,19 @@ class HouseholdReportSideFailure: spm_error: dict[str, JsonValue] | None +@dataclass(frozen=True) +class CalculatedVariables: + """The variables each side's simulation run calculated, sorted. + + A side is None when its run calculated every variable: one created before + requests could list variables, or by a request that listed none. + ``reform`` is also None for a report of the baseline alone. + """ + + baseline: tuple[str, ...] | None + reform: tuple[str, ...] | None + + @dataclass(frozen=True) class HouseholdReportFailure: """Why each side of a failed household report run failed, where it says. @@ -87,3 +102,18 @@ class HouseholdReportFailure: baseline: HouseholdReportSideFailure | None reform: HouseholdReportSideFailure | None + + +@dataclass(frozen=True) +class HouseholdReportOutcome: + """What a household report's run read gives beside the report's definition. + + ``result`` holds the calculated households once the run has succeeded, + ``failure`` each side's failure once it has failed, and + ``calculated_variables`` the variables each side's run calculates, + whatever its status. All three are None for a report with no run. + """ + + result: HouseholdReportResult | None + failure: HouseholdReportFailure | None + calculated_variables: CalculatedVariables | None diff --git a/policyengine_api/services/v2/stored_reports/services.py b/policyengine_api/services/v2/stored_reports/services.py index ced5064de..f0854f280 100644 --- a/policyengine_api/services/v2/stored_reports/services.py +++ b/policyengine_api/services/v2/stored_reports/services.py @@ -28,7 +28,8 @@ full economy result once it has succeeded. A household report's result is instead each of its simulation runs' calculated household (``simulation_runs.household_result``), read once its report run has -succeeded, and each side's failure once it has failed. Lists name at most 25 +succeeded, and each side's failure once it has failed, with the variables +each side's run calculates (``household_results.services``). Lists name at most 25 reports and read them as a read without a run does, with any window's years, without results: two queries, and with a user three or four more for their labels and their newest recorded runs. A search finds the country's @@ -81,9 +82,6 @@ from policyengine_api.services.v2.stored_reports.database_connectors import ( reads_budget_window_results as window_result_reads, ) -from policyengine_api.services.v2.stored_reports.database_connectors import ( - reads_household_results as household_result_reads, -) from policyengine_api.services.v2.stored_reports.database_connectors import ( reads_results as result_reads, ) @@ -101,11 +99,8 @@ from policyengine_api.services.v2.stored_reports.economy_results import ( transformations as result_transformations, ) -from policyengine_api.services.v2.stored_reports.household_results import ( - transformations as household_result_transformations, -) -from policyengine_api.services.v2.stored_reports.household_results.validators import ( - require_household_report_result, +from policyengine_api.services.v2.stored_reports.household_results.services import ( + household_report_outcome, ) from policyengine_api.services.v2.stored_reports.requester_views.services import ( requesters_view, @@ -504,29 +499,14 @@ def _household_report( ) -> HouseholdReportRead: """Return a household report with the outcome of the run read. - Its calculated households are read once that run has succeeded, and - each side's failure once it has failed. + The variables each side's run calculates are read whatever its + status, its calculated households once it has succeeded, and each + side's failure once it has failed (``household_report_outcome``). """ - run = stored.run - result = failure = None - if run is not None and run.status in { - ReportRunStatus.SUCCEEDED, - ReportRunStatus.FAILED, - }: - rows = household_result_reads.read_household_result_rows( - session, report_run=run - ) - if run.status is ReportRunStatus.SUCCEEDED: - result = require_household_report_result(run, rows) - else: - failure = household_result_transformations.household_report_failure( - run, rows - ) return household_report_read( stored, current_versions=self._current_versions(stored.report.country), - result=result, - failure=failure, + outcome=household_report_outcome(session, stored.run), ) def list_reports( diff --git a/policyengine_api/services/v2/stored_reports/transformations.py b/policyengine_api/services/v2/stored_reports/transformations.py index e67e76911..fa85f70ea 100644 --- a/policyengine_api/services/v2/stored_reports/transformations.py +++ b/policyengine_api/services/v2/stored_reports/transformations.py @@ -46,8 +46,7 @@ ReportRunCliffRows, ) from policyengine_api.services.v2.stored_reports.household_results.types import ( - HouseholdReportFailure, - HouseholdReportResult, + HouseholdReportOutcome, ) from policyengine_api.services.v2.stored_reports.types import ( CliffCalculationStatusName, @@ -224,12 +223,16 @@ def household_report_read( rows: StoredReportRows, *, current_versions: PackageVersions, - result: HouseholdReportResult | None, - failure: HouseholdReportFailure | None, + outcome: HouseholdReportOutcome, ) -> HouseholdReportRead: """Return a household report with the run read's outcome, if it has one.""" summary = household_report_summary_read(rows, current_versions=current_versions) - return HouseholdReportRead(**vars(summary), result=result, failure=failure) + return HouseholdReportRead( + **vars(summary), + result=outcome.result, + failure=outcome.failure, + calculated_variables=outcome.calculated_variables, + ) def budget_window_run_read( diff --git a/policyengine_api/services/v2/stored_reports/types.py b/policyengine_api/services/v2/stored_reports/types.py index e0cb5b402..2c3cc57b4 100644 --- a/policyengine_api/services/v2/stored_reports/types.py +++ b/policyengine_api/services/v2/stored_reports/types.py @@ -39,6 +39,7 @@ EconomyResult, ) from policyengine_api.services.v2.stored_reports.household_results.types import ( + CalculatedVariables, HouseholdReportFailure, HouseholdReportResult, ) @@ -203,11 +204,13 @@ class HouseholdReportRead(HouseholdReportSummaryRead): ``result`` holds the calculated households once that run has succeeded; ``failure`` says why each side failed once it has failed. Both are None - otherwise. + otherwise. ``calculated_variables`` names the variables each side's run + calculates, whatever its status, and is None for a report with no run. """ result: HouseholdReportResult | None failure: HouseholdReportFailure | None + calculated_variables: CalculatedVariables | None @dataclass(frozen=True) diff --git a/pyproject.toml b/pyproject.toml index 9e5d5941b..39b396d55 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -423,6 +423,8 @@ banned-module-level-imports = [ "policyengine_api.services.v2.dynamics.services", "policyengine_api.services.v2.household_calculations.database_session", "policyengine_api.services.v2.household_calculations.services", + "policyengine_api.services.v2.household_run_calculations.database_session", + "policyengine_api.services.v2.household_run_calculations.services", "policyengine_api.services.v2.households.database_session", "policyengine_api.services.v2.households.services", "policyengine_api.services.v2.legacy_refs.database_session", @@ -475,6 +477,8 @@ runtime-evaluated-base-classes = [ "policyengine_api.data.v2.models.run_results.UKAreaImpactBase", "policyengine_api.fastapi_routes.v2.errors_support.V2ErrorResponse", "policyengine_api.fastapi_routes.v2.households.document_models.HouseholdEntityRecord", + "policyengine_api.fastapi_routes.v2.household_calculations.response_models.HouseholdCalculationSuccessResponse", + "policyengine_api.fastapi_routes.v2.household_calculations.response_models.StrictHouseholdCalculationAPIModel", "policyengine_api.fastapi_routes.v2.households.document_models.StrictHouseholdDocumentModel", "policyengine_api.fastapi_routes.v2.households.response_models.HouseholdSuccessResponse", "policyengine_api.fastapi_routes.v2.households.response_models.StrictHouseholdAPIModel", diff --git a/tests/contract/registry.py b/tests/contract/registry.py index 2df942a4a..5b1cc0f7b 100644 --- a/tests/contract/registry.py +++ b/tests/contract/registry.py @@ -770,6 +770,24 @@ class WorkflowContract: ), route_group="report", ), + ContractRequest( + method="GET", + path="/v2/household-run-calculations/{calculation_id}?country_id=us", + expected_status=200, + stable_response_fields=( + "status", + "message", + "result.item.id", + "result.item.status", + "result.item.variables", + "result.item.axes", + "result.item.result", + "result.item.error_message", + "result.item.created_at", + "result.item.completed_at", + ), + route_group="report", + ), ContractRequest( method="POST", path="/v2/simulations?country_id=us", diff --git a/tests/unit/test_migration_flags.py b/tests/unit/test_migration_flags.py index 3ac24d270..2c3fff7f5 100644 --- a/tests/unit/test_migration_flags.py +++ b/tests/unit/test_migration_flags.py @@ -201,6 +201,10 @@ def test_explicit_migration_context_rejects_invalid_database_sources( ), ("/v2/user-simulations", "simulation"), ("/v2/user-reports/00000000-0000-0000-0000-000000000001", "report"), + ( + "/v2/household-run-calculations/00000000-0000-0000-0000-000000000001", + "report", + ), ("/v2/me", "user_profile"), ("/v2/me/upgrade", "user_profile"), ("/us/policy/1", "policy"), diff --git a/tests/unit/v2/test_household_report_routes.py b/tests/unit/v2/test_household_report_routes.py index 1165a0018..a33e698f0 100644 --- a/tests/unit/v2/test_household_report_routes.py +++ b/tests/unit/v2/test_household_report_routes.py @@ -99,6 +99,7 @@ def household_report_read(**changes: Any) -> HouseholdReportRead: ), ), "failure": None, + "calculated_variables": None, **household_summary_fields(), **changes, } From f0d3e6a8caf1fa9d5bfda2ca0fc5c66469a34780 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 4 Dec 2026 02:29:59 +0400 Subject: [PATCH 06/12] Add tests for requesting extra calculations of a household run, which fail before the change POST /v2/reports/{report_id}/runs/{run_id}/household-calculations reads the household report in its country, refuses a failed run with 409, checks the listed variables, asks the simulation service for each side's calculation and answers 201 with both, read back from household_run_calculations. The generated-client tests also send a household report's and a re-run's list of variables through the generated request models. Co-Authored-By: Claude Opus 5.5 --- .../libs/test_simulation_generated_client.py | 129 ++++ ...t_simulation_household_run_calculations.py | 354 +++++++++ .../test_household_run_calculation_creates.py | 722 ++++++++++++++++++ tests/unit/v2/test_metadata_routes.py | 1 + 4 files changed, 1206 insertions(+) create mode 100644 tests/unit/libs/test_simulation_household_run_calculations.py create mode 100644 tests/unit/v2/test_household_run_calculation_creates.py diff --git a/tests/unit/libs/test_simulation_generated_client.py b/tests/unit/libs/test_simulation_generated_client.py index 05f4fb8b2..1baa5020b 100644 --- a/tests/unit/libs/test_simulation_generated_client.py +++ b/tests/unit/libs/test_simulation_generated_client.py @@ -63,6 +63,7 @@ from policyengine_api.request_context import _asgi_observability_id from policyengine_api.services.v2.household_calculations.types import ( HouseholdCalculationAccepted, + HouseholdCalculationAxis, InlineHouseholdCalculationInput, ) from policyengine_api.services.v2.simulation_service.types import ( @@ -637,6 +638,9 @@ def household_report_case(**changes: Any) -> ReportCase: baseline={"dynamic_id": str(DYNAMIC_ID)}, reform={"policy_id": str(POLICY_ID), "dynamic_id": str(OTHER_DYNAMIC_ID)}, ), + "a household report listing its variables": household_report_case( + variables=["household_net_income", "snap"] + ), } @@ -763,6 +767,10 @@ def test_report_answers_the_generated_parser_refuses_are_read( "with force": {"force": True}, "with cliffs": {"include_cliffs": True}, "with force and cliffs": {"force": True, "include_cliffs": True}, + "a household report's, listing its variables": { + "kind": "household", + "variables": ("household_net_income", "snap"), + }, } STARTED_RUN = StartedReportRun( report_run_id=UUID(RERUN_STARTED["report_run_id"]), @@ -929,3 +937,124 @@ def test_a_body_the_generated_model_would_change_is_not_sent( send(http_client, hand_built_body) assert service.requests == [] + + +# Extra calculations of a household report's run, as API v1 asks for them. +HOUSEHOLD_RUN_CALCULATION_CHANGES = { + "variables alone": {}, + "variables and axes": { + "axes": [ + [ + HouseholdCalculationAxis( + name="employment_income", count=3, min=0, max=90_000.5 + ) + ], + [ + HouseholdCalculationAxis( + name="age", count=2, min=20, max=60, period="2026", index=1 + ) + ], + ] + }, + "axes naming options as null": { + "axes": [ + [ + HouseholdCalculationAxis( + name="employment_income", + count=2, + min=0, + max=1, + period=None, + index=None, + ) + ] + ] + }, +} + + +@pytest.mark.parametrize("case", list(HOUSEHOLD_RUN_CALCULATION_CHANGES)) +def test_extra_calculations_are_sent_by_the_generated_operation(case: str) -> None: + # Imported here: the client release that adds the operation is pinned + # with the change these tests precede. + from policyengine_api.libs.simulation_household_run_calculations import ( + household_run_calculations_request, + ) + from policyengine_api_simulation_client.api.default import ( + create_household_run_calculations, + ) + from policyengine_api_simulation_client.models import ( + HouseholdRunCalculationRequest, + ) + + from tests.unit.libs.test_simulation_household_run_calculations import ( + CALCULATIONS_CREATED, + REFORM_CALCULATION_ID, + calculations_input, + created_calculations, + ) + + request = calculations_input(**HOUSEHOLD_RUN_CALCULATION_CHANGES[case]) + hand_built_body = household_run_calculations_request(request) + expected = generated_request( + create_household_run_calculations._get_kwargs( + request.report_id, + request.report_run_id, + body=HouseholdRunCalculationRequest.from_dict(hand_built_body), + ) + ) + service = ScriptedService(201, CALCULATIONS_CREATED) + + with pytest.MonkeyPatch.context() as patch: + serializations: list[Serialization] = [] + patch.setattr( + HouseholdRunCalculationRequest, + "to_dict", + _recording_to_dict(HouseholdRunCalculationRequest.to_dict, serializations), + ) + created = service.report_client().create_household_run_calculations(request) + + assert created == created_calculations(REFORM_CALCULATION_ID) + assert_sent_through_generated_operation( + service.sent_request(), + serializations, + expected=expected, + model_name="HouseholdRunCalculationRequest", + hand_built_body=hand_built_body, + ) + + +def test_an_extra_calculation_body_the_generated_model_would_change_is_not_sent() -> ( + None +): + # Imported here: the client release that adds the operation is pinned + # with the change these tests precede. + from policyengine_api.libs.simulation_household_run_calculations import ( + household_run_calculations_request, + ) + + from policyengine_api.libs.simulation_service_operations import ( + post_household_run_calculations, + ) + from tests.unit.libs.test_simulation_household_run_calculations import ( + calculations_input, + ) + + request = calculations_input() + service = ScriptedService(201, {}) + http_client = simulation_service_http_client( + transport=httpx.MockTransport(service.answer) + ) + + with pytest.raises(ValueError, match="field_the_model_lacks"): + post_household_run_calculations( + http_client, + request.report_id, + request.report_run_id, + { + **household_run_calculations_request(request), + "field_the_model_lacks": 1, + }, + ) + + assert service.requests == [] diff --git a/tests/unit/libs/test_simulation_household_run_calculations.py b/tests/unit/libs/test_simulation_household_run_calculations.py new file mode 100644 index 000000000..4425ef22e --- /dev/null +++ b/tests/unit/libs/test_simulation_household_run_calculations.py @@ -0,0 +1,354 @@ +"""Ask the simulation service for extra calculations of a household report's run. + +API v1 posts the variables, and any axes, to the simulation service's +``POST /reports/{report_id}/runs/{report_run_id}/household-calculations``. +The service finds each side's calculation of the same variables and axes +that hasn't failed, or creates and starts one, and answers 201 naming them. +These tests check the request and how each of the service's answers is read. +""" + +from __future__ import annotations + +import json +from typing import Any +from uuid import UUID + +import httpx +import pytest + +from policyengine_api.libs.simulation_reports import SimulationServiceReportClient +from policyengine_api.services.v2.household_calculations.types import ( + HouseholdCalculationAxis, +) +from policyengine_api.services.v2.simulation_service.types import ( + SimulationServiceAnswerUnreadableError, + SimulationServiceConflictError, + SimulationServiceInternalError, + SimulationServiceInvalidRequestError, + SimulationServiceUnavailableError, +) + +SIMULATION_URL = "https://simulation.example.test" +ENVIRONMENT_VARIABLES = ( + "GATEWAY_AUTH_ISSUER", + "GATEWAY_AUTH_AUDIENCE", + "GATEWAY_AUTH_CLIENT_ID", + "GATEWAY_AUTH_CLIENT_SECRET", + "GATEWAY_AUTH_CLIENT_SECRET_RESOURCE", + "GATEWAY_AUTH_REQUIRED", + "SIM_ENTRYPOINT", + "OLD_SIMULATION_GATEWAY_URL", + "SIMULATION_ENTRYPOINT_URL", +) +REPORT_ID = UUID("00000000-0000-0000-0000-00000000e001") +REPORT_RUN_ID = UUID("00000000-0000-0000-0000-00000000e002") +BASELINE_CALCULATION_ID = UUID("00000000-0000-0000-0000-00000000e003") +REFORM_CALCULATION_ID = UUID("00000000-0000-0000-0000-00000000e004") +OTHER_ID = UUID("00000000-0000-0000-0000-00000000e005") +VARIABLES = ("household_net_income", "marginal_tax_rate") +CALCULATIONS_PATH = f"/reports/{REPORT_ID}/runs/{REPORT_RUN_ID}/household-calculations" +# What the simulation service answers once it has found or created each side's +# calculation. +CALCULATIONS_CREATED = { + "report_id": str(REPORT_ID), + "report_run_id": str(REPORT_RUN_ID), + "baseline": { + "household_run_calculation_id": str(BASELINE_CALCULATION_ID), + "simulation_run_id": "00000000-0000-0000-0000-00000000e006", + "status": "pending", + }, + "reform": { + "household_run_calculation_id": str(REFORM_CALCULATION_ID), + "simulation_run_id": "00000000-0000-0000-0000-00000000e007", + "status": "succeeded", + }, +} +REQUEST_AGAIN = ( + "Request the same calculations again: an identical request finds those the " + "simulation service created, rather than starting more." +) + + +@pytest.fixture(autouse=True) +def configured_simulation_service(monkeypatch): + """Name the Cloud Run simulation service; set no gateway credentials.""" + for name in ENVIRONMENT_VARIABLES: + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("SIMULATION_ENTRYPOINT_URL", f"{SIMULATION_URL}/") + monkeypatch.setenv("SIM_ENTRYPOINT", "old_gateway_direct") + monkeypatch.setenv("OLD_SIMULATION_GATEWAY_URL", "https://old.example.test") + + +def calculations_input(**changes: Any) -> Any: + """Return extra calculations of the report run, of ``VARIABLES``.""" + # Imported here because the change these tests precede adds it. + from policyengine_api.services.v2.simulation_service.types import ( + HouseholdRunCalculationsInput, + ) + + values: dict[str, Any] = { + "country_id": "us", + "report_id": REPORT_ID, + "report_run_id": REPORT_RUN_ID, + "variables": VARIABLES, + "axes": None, + } + return HouseholdRunCalculationsInput(**{**values, **changes}) + + +def created_calculations(reform_calculation_id: UUID | None) -> Any: + # Imported here because the change these tests precede adds it. + from policyengine_api.services.v2.simulation_service.types import ( + CreatedHouseholdRunCalculations, + ) + + return CreatedHouseholdRunCalculations( + baseline_calculation_id=BASELINE_CALCULATION_ID, + reform_calculation_id=reform_calculation_id, + ) + + +class ScriptedService: + """The simulation service, answering every request with one scripted answer.""" + + def __init__( + self, status_code: int = 201, body: object = CALCULATIONS_CREATED + ) -> None: + self.status_code = status_code + self.body = body + self.requests: list[httpx.Request] = [] + + def answer(self, request: httpx.Request) -> httpx.Response: + self.requests.append(request) + if isinstance(self.body, bytes): + return httpx.Response(self.status_code, content=self.body) + return httpx.Response(self.status_code, json=self.body) + + def calculate(self, **changes: Any) -> Any: + client = SimulationServiceReportClient.from_environment( + transport=httpx.MockTransport(self.answer) + ) + return client.create_household_run_calculations(calculations_input(**changes)) + + +def test_the_variables_are_posted_to_the_runs_calculations_route() -> None: + service = ScriptedService() + + service.calculate() + + (request,) = service.requests + assert request.method == "POST" + assert str(request.url) == f"{SIMULATION_URL}{CALCULATIONS_PATH}" + assert json.loads(request.content) == {"variables": list(VARIABLES)} + + +def test_axes_are_sent_with_only_the_fields_the_caller_gave() -> None: + service = ScriptedService() + axes = [ + [HouseholdCalculationAxis(name="employment_income", count=3, min=0, max=9e4)], + [ + HouseholdCalculationAxis( + name="age", count=2, min=20, max=60, period="2026", index=1 + ) + ], + ] + + service.calculate(axes=axes) + + (request,) = service.requests + assert json.loads(request.content) == { + "variables": list(VARIABLES), + "axes": [ + [{"name": "employment_income", "count": 3, "min": 0, "max": 90000.0}], + [ + { + "name": "age", + "count": 2, + "min": 20, + "max": 60, + "period": "2026", + "index": 1, + } + ], + ], + } + + +def test_the_path_names_the_report_and_its_run() -> None: + # Imported here because the change these tests precede adds it. + from policyengine_api.libs.simulation_household_run_calculations import ( + household_run_calculations_path, + ) + + assert household_run_calculations_path(REPORT_ID, REPORT_RUN_ID) == ( + CALCULATIONS_PATH + ) + + +def test_the_answer_names_each_sides_calculation() -> None: + assert ScriptedService().calculate() == created_calculations(REFORM_CALCULATION_ID) + + +def test_a_report_of_the_baseline_alone_names_no_reform_calculation() -> None: + service = ScriptedService(body={**CALCULATIONS_CREATED, "reform": None}) + + assert service.calculate() == created_calculations(None) + + +@pytest.mark.parametrize( + "body", + [ + b"not json", + {"report_id": str(REPORT_ID), "report_run_id": str(REPORT_RUN_ID)}, + {**CALCULATIONS_CREATED, "report_id": str(OTHER_ID)}, + {**CALCULATIONS_CREATED, "report_run_id": str(OTHER_ID)}, + ], + ids=["not JSON", "no baseline", "another report", "another run"], +) +def test_a_created_answer_that_cannot_be_read_says_to_request_again( + body: object, +) -> None: + with pytest.raises(SimulationServiceAnswerUnreadableError) as raised: + ScriptedService(201, body).calculate() + + assert str(raised.value) == ( + "The simulation service answered that it found or created the extra " + f"calculations, but its answer could not be read. {REQUEST_AGAIN}" + ) + + +@pytest.mark.parametrize( + "code", + ["report_run_failed", "report_run_not_current", "rerun_not_supported"], +) +def test_a_conflict_is_passed_on_with_its_code_and_reason(code: str) -> None: + service = ScriptedService(409, {"code": code, "detail": "Re-run the report."}) + + with pytest.raises(SimulationServiceConflictError) as raised: + service.calculate() + + assert str(raised.value) == ( + "The simulation service will not calculate this run now " + f"({code}): Re-run the report." + ) + assert raised.value.run_id is None + + +def test_a_conflict_that_cannot_be_read_is_the_service_unavailable() -> None: + with pytest.raises(SimulationServiceUnavailableError) as raised: + ScriptedService(409, b"not json").calculate() + + assert str(raised.value) == "The simulation service answered 409 unreadably." + + +@pytest.mark.parametrize( + ("status_code", "body"), + [ + ( + 422, + { + "code": "household_calculations_not_available", + "detail": "Report is not a household report.", + }, + ), + (400, {"code": "unknown_dynamic", "detail": "Report is not a household."}), + ], + ids=["422", "400 naming a row the report names"], +) +def test_a_refusal_of_the_stored_report_is_an_invalid_request( + status_code: int, body: dict[str, str] +) -> None: + with pytest.raises(SimulationServiceInvalidRequestError) as raised: + ScriptedService(status_code, body).calculate() + + assert str(raised.value) == ( + f"The simulation service cannot calculate this run ({body['code']}): " + f"{body['detail']}" + ) + + +def test_a_refusal_of_the_services_own_state_is_the_service_unavailable() -> None: + service = ScriptedService( + 400, {"code": "unknown_catalog_version", "detail": "Not deployed."} + ) + + with pytest.raises(SimulationServiceUnavailableError) as raised: + service.calculate() + + assert str(raised.value) == ( + "The simulation service refused to calculate this run " + "(unknown_catalog_version): Not deployed." + ) + + +@pytest.mark.parametrize( + ("status_code", "body", "status_and_code"), + [ + ( + 503, + {"code": "manifest_unavailable", "detail": "x"}, + "503 manifest_unavailable", + ), + ( + 404, + {"code": "unknown_report_run", "detail": "x"}, + "404 unknown_report_run", + ), + (429, b"", "429"), + ], + ids=["readable 503", "404", "429"], +) +def test_an_answer_sent_before_anything_was_written_is_the_service_unavailable( + status_code: int, body: object, status_and_code: str +) -> None: + with pytest.raises(SimulationServiceUnavailableError) as raised: + ScriptedService(status_code, body).calculate() + + assert str(raised.value) == ( + f"The simulation service is unavailable ({status_and_code})." + ) + + +def test_its_failure_may_follow_created_calculations() -> None: + service = ScriptedService(500, {"code": "internal_error", "detail": "x"}) + + with pytest.raises(SimulationServiceInternalError) as raised: + service.calculate() + + assert str(raised.value) == ( + "The simulation service may have created the extra calculations, but it " + f"failed (500 internal_error). {REQUEST_AGAIN}" + ) + + +@pytest.mark.parametrize( + ("status_code", "body", "message"), + [ + ( + 502, + b"", + "The simulation service may have received the request, but its " + f"answer was lost (a proxy answered 502 in its place). {REQUEST_AGAIN}", + ), + ( + 503, + b"Service Unavailable", + "The simulation service may have created the extra calculations, but " + f"it failed (503). {REQUEST_AGAIN}", + ), + ( + 299, + b"", + "The simulation service may have created the extra calculations, but " + f"it failed (299). {REQUEST_AGAIN}", + ), + ], + ids=["a proxy's 502", "a front end's 503", "an unexpected status"], +) +def test_an_answer_that_may_follow_created_calculations_is_unreadable( + status_code: int, body: object, message: str +) -> None: + with pytest.raises(SimulationServiceAnswerUnreadableError) as raised: + ScriptedService(status_code, body).calculate() + + assert str(raised.value) == message diff --git a/tests/unit/v2/test_household_run_calculation_creates.py b/tests/unit/v2/test_household_run_calculation_creates.py new file mode 100644 index 000000000..a01add8c6 --- /dev/null +++ b/tests/unit/v2/test_household_run_calculation_creates.py @@ -0,0 +1,722 @@ +"""Request extra calculations of a household report's run. + +``POST /v2/reports/{report_id}/runs/{run_id}/household-calculations +?country_id=`` asks for more of a household report's run than it +calculated: the variables it lists, for each side's stored household as +entered or varied along axes. API v1 reads the report in its country and +checks it is a household report whose run hasn't failed, checks each +variable against the running catalog version, then asks the simulation +service, which finds each side's calculation of the same variables and axes +that hasn't failed, or creates and starts one. API v1 reads each back and +answers 201 with both, to follow with ``GET +/v2/household-run-calculations/{id}``. A failed run is refused with 409: run +the report again first. +""" + +from __future__ import annotations + +import hashlib +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any +from uuid import UUID, uuid4 + +import pytest + +from policyengine_api.data.v2.models import ( + HouseholdRunCalculation, + ReportRunStatus, + SimulationStatus, +) +from policyengine_api.services.v2.household_calculations.types import ( + HouseholdCalculationAxis, +) +from policyengine_api.services.v2.household_calculations.validators import ( + HouseholdCalculationCountryError, + HouseholdCalculationStorageError, + HouseholdCalculationVariablesUnknownError, +) +from policyengine_api.services.v2.simulation_service.services import ( + SimulationSubmissionService, +) +from policyengine_api.services.v2.simulation_service.types import ( + SimulationServiceConflictError, + SimulationServiceInternalError, + SimulationServiceInvalidRequestError, + SimulationServiceUnavailableError, +) +from policyengine_api.services.v2.simulation_service.validators import ( + SubmissionStorageError, +) +from policyengine_api.services.v2.stored_reports.validators import ( + ReportRunNotFoundError, + StoredReportNotFoundError, +) +from tests.unit.v2.test_household_report_reads import ( + RunToStore, + sessions, # noqa: F401 # the fixture the service tests use + store_economy_report, + store_household_report, +) +from tests.unit.v2.test_household_report_submissions import ( + StoredHouseholds, + unconfigured_client, +) +from tests.unit.v2.test_household_report_variables import RunningCatalogVariables +from tests.unit.v2.test_household_run_calculation_reads import ( + CALCULATION_ID, + EARNINGS_VARIATION, + VARIABLES, + calculation_read, + calculation_route_client, +) +from tests.unit.v2.test_simulation_submissions import ( + HOUSEHOLD_ONLY_UK, + SERVED_COUNTRIES, + StoredCountries, + StoredDynamics, + StoredPolicies, +) + +if TYPE_CHECKING: + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + from tests.unit.v2.test_household_report_reads import StoredHouseholdReport + +REPORT_ID = UUID("00000000-0000-0000-0000-00000000f001") +RUN_ID = UUID("00000000-0000-0000-0000-00000000f002") +REFORM_CALCULATION_ID = UUID("00000000-0000-0000-0000-00000000f003") +UNKNOWN_ID = UUID("00000000-0000-0000-0000-00000000f004") +CALCULATIONS = ( + f"/v2/reports/{REPORT_ID}/runs/{RUN_ID}/household-calculations?country_id=us" +) +CALCULATIONS_PATH = "/v2/reports/{report_id}/runs/{run_id}/household-calculations" +ONE_MEBIBYTE = 1024 * 1024 + + +def _types() -> Any: + # Imported here because the change these tests precede adds them. + from policyengine_api.services.v2.household_run_calculations import types + + return types + + +def _validators() -> Any: + # Imported here because the change these tests precede adds them. + from policyengine_api.services.v2.household_run_calculations import validators + + return validators + + +def _calculations_input(**changes: Any) -> Any: + # Imported here because the change these tests precede adds it. + from policyengine_api.services.v2.simulation_service.types import ( + HouseholdRunCalculationsInput, + ) + + values: dict[str, Any] = { + "country_id": "us", + "report_id": REPORT_ID, + "report_run_id": RUN_ID, + "variables": tuple(VARIABLES), + "axes": None, + } + return HouseholdRunCalculationsInput(**{**values, **changes}) + + +def _created(baseline_id: UUID, reform_id: UUID | None) -> Any: + # Imported here because the change these tests precede adds it. + from policyengine_api.services.v2.simulation_service.types import ( + CreatedHouseholdRunCalculations, + ) + + return CreatedHouseholdRunCalculations( + baseline_calculation_id=baseline_id, reform_calculation_id=reform_id + ) + + +def _insert_calculation( + session: Session, *, simulation_run_id: UUID, simulation_id: UUID, axes: Any +) -> UUID: + """Insert a pending extra calculation of the run, as the service inserts one.""" + calculation = HouseholdRunCalculation( + simulation_run_id=simulation_run_id, + simulation_id=simulation_id, + variables=sorted(VARIABLES), + axes=axes, + key_version=1, + calculation_key=hashlib.sha256(uuid4().bytes).hexdigest(), + status=SimulationStatus.PENDING, + ) + session.add(calculation) + session.commit() + return calculation.id + + +@dataclass +class CalculatingService: + """The simulation service's client: inserts each side's calculation, recording it. + + It inserts a pending calculation of each side's simulation run of the + stored report, as the simulation service does, and names them; with + ``insert`` false it names calculations that don't exist. With ``error`` + it raises that instead. + """ + + sessions: sessionmaker[Session] + stored: StoredHouseholdReport + insert: bool = True + error: Exception | None = None + requests: list[Any] = field(default_factory=list) + + def create_household_run_calculations(self, request: Any) -> Any: + self.requests.append(request) + if self.error is not None: + raise self.error + if not self.insert: + return _created(UNKNOWN_ID, None) + axes = ( + None + if request.axes is None + else [ + [axis.model_dump(mode="json", exclude_unset=True) for axis in group] + for group in request.axes + ] + ) + stored = self.stored + assert stored.baseline_run_id is not None + with self.sessions() as session: + baseline_id = _insert_calculation( + session, + simulation_run_id=stored.baseline_run_id, + simulation_id=stored.baseline_simulation_id, + axes=axes, + ) + reform_id = None + if stored.reform_run_id is not None: + assert stored.reform_simulation_id is not None + reform_id = _insert_calculation( + session, + simulation_run_id=stored.reform_run_id, + simulation_id=stored.reform_simulation_id, + axes=axes, + ) + return _created(baseline_id, reform_id) + + +def _service(session_factory: sessionmaker[Session], submissions: Any) -> Any: + # Imported here because the change these tests precede adds the submissions. + from policyengine_api.services.v2.household_run_calculations.database_session import ( # noqa: E501 # a module path can't be split across lines + HouseholdRunCalculationDatabaseSession, + ) + from policyengine_api.services.v2.household_run_calculations.services import ( + V2HouseholdRunCalculationService, + ) + + return V2HouseholdRunCalculationService( + HouseholdRunCalculationDatabaseSession(session_factory), + submissions=submissions, + ) + + +def _store( + session_factory: sessionmaker[Session], + *, + status: ReportRunStatus = ReportRunStatus.RUNNING, + with_reform: bool = True, +) -> StoredHouseholdReport: + with session_factory() as session: + return store_household_report( + session, with_reform=with_reform, run=RunToStore(status=status) + ) + + +def _create(service: Any, stored: StoredHouseholdReport, **changes: Any) -> Any: + assert stored.report_run_id is not None + arguments: dict[str, Any] = { + "country_id": "us", + "report_id": stored.report_id, + "run_id": stored.report_run_id, + "variables": VARIABLES, + "axes": None, + **changes, + } + return service.create_calculations(**arguments) + + +@pytest.mark.parametrize( + "status", + [ReportRunStatus.PENDING, ReportRunStatus.RUNNING, ReportRunStatus.SUCCEEDED], +) +def test_each_sides_calculation_is_created_then_read( + sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above + status: ReportRunStatus, +) -> None: + stored = _store(sessions, status=status) + calculating = CalculatingService(sessions, stored) + + created = _create(_service(sessions, calculating), stored) + + assert created.baseline.status == "pending" + assert created.baseline.variables == tuple(sorted(VARIABLES)) + assert created.baseline.axes is None + assert created.baseline.result is None + assert created.reform is not None + assert created.reform.id != created.baseline.id + assert created.reform.status == "pending" + + +def test_the_simulation_service_is_asked_for_the_runs_variables_and_axes( + sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above +) -> None: + stored = _store(sessions) + calculating = CalculatingService(sessions, stored) + axes = [[HouseholdCalculationAxis(**EARNINGS_VARIATION[0][0])]] + + created = _create(_service(sessions, calculating), stored, axes=axes) + + assert calculating.requests == [ + _calculations_input( + report_id=stored.report_id, + report_run_id=stored.report_run_id, + axes=axes, + ) + ] + assert created.baseline.axes == EARNINGS_VARIATION + + +def test_a_report_of_the_baseline_alone_has_no_reform_calculation( + sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above +) -> None: + stored = _store(sessions, with_reform=False) + + created = _create(_service(sessions, CalculatingService(sessions, stored)), stored) + + assert created.reform is None + + +def test_a_failed_run_is_refused_before_the_simulation_service_is_asked( + sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above +) -> None: + stored = _store(sessions, status=ReportRunStatus.FAILED) + calculating = CalculatingService(sessions, stored) + + with pytest.raises(_validators().ReportRunFailedError) as refused: + _create(_service(sessions, calculating), stored) + + assert str(refused.value) == ( + f"Report run {stored.report_run_id} failed. Run the report again, then " + "request the calculations of its new run." + ) + assert calculating.requests == [] + + +@pytest.mark.parametrize( + ("changes", "error_type"), + [ + ({"report_id": UNKNOWN_ID}, StoredReportNotFoundError), + ({"country_id": "uk"}, StoredReportNotFoundError), + ({"run_id": UNKNOWN_ID}, ReportRunNotFoundError), + ], + ids=["unknown report", "report of another country", "unknown run"], +) +def test_an_unknown_report_or_run_is_not_found( + sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above + changes: dict[str, Any], + error_type: type[Exception], +) -> None: + stored = _store(sessions) + calculating = CalculatingService(sessions, stored) + + with pytest.raises(error_type): + _create(_service(sessions, calculating), stored, **changes) + + assert calculating.requests == [] + + +def test_a_run_of_another_report_is_not_found( + sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above +) -> None: + stored = _store(sessions) + with sessions() as session: + other = store_household_report( + session, country="uk", run=RunToStore(status=ReportRunStatus.RUNNING) + ) + calculating = CalculatingService(sessions, stored) + + with pytest.raises(ReportRunNotFoundError): + _create(_service(sessions, calculating), stored, run_id=other.report_run_id) + + assert calculating.requests == [] + + +def test_an_economy_report_has_no_extra_calculations( + sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above +) -> None: + stored = _store(sessions) + with sessions() as session: + economy_report_id = store_economy_report(session) + calculating = CalculatingService(sessions, stored) + + with pytest.raises(_validators().HouseholdCalculationsNotAvailableError) as refused: + _create(_service(sessions, calculating), stored, report_id=economy_report_id) + + assert str(refused.value) == ( + "Only a household report's runs have extra calculations; report " + f"{economy_report_id} is not a household report." + ) + assert calculating.requests == [] + + +def test_calculations_that_cannot_be_read_back_are_named( + sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above +) -> None: + stored = _store(sessions) + calculating = CalculatingService(sessions, stored, insert=False) + + with pytest.raises(_validators().HouseholdRunCalculationsUnreadableError) as failed: + _create(_service(sessions, calculating), stored) + + assert failed.value.baseline_calculation_id == UNKNOWN_ID + assert failed.value.reform_calculation_id is None + assert failed.value.country_id == "us" + + +def test_without_the_simulation_service_nothing_is_created( + sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above +) -> None: + stored = _store(sessions) + + with pytest.raises(SimulationServiceUnavailableError): + _create(_service(sessions, None), stored) + + +@dataclass +class RecordingCalculations: + """The simulation service's client, recording each request it is sent.""" + + requests: list[Any] = field(default_factory=list) + + def create_household_run_calculations(self, request: Any) -> Any: + self.requests.append(request) + return _created(CALCULATION_ID, REFORM_CALCULATION_ID) + + +def _submissions( + client_factory: Any, + variables: RunningCatalogVariables, + *, + countries: StoredCountries | None = None, +) -> SimulationSubmissionService: + return SimulationSubmissionService( + countries=countries or StoredCountries(countries=SERVED_COUNTRIES), + households=StoredHouseholds(), + policies=StoredPolicies(), + dynamics=StoredDynamics(), + variables=variables, + client_factory=client_factory, + ) + + +def test_the_variables_are_checked_then_sent() -> None: + client = RecordingCalculations() + variables = RunningCatalogVariables(known=frozenset(VARIABLES)) + request = _calculations_input() + + created = _submissions(lambda: client, variables).create_household_run_calculations( + request + ) + + assert variables.checked == [("us", tuple(VARIABLES))] + assert client.requests == [request] + assert created == _created(CALCULATION_ID, REFORM_CALCULATION_ID) + + +def test_unknown_variables_are_refused_by_name_unsent() -> None: + variables = RunningCatalogVariables(known=frozenset(VARIABLES)) + + with pytest.raises(HouseholdCalculationVariablesUnknownError) as refused: + _submissions(unconfigured_client, variables).create_household_run_calculations( + _calculations_input(variables=(*VARIABLES, "snep")) + ) + + assert refused.value.unknown_variables == ("snep",) + + +def test_a_country_without_household_calculations_is_refused_unsent() -> None: + countries = StoredCountries( + countries=[country for country in HOUSEHOLD_ONLY_UK if country.id != "us"] + ) + + with pytest.raises(HouseholdCalculationCountryError): + _submissions( + unconfigured_client, RunningCatalogVariables(), countries=countries + ).create_household_run_calculations(_calculations_input()) + + +def test_a_variable_check_that_cannot_read_storage_is_a_storage_failure() -> None: + variables = RunningCatalogVariables( + error=HouseholdCalculationStorageError("catalog unavailable") + ) + + with pytest.raises(SubmissionStorageError): + _submissions(unconfigured_client, variables).create_household_run_calculations( + _calculations_input() + ) + + +@dataclass +class FakeCalculationCreates: + """Answer each request with ``created`` or raise ``error``, recording it.""" + + created: Any = None + error: Exception | None = None + requests: list[dict[str, Any]] = field(default_factory=list) + + def create_calculations(self, **arguments: Any) -> Any: + self.requests.append(arguments) + if self.error is not None: + raise self.error + return self.created + + +def _created_reads(*, with_reform: bool = True) -> Any: + return _types().HouseholdRunCalculationsRead( + baseline=calculation_read(status="pending", result=None, completed_at=None), + reform=( + calculation_read( + id=REFORM_CALCULATION_ID, + status="pending", + result=None, + completed_at=None, + ) + if with_reform + else None + ), + ) + + +def _item(calculation_id: UUID) -> dict[str, Any]: + return { + "id": str(calculation_id), + "status": "pending", + "variables": VARIABLES, + "axes": EARNINGS_VARIATION, + "result": None, + "error_message": None, + "created_at": "2026-12-04T09:00:00Z", + "completed_at": None, + } + + +def test_requesting_calculations_answers_201_with_each_side() -> None: + service = FakeCalculationCreates(created=_created_reads()) + + response = calculation_route_client(service).post( + CALCULATIONS, json={"variables": VARIABLES, "axes": EARNINGS_VARIATION} + ) + + assert response.status_code == 201, response.text + assert response.json() == { + "status": "ok", + "message": None, + "result": { + "baseline": _item(CALCULATION_ID), + "reform": _item(REFORM_CALCULATION_ID), + }, + } + (request,) = service.requests + assert request == { + "country_id": "us", + "report_id": REPORT_ID, + "run_id": RUN_ID, + "variables": VARIABLES, + "axes": [[HouseholdCalculationAxis(**EARNINGS_VARIATION[0][0])]], + } + + +def test_a_report_of_the_baseline_alone_answers_a_null_reform() -> None: + service = FakeCalculationCreates(created=_created_reads(with_reform=False)) + + response = calculation_route_client(service).post( + CALCULATIONS, json={"variables": VARIABLES} + ) + + assert response.status_code == 201, response.text + assert response.json()["result"]["reform"] is None + assert service.requests[0]["axes"] is None + + +@pytest.mark.parametrize( + "body", + [ + {}, + {"variables": []}, + {"variables": ["snap", "snap"]}, + {"variables": ["snap"], "add_missing_variables": True}, + { + "variables": ["snap"], + "axes": [ + [ + {"name": "employment_income", "count": 2, "min": 0, "max": 1}, + {"name": "age", "count": 3, "min": 20, "max": 60}, + ] + ], + }, + { + "variables": ["snap"], + "axes": [ + [{"name": "employment_income", "count": 101, "min": 0, "max": 1}], + [{"name": "age", "count": 100, "min": 20, "max": 60}], + ], + }, + ], + ids=[ + "no variables", + "an empty list", + "a variable listed twice", + "a field the route doesn't take", + "a group of uneven point counts", + "a grid of too many points", + ], +) +def test_a_body_the_route_cannot_take_is_refused_unsent(body: dict[str, Any]) -> None: + service = FakeCalculationCreates(created=_created_reads()) + + response = calculation_route_client(service).post(CALCULATIONS, json=body) + + assert response.status_code == 422, response.text + assert service.requests == [] + + +def test_a_body_over_1_mib_is_refused() -> None: + service = FakeCalculationCreates(created=_created_reads()) + padding = "x" * ONE_MEBIBYTE + + response = calculation_route_client(service).post( + CALCULATIONS, json={"variables": [padding]} + ) + + assert response.status_code == 413 + assert service.requests == [] + + +def test_a_request_naming_no_country_is_refused() -> None: + service = FakeCalculationCreates(created=_created_reads()) + + response = calculation_route_client(service).post( + CALCULATIONS.split("?", 1)[0], json={"variables": VARIABLES} + ) + + assert response.status_code == 422 + assert service.requests == [] + + +def _refusal(name: str) -> Exception: + """Return the error the service raises for the refusal ``name``.""" + errors: dict[str, Any] = { + "unknown report": lambda: StoredReportNotFoundError("Report not found"), + "unknown run": lambda: ReportRunNotFoundError("Run not found"), + "not a household report": lambda: ( + _validators().HouseholdCalculationsNotAvailableError("Not a household") + ), + "failed run": lambda: _validators().ReportRunFailedError("The run failed"), + "the service's conflict": lambda: SimulationServiceConflictError("Not now"), + "the service's refusal": lambda: SimulationServiceInvalidRequestError("No"), + "no household calculations": lambda: HouseholdCalculationCountryError("No"), + "the service unavailable": lambda: SimulationServiceUnavailableError("Down"), + "the service failed": lambda: SimulationServiceInternalError("Failed"), + "storage": lambda: _validators().HouseholdRunCalculationStorageError("x"), + "submission storage": lambda: SubmissionStorageError("x"), + } + return errors[name]() + + +@pytest.mark.parametrize( + ("refusal", "status_code"), + [ + ("unknown report", 404), + ("unknown run", 404), + ("not a household report", 422), + ("failed run", 409), + ("the service's conflict", 409), + ("the service's refusal", 422), + ("no household calculations", 422), + ("the service unavailable", 503), + ("the service failed", 502), + ("storage", 503), + ("submission storage", 503), + ], +) +def test_each_refusal_answers_its_status(refusal: str, status_code: int) -> None: + service = FakeCalculationCreates(error=_refusal(refusal)) + + response = calculation_route_client(service).post( + CALCULATIONS, json={"variables": VARIABLES} + ) + + assert response.status_code == status_code, response.text + assert response.json()["status"] == "error" + + +def test_unknown_variables_answer_422_naming_them() -> None: + service = FakeCalculationCreates( + error=HouseholdCalculationVariablesUnknownError(("snep",)) + ) + + response = calculation_route_client(service).post( + CALCULATIONS, json={"variables": ["snep"]} + ) + + assert response.status_code == 422 + body = response.json() + assert body["code"] == "unknown_variables" + assert body["unknown_variables"] == ["snep"] + + +def test_calculations_that_cannot_be_read_back_answer_502_naming_them() -> None: + service = FakeCalculationCreates( + error=_validators().HouseholdRunCalculationsUnreadableError( + country_id="us", + report_id=REPORT_ID, + run_id=RUN_ID, + baseline_calculation_id=CALCULATION_ID, + reform_calculation_id=REFORM_CALCULATION_ID, + ) + ) + + response = calculation_route_client(service).post( + CALCULATIONS, json={"variables": VARIABLES} + ) + + assert response.status_code == 502 + assert response.json() == { + "status": "error", + "message": ( + "The simulation service created the extra calculations of report " + f"{REPORT_ID}'s run {RUN_ID}, but they could not be read back. Read " + f"them with GET /v2/household-run-calculations/{CALCULATION_ID}" + "?country_id=us and GET /v2/household-run-calculations/" + f"{REFORM_CALCULATION_ID}?country_id=us rather than requesting them " + "again." + ), + "baseline_calculation_id": str(CALCULATION_ID), + "reform_calculation_id": str(REFORM_CALCULATION_ID), + } + + +def test_the_openapi_document_describes_the_request() -> None: + document = calculation_route_client().get("/v2/openapi.json").json() + schemas = document["components"]["schemas"] + + create = document["paths"][CALCULATIONS_PATH]["post"] + assert {"201", "404", "409", "413", "422", "502", "503"} <= set(create["responses"]) + success = create["responses"]["201"]["content"]["application/json"]["schema"] + result_name = success["$ref"].rsplit("/", 1)[-1] + assert result_name == "HouseholdRunCalculationsCreatedResponse" + body = create["requestBody"]["content"]["application/json"]["schema"] + request = schemas[body["$ref"].rsplit("/", 1)[-1]] + assert request["required"] == ["variables"] + assert request["properties"]["variables"]["minItems"] == 1 + assert set(request["properties"]) == {"variables", "axes"} + assert request["additionalProperties"] is False diff --git a/tests/unit/v2/test_metadata_routes.py b/tests/unit/v2/test_metadata_routes.py index 7ade5daf6..d49ced8c4 100644 --- a/tests/unit/v2/test_metadata_routes.py +++ b/tests/unit/v2/test_metadata_routes.py @@ -349,6 +349,7 @@ def test_openapi_references_explicit_resource_response_schemas() -> None: "/v2/reports", "/v2/reports/{report_id}", "/v2/reports/{report_id}/runs", + "/v2/reports/{report_id}/runs/{run_id}/household-calculations", "/v2/simulations", "/v2/simulations/{simulation_id}", "/v2/user-dynamics", From 65a9632dc3baead9a05877d6e37d99e42521e9a5 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 4 Dec 2026 02:35:50 +0400 Subject: [PATCH 07/12] Request extra calculations of a household report's run POST /v2/reports/{report_id}/runs/{run_id}/household-calculations?country_id= reads the report and run in the country, refuses another kind of report (422), an unknown report or run (404) and a failed run (409), checks the country and each listed variable, then asks the simulation service's new route through the generated client. The service finds each side's calculation of the same variables and axes that hasn't failed, or creates and starts one; API v1 reads both back and answers 201. Calculations that cannot be read back answer 502 naming each, and the simulation service's answers are read as for a re-run. The generated client's create_household_run_calculations operation comes with the simulation service release that adds the route, so this change needs the client pin raised to that release before it can merge. Co-Authored-By: Claude Opus 5.5 --- docs/engineering/migration-contracts.md | 3 +- docs/generated/migration_contracts.json | 18 +- .../fastapi_routes/dependencies.py | 3 +- .../resource_service_protocols.py | 18 ++ .../request_models.py | 25 ++ .../response_models.py | 91 +++++- .../v2/household_run_calculations/routes.py | 175 ++++++++++- .../libs/simulation_household_calculations.py | 10 +- .../simulation_household_run_calculations.py | 293 ++++++++++++++++++ policyengine_api/libs/simulation_reports.py | 27 +- .../libs/simulation_service_operations.py | 26 ++ .../v2/household_calculations/types.py | 36 ++- .../database_connectors/reads.py | 26 ++ .../v2/household_run_calculations/services.py | 162 +++++++++- .../v2/household_run_calculations/types.py | 12 + .../household_run_calculations/validators.py | 99 +++++- .../v2/simulation_service/services.py | 30 ++ .../services/v2/simulation_service/types.py | 69 ++++- tests/contract/registry.py | 18 ++ 19 files changed, 1098 insertions(+), 43 deletions(-) create mode 100644 policyengine_api/fastapi_routes/v2/household_run_calculations/request_models.py create mode 100644 policyengine_api/libs/simulation_household_run_calculations.py diff --git a/docs/engineering/migration-contracts.md b/docs/engineering/migration-contracts.md index 7a25e98e4..ecf61beea 100644 --- a/docs/engineering/migration-contracts.md +++ b/docs/engineering/migration-contracts.md @@ -8,7 +8,7 @@ Generated from `policyengine_api/migration_registry.py` and `tests/contract/regi | --- | ---: | | route group count | 9 | | workflow count | 20 | -| request count | 120 | +| request count | 121 | | db entity count | 6 | | sim flow count | 3 | @@ -239,6 +239,7 @@ Generated from `policyengine_api/migration_registry.py` and `tests/contract/regi | `GET` | `/v2/reports/{report_id}?country_id=us` | 200 | `report` | none | `status`, `message`, `result.item.id`, `result.item.kind`, `result.item.status`, `result.item.run`, `result.item.current_versions`, `result.item.result` | | `POST` | `/v2/reports/{report_id}/runs?country_id=us` | 201 | `report` | none | `status`, `message`, `result.item.id`, `result.item.status`, `result.item.run`, `result.item.current_versions` | | `GET` | `/v2/reports/{report_id}/runs?country_id=us` | 200 | `report` | none | `status`, `message`, `result.report_id`, `result.kind`, `result.items`, `result.current_versions` | +| `POST` | `/v2/reports/{report_id}/runs/{run_id}/household-calculations?country_id=us` | 201 | `report` | none | `status`, `message`, `result.baseline.id`, `result.baseline.status`, `result.baseline.variables`, `result.baseline.axes`, `result.reform` | | `GET` | `/v2/household-run-calculations/{calculation_id}?country_id=us` | 200 | `report` | none | `status`, `message`, `result.item.id`, `result.item.status`, `result.item.variables`, `result.item.axes`, `result.item.result`, `result.item.error_message`, `result.item.created_at`, `result.item.completed_at` | | `POST` | `/v2/simulations?country_id=us` | 201 | `simulation` | none | `status`, `message`, `result.item.id`, `result.item.kind`, `result.item.status`, `result.item.run` | | `GET` | `/v2/simulations/{simulation_id}?country_id=us` | 200 | `simulation` | none | `status`, `message`, `result.item.id`, `result.item.status`, `result.item.run`, `result.item.current_versions` | diff --git a/docs/generated/migration_contracts.json b/docs/generated/migration_contracts.json index 104c0bf96..4a78e52b2 100644 --- a/docs/generated/migration_contracts.json +++ b/docs/generated/migration_contracts.json @@ -1,7 +1,7 @@ { "metadata": { "db_entity_count": 6, - "request_count": 120, + "request_count": 121, "route_group_count": 9, "sim_flow_count": 3, "workflow_count": 20 @@ -1723,6 +1723,22 @@ "result.current_versions" ] }, + { + "expected_status": 201, + "headers": [], + "method": "POST", + "path": "/v2/reports/{report_id}/runs/{run_id}/household-calculations?country_id=us", + "route_group": "report", + "stable_response_fields": [ + "status", + "message", + "result.baseline.id", + "result.baseline.status", + "result.baseline.variables", + "result.baseline.axes", + "result.reform" + ] + }, { "expected_status": 200, "headers": [], diff --git a/policyengine_api/fastapi_routes/dependencies.py b/policyengine_api/fastapi_routes/dependencies.py index b0df900b8..a7753cdbc 100644 --- a/policyengine_api/fastapi_routes/dependencies.py +++ b/policyengine_api/fastapi_routes/dependencies.py @@ -243,7 +243,8 @@ def _default_v2_household_run_calculation_service_factory() -> ( ) return V2HouseholdRunCalculationService( - HouseholdRunCalculationDatabaseSession(get_v2_session_factory()) + HouseholdRunCalculationDatabaseSession(get_v2_session_factory()), + submissions=_default_simulation_submissions(), ) diff --git a/policyengine_api/fastapi_routes/resource_service_protocols.py b/policyengine_api/fastapi_routes/resource_service_protocols.py index 1c912b16e..fb072a185 100644 --- a/policyengine_api/fastapi_routes/resource_service_protocols.py +++ b/policyengine_api/fastapi_routes/resource_service_protocols.py @@ -24,12 +24,14 @@ NativeDynamicCreationInput, ) from policyengine_api.services.v2.household_calculations.types import ( + HouseholdCalculationAxis, HouseholdCalculationRead, HouseholdCalculationSubmission, HouseholdCalculationSubmitted, ) from policyengine_api.services.v2.household_run_calculations.types import ( HouseholdRunCalculationRead, + HouseholdRunCalculationsRead, ) from policyengine_api.services.v2.households.types import ( HouseholdPage, @@ -251,6 +253,22 @@ def get_calculation( """ ... + def create_calculations( + self, + *, + country_id: str, + report_id: UUID, + run_id: UUID, + variables: Sequence[str], + axes: list[list[HouseholdCalculationAxis]] | None, + ) -> HouseholdRunCalculationsRead: + """Request each side's extra calculation of the country's household report run. + + Return both, read back by ID. Raise the errors + ``V2HouseholdRunCalculationService.create_calculations`` lists. + """ + ... + class V2StoredReportResourceService(Protocol): """Route-independent report operations for one request.""" diff --git a/policyengine_api/fastapi_routes/v2/household_run_calculations/request_models.py b/policyengine_api/fastapi_routes/v2/household_run_calculations/request_models.py new file mode 100644 index 000000000..499a9efd8 --- /dev/null +++ b/policyengine_api/fastapi_routes/v2/household_run_calculations/request_models.py @@ -0,0 +1,25 @@ +"""Strict HTTP request model for extra calculations of household report runs.""" + +from __future__ import annotations + +from policyengine_api.services.v2.household_calculations.types import ( + AxisGroups, + NonEmptyVariableNames, + StrictCalculationModel, +) + + +class HouseholdRunCalculationsRequest(StrictCalculationModel): + """The variables to calculate on each side of a household report's run. + + ``variables`` lists 1 to 10,000 distinct names of 1 to 255 characters, + each a variable of the running catalog version. ``axes`` varies the + stored household's inputs across points, as ``/v2/household-calculations`` + takes axes for a stored household: the axes of one group vary together, + so they share one point count, and the groups form a grid of at most + 10,000 points. Without ``axes``, or with null, the household is + calculated as stored. No other field is accepted. + """ + + variables: NonEmptyVariableNames + axes: AxisGroups | None = None diff --git a/policyengine_api/fastapi_routes/v2/household_run_calculations/response_models.py b/policyengine_api/fastapi_routes/v2/household_run_calculations/response_models.py index bb00360b0..40dfe148f 100644 --- a/policyengine_api/fastapi_routes/v2/household_run_calculations/response_models.py +++ b/policyengine_api/fastapi_routes/v2/household_run_calculations/response_models.py @@ -8,7 +8,10 @@ from pydantic import JsonValue -from policyengine_api.fastapi_routes.v2.errors_support import V2ErrorResponse +from policyengine_api.fastapi_routes.v2.errors_support import ( + V2ErrorResponse, + V2UnknownVariablesErrorResponse, +) from policyengine_api.fastapi_routes.v2.household_calculations.response_models import ( HouseholdCalculationOutputItem, HouseholdCalculationSuccessResponse, @@ -65,6 +68,35 @@ class HouseholdRunCalculationResponse( """Success response holding one extra calculation.""" +class HouseholdRunCalculationsCreatedResult(StrictHouseholdCalculationAPIModel): + """Each side's extra calculation of a household report's run. + + ``reform`` is null for a report of the baseline alone. A report comparing + a policy with itself names one calculation on both sides. + """ + + baseline: HouseholdRunCalculationItem + reform: HouseholdRunCalculationItem | None + + +class HouseholdRunCalculationsCreatedResponse( + HouseholdCalculationSuccessResponse[HouseholdRunCalculationsCreatedResult] +): + """Success response holding each side's extra calculation.""" + + +class HouseholdRunCalculationsUnreadableResponse(V2ErrorResponse): + """The 502 answer when the calculations exist but can't be read back. + + The caller reads each with ``GET + /v2/household-run-calculations/{id}`` rather than requesting them again. + ``reform_calculation_id`` is null for a report of the baseline alone. + """ + + baseline_calculation_id: UUID + reform_calculation_id: UUID | None + + HOUSEHOLD_RUN_CALCULATION_READ_RESPONSES: dict[int | str, dict[str, Any]] = { 404: { "model": V2ErrorResponse, @@ -88,3 +120,60 @@ class HouseholdRunCalculationResponse( "description": "The v2 database is not configured or cannot be read.", }, } +HOUSEHOLD_RUN_CALCULATIONS_CREATE_RESPONSES: dict[int | str, dict[str, Any]] = { + 404: { + "model": V2ErrorResponse, + "description": ( + "No report has this ID in this country, or the report has no run " + "of that ID." + ), + }, + 409: { + "model": V2ErrorResponse, + "description": ( + "The run failed, or the simulation service will not calculate it " + "now: the run calculated on other versions than its default " + "worker's (report_run_not_current), or the stored report lacks a " + "row its runs calculate on (rerun_not_supported). Run the report " + "again, then request the calculations of its new run. Nothing was " + "started." + ), + }, + 413: { + "model": V2ErrorResponse, + "description": "The request body exceeds 1 MiB.", + }, + 422: { + "model": V2UnknownVariablesErrorResponse | V2ErrorResponse, + "description": ( + "The request does not match the schema (such as an empty list of " + "variables, one naming a variable twice, or axes of one group with " + "different point counts); the report is not a household report; " + "the country has no household calculations; the list names " + "variables the running catalog version does not have (code " + "unknown_variables, which names them); or the simulation service " + "cannot calculate the stored household or policies, with its code " + "and reason." + ), + }, + 502: { + "model": V2ErrorResponse | HouseholdRunCalculationsUnreadableResponse, + "description": ( + "The simulation service may have created the calculations, but its " + "answer does not say so: its answer was lost, a proxy answered in " + "its place, it failed (500), or it answered in a shape or status " + "API v1 does not expect. Request the same calculations " + "again: an identical request finds those it created. Or it created " + "them, but they cannot be read back: the answer names each, to read " + "with GET /v2/household-run-calculations/{id}." + ), + }, + 503: { + "model": V2ErrorResponse, + "description": ( + "The simulation service is not configured or unavailable, and " + "started nothing; or the v2 database is not configured or cannot " + "be read." + ), + }, +} diff --git a/policyengine_api/fastapi_routes/v2/household_run_calculations/routes.py b/policyengine_api/fastapi_routes/v2/household_run_calculations/routes.py index 1231490d7..d3276af52 100644 --- a/policyengine_api/fastapi_routes/v2/household_run_calculations/routes.py +++ b/policyengine_api/fastapi_routes/v2/household_run_calculations/routes.py @@ -1,10 +1,13 @@ -"""Native FastAPI route reading extra calculations of household report runs. +"""Native FastAPI routes requesting and reading extra calculations of household runs. An extra calculation calculates more of one side of a household report's run, such as ``marginal_tax_rate`` or an earnings variation. The simulation service inserts it in ``household_run_calculations`` and its household function completes it; reading one reads the row and never calls the -simulation service. No account is needed, as for reading a report. +simulation service. Requesting them checks the report, its run and the +variables listed, then asks the simulation service for each side's +calculation, which it finds or creates and starts. No account is needed, +as for reading or running a report; nothing is recorded for a user. """ from __future__ import annotations @@ -24,17 +27,43 @@ V2ErrorMapping, run_v2_operation, ) +from policyengine_api.fastapi_routes.v2.household_run_calculations.request_models import ( # noqa: E501 # a module path can't be split across lines + HouseholdRunCalculationsRequest, +) from policyengine_api.fastapi_routes.v2.household_run_calculations.response_models import ( # noqa: E501 # a module path can't be split across lines HOUSEHOLD_RUN_CALCULATION_READ_RESPONSES, + HOUSEHOLD_RUN_CALCULATIONS_CREATE_RESPONSES, HouseholdRunCalculationItem, HouseholdRunCalculationResponse, HouseholdRunCalculationResult, + HouseholdRunCalculationsCreatedResponse, + HouseholdRunCalculationsCreatedResult, + HouseholdRunCalculationsUnreadableResponse, +) +from policyengine_api.fastapi_routes.v2.simulation_resources_support import ( + SUBMISSION_ERROR_MAPPINGS, + SUBMISSION_REFUSALS, + created_record_unreadable_answer, + simulation_resource_operation, +) +from policyengine_api.fastapi_routes.v2.user_resources_support import ( + request_size_limit, ) from policyengine_api.query_parameters import HouseholdRunCalculationQuery from policyengine_api.services.v2.household_run_calculations.validators import ( + HouseholdCalculationsNotAvailableError, HouseholdRunCalculationNotFoundError, HouseholdRunCalculationResultUnreadableError, HouseholdRunCalculationStorageError, + HouseholdRunCalculationsUnreadableError, + ReportRunFailedError, +) +from policyengine_api.services.v2.simulation_service.types import ( + SimulationServiceConflictError, +) +from policyengine_api.services.v2.stored_reports.validators import ( + ReportRunNotFoundError, + StoredReportNotFoundError, ) if TYPE_CHECKING: @@ -49,6 +78,12 @@ HouseholdRunCalculationQuery, Depends(query_dependency(HouseholdRunCalculationQuery)), ] +# A list of 10,000 variable names of 60 characters is about 615 KiB of JSON, +# within the limit, as for a household report's list. +MAXIMUM_CALCULATIONS_REQUEST_BYTES = 1024 * 1024 +enforce_calculations_request_size = request_size_limit( + MAXIMUM_CALCULATIONS_REQUEST_BYTES, label="1 MiB" +) HOUSEHOLD_RUN_CALCULATION_ERROR_MAPPINGS = ( V2ErrorMapping((HouseholdRunCalculationNotFoundError,), 404), V2ErrorMapping( @@ -64,6 +99,90 @@ ) +# Refusals a caller can act on carry their own message and are not logged. +HOUSEHOLD_RUN_CALCULATIONS_CREATE_REFUSALS: tuple[type[Exception], ...] = ( + StoredReportNotFoundError, + ReportRunNotFoundError, + HouseholdCalculationsNotAvailableError, + ReportRunFailedError, + SimulationServiceConflictError, + *SUBMISSION_REFUSALS, +) +HOUSEHOLD_RUN_CALCULATIONS_CREATE_ERROR_MAPPINGS = ( + V2ErrorMapping((StoredReportNotFoundError, ReportRunNotFoundError), 404), + V2ErrorMapping((ReportRunFailedError, SimulationServiceConflictError), 409), + V2ErrorMapping((HouseholdCalculationsNotAvailableError,), 422), + *SUBMISSION_ERROR_MAPPINGS, + V2ErrorMapping( + (HouseholdRunCalculationStorageError,), + 503, + "V2 household run calculation storage is unavailable", + ), +) + + +def _unreadable_message(error: HouseholdRunCalculationsUnreadableError) -> str: + """Say where to read the calculations the simulation service named.""" + reads = " and ".join( + f"GET /v2/household-run-calculations/{calculation_id}" + f"?country_id={error.country_id}" + for calculation_id in ( + error.baseline_calculation_id, + error.reform_calculation_id, + ) + if calculation_id is not None + ) + return ( + "The simulation service created the extra calculations of report " + f"{error.report_id}'s run {error.run_id}, but they could not be read " + f"back. Read them with {reads} rather than requesting them again." + ) + + +def _create_calculations( + service: V2HouseholdRunCalculationResourceService, + *, + country_id: str, + report_id: UUID, + run_id: UUID, + body: HouseholdRunCalculationsRequest, +) -> HouseholdRunCalculationsCreatedResponse | JSONResponse: + """Request the calculations ``body`` lists; answer each side's. + + Calculations that cannot be read back once the simulation service named + them answer 502, naming each. Every other failure is raised, for the + route's error mappings to answer. + """ + try: + created = service.create_calculations( + country_id=country_id, + report_id=report_id, + run_id=run_id, + variables=body.variables, + axes=body.axes, + ) + except HouseholdRunCalculationsUnreadableError as error: + return created_record_unreadable_answer( + "v2_household_run_calculations_unreadable", + error, + HouseholdRunCalculationsUnreadableResponse( + message=_unreadable_message(error), + baseline_calculation_id=error.baseline_calculation_id, + reform_calculation_id=error.reform_calculation_id, + ), + ) + return HouseholdRunCalculationsCreatedResponse( + result=HouseholdRunCalculationsCreatedResult( + baseline=HouseholdRunCalculationItem.from_read(created.baseline), + reform=( + None + if created.reform is None + else HouseholdRunCalculationItem.from_read(created.reform) + ), + ) + ) + + def _service_factory( dependencies: NativeRouteDependencies, ) -> Callable[[], V2HouseholdRunCalculationResourceService]: @@ -75,10 +194,60 @@ def _service_factory( def build_v2_household_run_calculation_router( dependencies: NativeRouteDependencies, ) -> APIRouter: - """Build the extra calculation read route without opening any connection.""" + """Build the extra calculation routes without opening any connection.""" router = APIRouter(prefix="/v2") service_factory = _service_factory(dependencies) + @router.post( + "/reports/{report_id}/runs/{run_id}/household-calculations", + response_model=HouseholdRunCalculationsCreatedResponse, + status_code=201, + responses=HOUSEHOLD_RUN_CALCULATIONS_CREATE_RESPONSES, + summary="Request extra calculations of a household report's run", + description=( + "Calculates more of each side of a household report's run than the " + "run did: the variables listed, for the side's stored household as " + "entered, or varied along axes, under the side's policy, dynamic and " + "year, on the run's versions. Checks that the report is a household " + "report of the country, that the run is one of its own and hasn't " + "failed (a failed run answers 409: run the report again first), and " + "that each variable is a variable of the running catalog version, " + "then has the simulation service find, for each side, the " + "calculation of the same variables and axes that hasn't failed, or " + "create and start one. A pending, running or succeeded run may be " + "calculated; one on other versions than the simulation service's " + "default worker's answers 409. Answers 201 with each side's " + "calculation, found or created (reform null for a report of the " + "baseline alone); read each with GET " + "/v2/household-run-calculations/{id} until it has succeeded or " + "failed. No user credential is needed, and nothing is recorded " + "for a user." + ), + ) + def create_household_run_calculations( + report_id: UUID, + run_id: UUID, + body: HouseholdRunCalculationsRequest, + query: HouseholdRunCalculationQueryDependency, + _size: Annotated[None, Depends(enforce_calculations_request_size)], + ) -> HouseholdRunCalculationsCreatedResponse | JSONResponse: + def create() -> HouseholdRunCalculationsCreatedResponse | JSONResponse: + return _create_calculations( + service_factory(), + country_id=query.country_id, + report_id=report_id, + run_id=run_id, + body=body, + ) + + return simulation_resource_operation( + create, + HOUSEHOLD_RUN_CALCULATIONS_CREATE_ERROR_MAPPINGS, + refusals=HOUSEHOLD_RUN_CALCULATIONS_CREATE_REFUSALS, + event="v2_household_run_calculations_failed", + fallback_message="V2 household run calculation request failed", + ) + @router.get( "/household-run-calculations/{calculation_id}", response_model=HouseholdRunCalculationResponse, diff --git a/policyengine_api/libs/simulation_household_calculations.py b/policyengine_api/libs/simulation_household_calculations.py index a20b90855..fb2990a4f 100644 --- a/policyengine_api/libs/simulation_household_calculations.py +++ b/policyengine_api/libs/simulation_household_calculations.py @@ -206,10 +206,14 @@ class _AcceptedJob(AnswerModel): status: HouseholdJobStatusName -def _axes_body( +def axes_request_body( axes: list[list[HouseholdCalculationAxis]], ) -> list[list[dict[str, Any]]]: - """Return the axes as sent: each axis keeps only the fields the caller gave.""" + """Return the axes as sent: each axis keeps only the fields the caller gave. + + Extra calculations of a household report's run send their axes so too + (``policyengine_api.libs.simulation_household_run_calculations``). + """ return [ [axis.model_dump(mode="json", exclude_unset=True) for axis in group] for group in axes @@ -244,7 +248,7 @@ def household_calculation_request( if calculation.variables is not None: body["variables"] = list(calculation.variables) if calculation.axes is not None: - body["axes"] = _axes_body(calculation.axes) + body["axes"] = axes_request_body(calculation.axes) if calculation.spm is not None: body["spm"] = calculation.spm.model_dump(mode="json") return body diff --git a/policyengine_api/libs/simulation_household_run_calculations.py b/policyengine_api/libs/simulation_household_run_calculations.py new file mode 100644 index 000000000..8c12f36e0 --- /dev/null +++ b/policyengine_api/libs/simulation_household_run_calculations.py @@ -0,0 +1,293 @@ +"""Ask the simulation service for extra calculations of a household report's run. + +``start_household_run_calculations`` is what +``SimulationServiceReportClient.create_household_run_calculations`` does: it +posts ``{"variables": [...]}``, with ``"axes"`` when the caller gave them +(each axis keeping only the fields the caller gave), to the Cloud Run +simulation service's ``POST +/reports/{report_id}/runs/{report_run_id}/household-calculations``, through +the generated client's ``create_household_run_calculations`` operation +(``post_household_run_calculations`` in +``policyengine_api.libs.simulation_service_operations``). For each side's +simulation run of the report run, the service finds the calculation of the +same variables and axes that hasn't failed, or creates one and starts its +household function call. + +API v1 reads the report and its run in its country before asking, so it +never asks about a report or run it does not have. The simulation +service answers: + +- 201 or 202 naming the report, its run and each side's calculation (the + reform's null for a report of the baseline alone). One whose body cannot + be read, or that names another report or run, is + SimulationServiceAnswerUnreadableError; +- 409 with ``code`` and ``detail`` when the run failed + (``report_run_failed``) or calculated on other versions than the default + worker's (``report_run_not_current``), so the report must be run again + first, or the stored report lacks a row its runs calculate on + (``rerun_not_supported``): SimulationServiceConflictError, with the code + and reason. It answers 409 before writing anything, so one that cannot be + read is SimulationServiceUnavailableError; +- 422 with its reasons when the stored report is not a household report or + its household or policies cannot be calculated, and 400 with a code in + ``CALLER_ROW_REFUSAL_CODES``: SimulationServiceInvalidRequestError, with + the code and reasons. Any other 400 is the service's own state, such as + its household function or catalog version missing while a release + deploys: SimulationServiceUnavailableError, with the code and reason; +- 503 with its code when it is not configured or cannot read its manifest + or database, before writing anything, and 401, 403, 404, 405, 413 or 429, + which come before any write too: SimulationServiceUnavailableError. A 404 + is the service's state, since API v1 has just read the report and + run. + +Any other answer may follow calculations the service created: an answer +lost after the request may have been sent, a proxy's 502 or 504 and a 503 +that cannot be read (SimulationServiceAnswerUnreadableError), a 500 +(SimulationServiceInternalError), and any other status +(SimulationServiceAnswerUnreadableError). Each asks the caller to request +the same calculations again, which finds those the service created rather +than starting more. + +A 400's, 409's or 422's message gives the service's code and reason, and +any other message gives the status and code, never the reason, which may be +an exception's text. +""" + +from __future__ import annotations + +from http import HTTPStatus +from typing import TYPE_CHECKING, Any, NoReturn +from uuid import UUID + +from pydantic import ValidationError + +from policyengine_api.libs.simulation_service_answers import ( + CALLER_ROW_REFUSAL_CODES, + CREATED_STATUSES, + PROXY_STAND_IN_STATUSES, + REFUSAL_STATUSES, + SENT_BEFORE_ROUTE_STATUSES, + AnswerModel, + Refusal, + SimulationAnswer, + answer_lost, + created_but_failed, + fixed_identifier_code, + parsed_body, + refusal_reason, + send_to_simulation_service, + status_and_code, +) +from policyengine_api.services.v2.simulation_service.types import ( + CreatedHouseholdRunCalculations, + SimulationServiceAnswerUnreadableError, + SimulationServiceConflictError, + SimulationServiceInternalError, + SimulationServiceInvalidRequestError, + SimulationServiceUnavailableError, +) + +if TYPE_CHECKING: + from collections.abc import Callable + + import httpx + + from policyengine_api.services.v2.simulation_service.types import ( + HouseholdRunCalculationsInput, + ) + +REQUEST_AGAIN = ( + "Request the same calculations again: an identical request finds those the " + "simulation service created, rather than starting more." +) +UNREADABLE_ANSWER = ( + "The simulation service answered that it found or created the extra " + f"calculations, but its answer could not be read. {REQUEST_AGAIN}" +) +CALCULATIONS = "extra calculations" + + +class _SideCalculation(AnswerModel): + household_run_calculation_id: UUID + + +class _CalculationsCreated(AnswerModel): + report_id: UUID + report_run_id: UUID + baseline: _SideCalculation + reform: _SideCalculation | None + + +class _CalculationRefusal(Refusal): + """A refusal's or failure's body: a reason, or each refused field, and a code.""" + + code: str | None = None + + +def household_run_calculations_path(report_id: UUID, report_run_id: UUID) -> str: + """Return the simulation service's path for the run's extra calculations. + + Tests check requests against it. The generated + ``create_household_run_calculations`` operation builds its own copy, + which it sends the request to. + """ + return f"/reports/{report_id}/runs/{report_run_id}/household-calculations" + + +def household_run_calculations_request( + request: HouseholdRunCalculationsInput, +) -> dict[str, Any]: + """Return the simulation service's request body for the extra calculations. + + ``axes`` is sent only when the caller gave them, each axis with only the + fields the caller gave. + """ + # Imported here: the household calculation client is loaded on first use. + from policyengine_api.libs.simulation_household_calculations import ( + axes_request_body, + ) + + body: dict[str, Any] = {"variables": list(request.variables)} + if request.axes is not None: + body["axes"] = axes_request_body(request.axes) + return body + + +def _refusal(answer: SimulationAnswer) -> _CalculationRefusal | None: + try: + return _CalculationRefusal.model_validate_json(answer.content) + except ValidationError: + return None + + +def _status_and_code(answer: SimulationAnswer) -> str: + """Return the answer's status and fixed-identifier code, never its reason.""" + return status_and_code( + answer.status_code, fixed_identifier_code(parsed_body(answer)) + ) + + +def _code_and_reason(refusal: _CalculationRefusal) -> str: + """Return `` (code): reason``, or ``: reason`` when the service gave no code.""" + code = "" if refusal.code is None else f" ({refusal.code})" + return f"{code}: {refusal_reason(refusal)}" + + +def _raise_for_refused_request( + answer: SimulationAnswer, refusal: _CalculationRefusal +) -> NoReturn: + """Raise the error a readable 400 or 422 means.""" + code_and_reason = _code_and_reason(refusal) + if ( + answer.status_code == HTTPStatus.UNPROCESSABLE_ENTITY + or refusal.code in CALLER_ROW_REFUSAL_CODES + ): + msg = f"The simulation service cannot calculate this run{code_and_reason}" + raise SimulationServiceInvalidRequestError(msg) + msg = f"The simulation service refused to calculate this run{code_and_reason}" + raise SimulationServiceUnavailableError(msg) + + +def _raise_for_conflict(answer: SimulationAnswer) -> NoReturn: + """Raise the error a 409 means: a conflict, or unavailable when unreadable.""" + refusal = _refusal(answer) + if refusal is None or refusal.code is None: + msg = f"The simulation service answered {answer.status_code} unreadably." + raise SimulationServiceUnavailableError(msg) + msg = ( + "The simulation service will not calculate this run now" + f"{_code_and_reason(refusal)}" + ) + raise SimulationServiceConflictError(msg) + + +def _raise_for_unavailable(answer: SimulationAnswer) -> NoReturn: + """Raise the error a 503 means. + + The service's own 503 comes before it writes anything; one that cannot + be read, such as Cloud Run's own, may follow calculations it created. + """ + if _refusal(answer) is None: + raise SimulationServiceAnswerUnreadableError( + created_but_failed(CALCULATIONS, _status_and_code(answer), REQUEST_AGAIN) + ) + msg = f"The simulation service is unavailable ({_status_and_code(answer)})." + raise SimulationServiceUnavailableError(msg) + + +def _raise_for_refusal(answer: SimulationAnswer) -> NoReturn: + """Raise the error any answer but found or created calculations means.""" + status_code = answer.status_code + if status_code in REFUSAL_STATUSES: + refusal = _refusal(answer) + if refusal is None: + msg = f"The simulation service answered {status_code} unreadably." + raise SimulationServiceUnavailableError(msg) + _raise_for_refused_request(answer, refusal) + if status_code == HTTPStatus.CONFLICT: + _raise_for_conflict(answer) + if status_code in PROXY_STAND_IN_STATUSES: + msg = answer_lost(f"a proxy answered {status_code} in its place", REQUEST_AGAIN) + raise SimulationServiceAnswerUnreadableError(msg) + if status_code == HTTPStatus.SERVICE_UNAVAILABLE: + _raise_for_unavailable(answer) + if status_code in SENT_BEFORE_ROUTE_STATUSES: + msg = f"The simulation service is unavailable ({_status_and_code(answer)})." + raise SimulationServiceUnavailableError(msg) + msg = created_but_failed(CALCULATIONS, _status_and_code(answer), REQUEST_AGAIN) + if status_code == HTTPStatus.INTERNAL_SERVER_ERROR: + raise SimulationServiceInternalError(msg) + raise SimulationServiceAnswerUnreadableError(msg) + + +def _require_created( + answer: SimulationAnswer, request: HouseholdRunCalculationsInput +) -> CreatedHouseholdRunCalculations: + """Return the calculations the answer names, once it names the request's run. + + Raise SimulationServiceAnswerUnreadableError for an answer that cannot + be read or names another report or run. + """ + try: + created = _CalculationsCreated.model_validate_json(answer.content) + except ValidationError as error: + raise SimulationServiceAnswerUnreadableError(UNREADABLE_ANSWER) from error + if (created.report_id, created.report_run_id) != ( + request.report_id, + request.report_run_id, + ): + raise SimulationServiceAnswerUnreadableError(UNREADABLE_ANSWER) + return CreatedHouseholdRunCalculations( + baseline_calculation_id=created.baseline.household_run_calculation_id, + reform_calculation_id=( + None + if created.reform is None + else created.reform.household_run_calculation_id + ), + ) + + +def start_household_run_calculations( + http_client: httpx.Client, + request: HouseholdRunCalculationsInput, + *, + send: Callable[[httpx.Client, UUID, UUID, dict[str, Any]], SimulationAnswer], +) -> CreatedHouseholdRunCalculations: + """Have the simulation service find or start each side's calculation. + + Send through ``send`` on ``http_client``, and raise the errors the module + docstring lists for the service's answers. A connection never made, or a + gateway token that cannot be fetched, is + SimulationServiceUnavailableError. + """ + answer = send_to_simulation_service( + lambda client, body: send( + client, request.report_id, request.report_run_id, body + ), + http_client, + household_run_calculations_request(request), + submit_again_sentence=REQUEST_AGAIN, + ) + if answer.status_code in CREATED_STATUSES: + return _require_created(answer, request) + _raise_for_refusal(answer) diff --git a/policyengine_api/libs/simulation_reports.py b/policyengine_api/libs/simulation_reports.py index 198bb0b00..daaebba19 100644 --- a/policyengine_api/libs/simulation_reports.py +++ b/policyengine_api/libs/simulation_reports.py @@ -117,6 +117,9 @@ from pydantic import ValidationError +from policyengine_api.libs.simulation_household_run_calculations import ( + start_household_run_calculations, +) from policyengine_api.libs.simulation_report_reruns import start_report_rerun from policyengine_api.libs.simulation_service_answers import ( CALLER_ROW_REFUSAL_CODES, @@ -138,6 +141,7 @@ submit_again, ) from policyengine_api.libs.simulation_service_operations import ( + post_household_run_calculations, post_report, post_report_rerun, post_simulation, @@ -159,10 +163,12 @@ from policyengine_api.services.v2.simulation_service.types import ( BudgetWindowReportCreationInput, + CreatedHouseholdRunCalculations, EconomyReportCreationInput, EconomySimulationCreationInput, HouseholdPolicyChoice, HouseholdReportCreationInput, + HouseholdRunCalculationsInput, PolicyChoice, ReportRerunInput, StartedReportRun, @@ -437,7 +443,7 @@ def _raise_for_refusal(answer: SimulationAnswer, record: RecordName) -> NoReturn class SimulationServiceReportClient: - """Create simulations and reports, and run reports again, through the service.""" + """Create simulations and reports, run reports again, and calculate their runs.""" def __init__( self, @@ -452,8 +458,11 @@ def __init__( send_report_rerun: Callable[ [httpx.Client, UUID, dict[str, Any]], SimulationAnswer ] = post_report_rerun, + send_household_run_calculations: Callable[ + [httpx.Client, UUID, UUID, dict[str, Any]], SimulationAnswer + ] = post_household_run_calculations, ) -> None: - """Send through ``send_simulation``, ``send_report`` and ``send_report_rerun``. + """Send each kind of request through its ``send_`` function. Each sends on ``http_client``, which has the service's base URL. """ @@ -461,6 +470,7 @@ def __init__( self._send_simulation = send_simulation self._send_report = send_report self._send_report_rerun = send_report_rerun + self._send_household_run_calculations = send_household_run_calculations @classmethod def from_environment( @@ -606,6 +616,19 @@ def rerun_report(self, rerun: ReportRerunInput) -> StartedReportRun: self._http_client, rerun, send=self._send_report_rerun ) + def create_household_run_calculations( + self, request: HouseholdRunCalculationsInput + ) -> CreatedHouseholdRunCalculations: + """Have the service find or start each side's extra calculation of the run. + + Raise the errors + ``policyengine_api.libs.simulation_household_run_calculations`` lists + for the service's answers. + """ + return start_household_run_calculations( + self._http_client, request, send=self._send_household_run_calculations + ) + @lru_cache(maxsize=1) def process_simulation_service_client() -> SimulationServiceReportClient: diff --git a/policyengine_api/libs/simulation_service_operations.py b/policyengine_api/libs/simulation_service_operations.py index f50f69591..23e20ad16 100644 --- a/policyengine_api/libs/simulation_service_operations.py +++ b/policyengine_api/libs/simulation_service_operations.py @@ -60,6 +60,9 @@ from typing import TYPE_CHECKING, Any +from policyengine_api_simulation_client.api.default.create_household_run_calculations import ( # noqa: E501 # a module path can't be split across lines + _get_kwargs as household_run_calculations_request_arguments, +) from policyengine_api_simulation_client.api.default.create_report import ( _get_kwargs as report_request_arguments, ) @@ -81,6 +84,7 @@ EconomySimulationRequest, HouseholdCalculationRequest, HouseholdReportRequest, + HouseholdRunCalculationRequest, InlineHouseholdCalculationRequest, ReportRerunRequest, ) @@ -222,3 +226,25 @@ def post_report_rerun( return send_request_with_body( http_client, report_rerun_request_arguments(report_id, body=request), body ) + + +def post_household_run_calculations( + http_client: httpx.Client, + report_id: UUID, + report_run_id: UUID, + body: dict[str, Any], +) -> SimulationAnswer: + """Ask for extra calculations of a household report's run. + + The route is ``POST + /reports/{report_id}/runs/{report_run_id}/household-calculations``. Raise + what ``send_request_with_body`` raises. + """ + request = HouseholdRunCalculationRequest.from_dict(body) + return send_request_with_body( + http_client, + household_run_calculations_request_arguments( + report_id, report_run_id, body=request + ), + body, + ) diff --git a/policyengine_api/services/v2/household_calculations/types.py b/policyengine_api/services/v2/household_calculations/types.py index 3e16abd43..f02aa9c4a 100644 --- a/policyengine_api/services/v2/household_calculations/types.py +++ b/policyengine_api/services/v2/household_calculations/types.py @@ -126,6 +126,33 @@ class HouseholdCalculationAxis(StrictCalculationModel): ] +def require_axis_point_limits( + axes: list[list[HouseholdCalculationAxis]], +) -> list[list[HouseholdCalculationAxis]]: + """Refuse groups of uneven point counts and grids of too many points. + + The axes of one group vary together, so they share one point count, and + the groups form a grid of at most MAXIMUM_AXIS_POINTS points. + """ + for group in axes: + if len({axis.count for axis in group}) != 1: + msg = "the axes of one group must share one point count" + raise ValueError(msg) + if math.prod(group[0].count for group in axes) > MAXIMUM_AXIS_POINTS: + msg = f"the axis groups may vary at most {MAXIMUM_AXIS_POINTS} points" + raise ValueError(msg) + return axes + + +# Up to MAXIMUM_AXIS_GROUPS groups of axes, as /v2/household-calculations and +# an extra calculation of a household report's run take them. +AxisGroups = Annotated[ + list[AxisGroup], + Field(max_length=MAXIMUM_AXIS_GROUPS), + AfterValidator(require_axis_point_limits), +] + + def _omit_spm_default(schema: dict[str, Any]) -> None: # Omitting spm sends no SPM settings; an explicit null is not a selection. schema.pop("default", None) @@ -172,14 +199,7 @@ def limit_axis_points( """Refuse groups of uneven point counts and grids of too many points.""" if axes is None: return None - for group in axes: - if len({axis.count for axis in group}) != 1: - msg = "the axes of one group must share one point count" - raise ValueError(msg) - if math.prod(group[0].count for group in axes) > MAXIMUM_AXIS_POINTS: - msg = f"the axis groups may vary at most {MAXIMUM_AXIS_POINTS} points" - raise ValueError(msg) - return axes + return require_axis_point_limits(axes) @field_validator("variables") @classmethod diff --git a/policyengine_api/services/v2/household_run_calculations/database_connectors/reads.py b/policyengine_api/services/v2/household_run_calculations/database_connectors/reads.py index a4c4cd1e9..26fb6b2c5 100644 --- a/policyengine_api/services/v2/household_run_calculations/database_connectors/reads.py +++ b/policyengine_api/services/v2/household_run_calculations/database_connectors/reads.py @@ -8,6 +8,8 @@ from policyengine_api.data.v2.models import ( HouseholdRunCalculation, + Report, + ReportRun, Simulation, TaxBenefitModel, TaxBenefitModelVersion, @@ -44,3 +46,27 @@ def read_household_run_calculation( ) ) return session.exec(statement).one_or_none() + + +def read_report(session: Session, *, country_id: str, report_id: UUID) -> Report | None: + """Return the country's report, or None when the country has no such report.""" + statement = select(Report).where( + col(Report.id) == report_id, col(Report.country) == country_id + ) + return session.exec(statement).one_or_none() + + +def read_report_run( + session: Session, *, report_id: UUID, run_id: UUID +) -> ReportRun | None: + """Return the report's own run ``run_id``, or None when it has no such run. + + A run of another report, or of a budget window's year, is not one of its + own runs. + """ + statement = select(ReportRun).where( + col(ReportRun.id) == run_id, + col(ReportRun.report_id) == report_id, + col(ReportRun.budget_window_run_id).is_(None), + ) + return session.exec(statement).one_or_none() diff --git a/policyengine_api/services/v2/household_run_calculations/services.py b/policyengine_api/services/v2/household_run_calculations/services.py index 494f3882a..f03f15607 100644 --- a/policyengine_api/services/v2/household_run_calculations/services.py +++ b/policyengine_api/services/v2/household_run_calculations/services.py @@ -1,4 +1,4 @@ -"""Read extra calculations of household report runs. +"""Request and read extra calculations of household report runs. An extra calculation (``household_run_calculations``) calculates more of one side's simulation run of a household report, such as @@ -6,6 +6,13 @@ inserts it and its household function completes it; reading one reads the row and never calls the simulation service. A calculation is read within its country: one of another country's run is not found. + +Requesting calculations of a report's run reads the report and run in the +country, refuses a report of another kind and a failed run, then has the +checking ``SimulationSubmissionService`` check the country and variables and +ask the simulation service, which finds each side's calculation of the same +variables and axes that hasn't failed, or creates and starts one. Each is +then read back by ID. """ from __future__ import annotations @@ -17,26 +24,47 @@ from policyengine_api.services.v2.household_run_calculations.database_connectors.reads import ( # noqa: E501 # a module path can't be split across lines read_household_run_calculation, + read_report, + read_report_run, ) from policyengine_api.services.v2.household_run_calculations.transformations import ( household_run_calculation_read, ) +from policyengine_api.services.v2.household_run_calculations.types import ( + HouseholdRunCalculationsRead, +) from policyengine_api.services.v2.household_run_calculations.validators import ( HouseholdRunCalculationStorageError, + HouseholdRunCalculationsUnreadableError, calculated_household, + require_calculable_run, require_calculation, + require_household_report, +) +from policyengine_api.services.v2.simulation_service.types import ( + HouseholdRunCalculationsInput, + SimulationServiceUnavailableError, ) if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Iterator, Sequence from uuid import UUID + from sqlmodel import Session + + from policyengine_api.services.v2.household_calculations.types import ( + HouseholdCalculationAxis, + ) from policyengine_api.services.v2.household_run_calculations.database_session import ( # noqa: E501 # a module path can't be split across lines HouseholdRunCalculationDatabaseSession, ) from policyengine_api.services.v2.household_run_calculations.types import ( HouseholdRunCalculationRead, ) + from policyengine_api.services.v2.simulation_service.types import ( + CreatedHouseholdRunCalculations, + SimulationServiceClient, + ) @contextmanager @@ -49,14 +77,42 @@ def _storage_failures() -> Iterator[None]: raise HouseholdRunCalculationStorageError(msg) from error +def _calculation( + session: Session, *, country_id: str, calculation_id: UUID +) -> HouseholdRunCalculationRead: + """Return the country's calculation, with its household once it has succeeded. + + Raise what ``V2HouseholdRunCalculationService.get_calculation`` raises, + except HouseholdRunCalculationStorageError. + """ + calculation = require_calculation( + read_household_run_calculation( + session, country_id=country_id, calculation_id=calculation_id + ), + calculation_id=calculation_id, + ) + return household_run_calculation_read( + calculation, calculated_household(calculation) + ) + + class V2HouseholdRunCalculationService: - """Read extra calculations of household report runs from the v2 tables.""" + """Request extra calculations of household report runs, and read them.""" def __init__( - self, database_session: HouseholdRunCalculationDatabaseSession + self, + database_session: HouseholdRunCalculationDatabaseSession, + *, + submissions: SimulationServiceClient | None = None, ) -> None: - """Read through ``database_session``.""" + """Read through ``database_session``; request through ``submissions``. + + ``submissions`` is the checking ``SimulationSubmissionService``; + without it, requesting calculations raises + SimulationServiceUnavailableError. + """ self._database_session = database_session + self._submissions = submissions def get_calculation( self, *, country_id: str, calculation_id: UUID @@ -70,12 +126,94 @@ def get_calculation( the database cannot be read. """ with _storage_failures(), self._database_session.read() as session: - calculation = require_calculation( - read_household_run_calculation( - session, country_id=country_id, calculation_id=calculation_id - ), - calculation_id=calculation_id, + return _calculation( + session, country_id=country_id, calculation_id=calculation_id + ) + + def create_calculations( + self, + *, + country_id: str, + report_id: UUID, + run_id: UUID, + variables: Sequence[str], + axes: list[list[HouseholdCalculationAxis]] | None, + ) -> HouseholdRunCalculationsRead: + """Request each side's calculation of the country's household report run. + + The simulation service calculates ``variables`` for each side's + stored household, as entered or varied along ``axes``; it finds a + calculation of the same variables and axes that hasn't failed, or + creates and starts one. Return both, read back by ID. + + Raise StoredReportNotFoundError when the country has no such report, + HouseholdCalculationsNotAvailableError for a report of another kind, + ReportRunNotFoundError when the report has no such run and + ReportRunFailedError for a failed one, each before the simulation + service is asked; HouseholdRunCalculationStorageError when the report + cannot be read; SimulationServiceUnavailableError when the service is + not configured here; the submission's checks' and the simulation + service's errors (see + ``SimulationSubmissionService.create_household_run_calculations``); + and HouseholdRunCalculationsUnreadableError, caused by the read's own + error, when the calculations cannot be read back. + """ + if self._submissions is None: + msg = "The simulation service is not configured here" + raise SimulationServiceUnavailableError(msg) + with _storage_failures(), self._database_session.read() as session: + require_household_report( + read_report(session, country_id=country_id, report_id=report_id), + country_id=country_id, + report_id=report_id, + ) + require_calculable_run( + read_report_run(session, report_id=report_id, run_id=run_id), + report_id=report_id, + run_id=run_id, + ) + created = self._submissions.create_household_run_calculations( + HouseholdRunCalculationsInput( + country_id=country_id, + report_id=report_id, + report_run_id=run_id, + variables=tuple(variables), + axes=axes, ) - return household_run_calculation_read( - calculation, calculated_household(calculation) + ) + try: + return self._read_created(country_id, created) + except Exception as error: + # The calculations exist whatever failed, so the caller reads them. + raise HouseholdRunCalculationsUnreadableError( + country_id=country_id, + report_id=report_id, + run_id=run_id, + baseline_calculation_id=created.baseline_calculation_id, + reform_calculation_id=created.reform_calculation_id, + ) from error + + def _read_created( + self, country_id: str, created: CreatedHouseholdRunCalculations + ) -> HouseholdRunCalculationsRead: + """Read each side's calculation the simulation service named. + + A report comparing a policy with itself names one calculation on both + sides, which is read once. + """ + with self._database_session.read() as session: + baseline = _calculation( + session, + country_id=country_id, + calculation_id=created.baseline_calculation_id, ) + reform_id = created.reform_calculation_id + if reform_id is None: + reform = None + elif reform_id == baseline.id: + reform = baseline + else: + reform = _calculation( + session, country_id=country_id, calculation_id=reform_id + ) + return HouseholdRunCalculationsRead(baseline=baseline, reform=reform) diff --git a/policyengine_api/services/v2/household_run_calculations/types.py b/policyengine_api/services/v2/household_run_calculations/types.py index fba0140d0..a5faaf275 100644 --- a/policyengine_api/services/v2/household_run_calculations/types.py +++ b/policyengine_api/services/v2/household_run_calculations/types.py @@ -44,3 +44,15 @@ class HouseholdRunCalculationRead: error_message: str | None created_at: datetime completed_at: datetime | None + + +@dataclass(frozen=True) +class HouseholdRunCalculationsRead: + """Each side's extra calculation of a household report run, as requested. + + ``reform`` is None for a report of the baseline alone. A report comparing + a policy with itself has one calculation on both sides. + """ + + baseline: HouseholdRunCalculationRead + reform: HouseholdRunCalculationRead | None diff --git a/policyengine_api/services/v2/household_run_calculations/validators.py b/policyengine_api/services/v2/household_run_calculations/validators.py index b04df9f12..76e76d8a5 100644 --- a/policyengine_api/services/v2/household_run_calculations/validators.py +++ b/policyengine_api/services/v2/household_run_calculations/validators.py @@ -1,4 +1,8 @@ -"""Checks of the extra calculations of household report runs that API v1 reads.""" +"""Checks of the extra calculations of household report runs. + +API v1 reads a calculation, and checks a report and its run before asking the +simulation service for more calculations of the run. +""" from __future__ import annotations @@ -6,15 +10,24 @@ from pydantic import ValidationError -from policyengine_api.data.v2.models import SimulationStatus +from policyengine_api.data.v2.models import ReportRunStatus, SimulationStatus from policyengine_api.services.v2.household_calculations.types import ( StoredExecutionResult, ) +from policyengine_api.services.v2.stored_reports.transformations import report_kind +from policyengine_api.services.v2.stored_reports.validators import ( + ReportRunNotFoundError, + StoredReportNotFoundError, +) if TYPE_CHECKING: from uuid import UUID - from policyengine_api.data.v2.models import HouseholdRunCalculation + from policyengine_api.data.v2.models import ( + HouseholdRunCalculation, + Report, + ReportRun, + ) from policyengine_api.services.v2.household_calculations.types import ( HouseholdCalculationOutput, ) @@ -32,6 +45,86 @@ class HouseholdRunCalculationResultUnreadableError(RuntimeError): """A succeeded calculation's stored result is not a readable result document.""" +class HouseholdCalculationsNotAvailableError(ValueError): + """The report isn't a household report, so its runs have no extra calculations.""" + + +class ReportRunFailedError(RuntimeError): + """The run failed, so it has no households to calculate more of. + + Running the report again gives a run whose calculations may be asked for. + """ + + +class HouseholdRunCalculationsUnreadableError(RuntimeError): + """The simulation service named the run's calculations; they can't be read back. + + They exist, so the caller reads each by ID rather than asking again. The + error's cause is the read's own failure, if any. + """ + + def __init__( + self, + *, + country_id: str, + report_id: UUID, + run_id: UUID, + baseline_calculation_id: UUID, + reform_calculation_id: UUID | None, + ) -> None: + """Name the report run and each side's calculation.""" + self.country_id = country_id + self.report_id = report_id + self.run_id = run_id + self.baseline_calculation_id = baseline_calculation_id + self.reform_calculation_id = reform_calculation_id + super().__init__( + f"Extra calculations of report {report_id}'s run {run_id} could " + "not be read back" + ) + + +def require_household_report( + report: Report | None, *, country_id: str, report_id: UUID +) -> Report: + """Return the country's household report. + + Raise StoredReportNotFoundError when the country has no such report, and + HouseholdCalculationsNotAvailableError for any other kind of report. + """ + if report is None: + msg = f"Report {report_id} was not found in country {country_id!r}" + raise StoredReportNotFoundError(msg) + if report_kind(report) != "household": + msg = ( + "Only a household report's runs have extra calculations; report " + f"{report_id} is not a household report." + ) + raise HouseholdCalculationsNotAvailableError(msg) + return report + + +def require_calculable_run( + run: ReportRun | None, *, report_id: UUID, run_id: UUID +) -> ReportRun: + """Return the report's run, unless it failed. + + A pending, running or succeeded run passes. Raise ReportRunNotFoundError + when the report has no such run, and ReportRunFailedError for a failed + one. + """ + if run is None: + msg = f"Report {report_id} has no run {run_id}" + raise ReportRunNotFoundError(msg) + if run.status is ReportRunStatus.FAILED: + msg = ( + f"Report run {run_id} failed. Run the report again, then request " + "the calculations of its new run." + ) + raise ReportRunFailedError(msg) + return run + + def require_calculation( calculation: HouseholdRunCalculation | None, *, calculation_id: UUID ) -> HouseholdRunCalculation: diff --git a/policyengine_api/services/v2/simulation_service/services.py b/policyengine_api/services/v2/simulation_service/services.py index 902253e36..fb0743f33 100644 --- a/policyengine_api/services/v2/simulation_service/services.py +++ b/policyengine_api/services/v2/simulation_service/services.py @@ -32,6 +32,15 @@ Its dynamics are not checked again: each was checked to be the country's when the report was created, and the simulation service refuses a re-run whose dynamic sets parameters its catalog version lacks. + +Asking for extra calculations of a household report's run (``POST +/reports/{report_id}/runs/{report_run_id}/household-calculations``) checks +that the country's row allows household calculations, then that every +variable listed is a variable of the running catalog version, as a household +report's are checked. The run's policies and dynamics are not checked +again: the simulation service calculates only a run on its default worker's +versions, and refuses one whose stored household or policies it cannot +calculate. """ from __future__ import annotations @@ -72,10 +81,12 @@ from policyengine_api.services.v2.simulation_service.types import ( BudgetWindowReportCreationInput, CountrySource, + CreatedHouseholdRunCalculations, DynamicSource, EconomyReportCreationInput, EconomySimulationCreationInput, HouseholdReportCreationInput, + HouseholdRunCalculationsInput, PolicySource, ReportRerunInput, ReportRerunKind, @@ -337,6 +348,25 @@ def rerun_report(self, rerun: ReportRerunInput) -> StartedReportRun: self._require_known_variables(rerun.country_id, rerun.variables) return self._client_factory().rerun_report(rerun) + def create_household_run_calculations( + self, request: HouseholdRunCalculationsInput + ) -> CreatedHouseholdRunCalculations: + """Check the extra calculations, then have the simulation service start them. + + Return each side's calculation the service found or created. Raise + HouseholdCalculationCountryError unless the country's row allows + household calculations, then HouseholdCalculationVariablesUnknownError + naming the listed variables the running catalog version lacks, + SubmissionStorageError when the database or its catalog cannot be + read, then the simulation service's errors. + """ + with _storage_failures(): + require_household_country( + self._countries.list_countries(), request.country_id + ) + self._require_known_variables(request.country_id, request.variables) + return self._client_factory().create_household_run_calculations(request) + def _country_check(kind: ReportRerunKind) -> CountryCheck: """Return the check a new report of this kind makes of its country's row. diff --git a/policyengine_api/services/v2/simulation_service/types.py b/policyengine_api/services/v2/simulation_service/types.py index dbe6ddd7d..27367fab8 100644 --- a/policyengine_api/services/v2/simulation_service/types.py +++ b/policyengine_api/services/v2/simulation_service/types.py @@ -2,9 +2,11 @@ The simulation service creates simulations, reports and their runs in the detailed-save tables, and starts their calculation on Modal. Its -``POST /simulations``, ``POST /reports`` and ``POST -/reports/{report_id}/runs``, which runs a stored report again, are reached -through ``SimulationServiceClient``; +``POST /simulations``, ``POST /reports``, ``POST +/reports/{report_id}/runs``, which runs a stored report again, and ``POST +/reports/{report_id}/runs/{report_run_id}/household-calculations``, which +calculates more of a household report's run, are reached through +``SimulationServiceClient``; ``policyengine_api.libs.simulation_reports`` implements it over HTTP, and tests replace it with a stand-in. Reading what it created needs no call: the Public API reads the tables. @@ -47,6 +49,9 @@ from policyengine_api.services.v2.countries.types import CountryRead from policyengine_api.services.v2.dynamics.types import CheckedDynamicRead + from policyengine_api.services.v2.household_calculations.types import ( + HouseholdCalculationAxis, + ) from policyengine_api.services.v2.policies.types import CheckedPolicyRead # The bounds the simulation service and the tables accept. @@ -151,13 +156,16 @@ class SimulationServiceInvalidRequestError(ValueError): class SimulationServiceConflictError(RuntimeError): - """The simulation service will not run the stored report again now. + """The simulation service refuses to run a stored report, or calculate a run, now. The report has a run pending or running, which ``run_id`` names, or it is one the service does not run again, such as a kind of report it cannot - re-run yet or one whose simulation, region or dataset is gone. The - service wrote nothing. The message gives the service's code and reason; - the route answers 409, naming ``run_id`` when the service named a run. + re-run yet or one whose simulation, region or dataset is gone. For extra + calculations of a household report's run, the run failed or calculated + on other versions than the service's default worker's, and the report + must be run again first. The service wrote nothing. The message gives + the service's code and reason; the route answers 409, naming ``run_id`` + when the service named a run. """ def __init__(self, message: str, *, run_id: UUID | None = None) -> None: @@ -470,6 +478,38 @@ class ReportRerunInput: variables: tuple[str, ...] | None = None +@dataclass(frozen=True) +class HouseholdRunCalculationsInput: + """Extra calculations of each side of a household report run of the country. + + The simulation service calculates ``variables`` (1 to 10,000 distinct + names, each a variable of the running catalog version) for each side's + simulation run of the report's run ``report_run_id``: for its stored + household as entered, or varied along ``axes``, as + ``/v2/household-calculations`` takes them for a stored household. Each + axis is sent with only the fields the caller gave. + """ + + country_id: str + report_id: UUID + report_run_id: UUID + variables: tuple[str, ...] + axes: list[list[HouseholdCalculationAxis]] | None = None + + +@dataclass(frozen=True) +class CreatedHouseholdRunCalculations: + """Each side's extra calculation the simulation service found or created. + + ``reform_calculation_id`` is None for a report of the baseline alone; a + report comparing a policy with itself names one calculation on both + sides. + """ + + baseline_calculation_id: UUID + reform_calculation_id: UUID | None + + class SimulationServiceClient(Protocol): """The simulation service's routes that create and start calculations. @@ -497,7 +537,9 @@ class SimulationServiceClient(Protocol): record, and SimulationServiceConflictError when the service will not run the report again now; a 409 that cannot be read is SimulationServiceUnavailableError, since the service answers 409 only - before writing anything. + before writing anything. ``create_household_run_calculations`` raises + the errors ``rerun_report`` raises, a conflict when the run failed or + calculated on other versions than the default worker's. ``SimulationSubmissionService``, which checks a submission before sending it through a client, also raises EconomyCalculationsUnsupportedError, @@ -546,6 +588,17 @@ def rerun_report(self, rerun: ReportRerunInput) -> StartedReportRun: """ ... + def create_household_run_calculations( + self, request: HouseholdRunCalculationsInput + ) -> CreatedHouseholdRunCalculations: + """Find or start each side's extra calculation of the run; return them. + + For each side's simulation run, the service finds the calculation of + the same variables and axes that hasn't failed, or creates and + starts one. + """ + ... + class CountrySource(Protocol): """The countries list a submission checks first.""" diff --git a/tests/contract/registry.py b/tests/contract/registry.py index 5b1cc0f7b..1654b674c 100644 --- a/tests/contract/registry.py +++ b/tests/contract/registry.py @@ -770,6 +770,24 @@ class WorkflowContract: ), route_group="report", ), + ContractRequest( + method="POST", + path=( + "/v2/reports/{report_id}/runs/{run_id}/household-calculations" + "?country_id=us" + ), + expected_status=201, + stable_response_fields=( + "status", + "message", + "result.baseline.id", + "result.baseline.status", + "result.baseline.variables", + "result.baseline.axes", + "result.reform", + ), + route_group="report", + ), ContractRequest( method="GET", path="/v2/household-run-calculations/{calculation_id}?country_id=us", From 48cda19cde41a70459576d3db53ac34c908df3ac Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 4 Dec 2026 02:36:52 +0400 Subject: [PATCH 08/12] Describe household reports' variables in the report routes, and add the changelog Co-Authored-By: Claude Opus 5.5 --- .../v2-household-report-variables.added.md | 1 + .../fastapi_routes/v2/reports/routes.py | 19 +++++++++++++++---- 2 files changed, 16 insertions(+), 4 deletions(-) create mode 100644 changelog.d/v2-household-report-variables.added.md diff --git a/changelog.d/v2-household-report-variables.added.md b/changelog.d/v2-household-report-variables.added.md new file mode 100644 index 000000000..c1dcd0426 --- /dev/null +++ b/changelog.d/v2-household-report-variables.added.md @@ -0,0 +1 @@ +API v1's `/v2/reports` takes the variables a household report's runs calculate, on creating the report and on running it again, and reading a household report names the variables each side's run calculates (`calculated_variables`). `POST /v2/reports/{report_id}/runs/{run_id}/household-calculations` requests extra calculations of a household report's run, and `GET /v2/household-run-calculations/{calculation_id}` reads one. diff --git a/policyengine_api/fastapi_routes/v2/reports/routes.py b/policyengine_api/fastapi_routes/v2/reports/routes.py index fed79ce88..7306ae0a1 100644 --- a/policyengine_api/fastapi_routes/v2/reports/routes.py +++ b/policyengine_api/fastapi_routes/v2/reports/routes.py @@ -445,8 +445,12 @@ def _add_report_run_routes( "side reuses a run of its own simulation that succeeded on those " "versions; with force, both simulations are calculated again. A " "household report's sides are always calculated again, so force " - "changes nothing for it. With include_cliffs, the simulation " - "service also starts a cliff calculation for each of an economy " + "changes nothing for it. A household report's re-run may list the " + "variables its new runs calculate (variables), checked as a new " + "household report's are; any other report listing variables " + "answers 422 before anything is asked. With include_cliffs, the " + "simulation service also starts a cliff calculation for each of an " + "economy " "report run's simulation runs that has none, or whose newest one " "failed, and the answer's cliffs says how far they have got. A " "simulation service that doesn't calculate cliffs per simulation " @@ -547,7 +551,10 @@ def build_v2_report_router(dependencies: NativeRouteDependencies) -> APIRouter: "household calculations instead (a household-only country does), " "and the household it names must be stored in the country, with a " "default year; its simulations each calculate that household in its " - "default year. A budget window (kind budget_window) is checked as an " + "default year. A household report may list the variables its runs " + "calculate (variables), each checked last against the running " + "catalog version; without a list, its runs calculate every " + "variable. A budget window (kind budget_window) is checked as an " "economy report is; the simulation service creates a budget-window " "run with a report run for each year, and starts its years. label " "and description are optional and stored nowhere: a report's name and " @@ -636,7 +643,11 @@ def read() -> ReportListResponse | JSONResponse: "once both have succeeded. A household report's " "result is each simulation's calculated household, as " "/v2/household-calculations answers one, and a failed run gives each " - "side's error. A budget window's run is a budget-window run with a " + "side's error, and calculated_variables names the variables each " + "side's run calculates, whatever its status (a side is null when it " + "calculates every variable); request others with POST " + "/v2/reports/{report_id}/runs/{run_id}/household-calculations. A " + "budget window's run is a budget-window run with a " "report run per year, and its result today's budget-window format: " "each year's budget figures and their totals. With year, a budget " "window answers that year as an economy report (kind economy): the " From 3d0f583183f3b6d29b36c0414ab71deb090c9d6f Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 4 Dec 2026 02:57:44 +0400 Subject: [PATCH 09/12] Add a test for the extra-calculation read's migration log record, which fails before the fix GET /v2/household-run-calculations/{id} reads only Supabase and calls nothing, like the report reads, so its log record should not read the report route group's database or compute flags. Co-Authored-By: Claude Opus 5.5 --- tests/unit/routes/test_migration_context_logging.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/unit/routes/test_migration_context_logging.py b/tests/unit/routes/test_migration_context_logging.py index e0126292c..29895676d 100644 --- a/tests/unit/routes/test_migration_context_logging.py +++ b/tests/unit/routes/test_migration_context_logging.py @@ -723,6 +723,13 @@ class _SimulationResourceRequest(NamedTuple): _SimulationResourceRequest( "POST", "/v2/simulations", "simulation", "economy", "v2_primary" ), + _SimulationResourceRequest( + "GET", + "/v2/household-run-calculations/00000000-0000-0000-0000-000000000001", + "report", + None, + None, + ), ) From ee6dee134b27873a4d0e45393d3c7e0a9fead2c4 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 4 Dec 2026 02:59:02 +0400 Subject: [PATCH 10/12] Log the extra-calculation read like the other API v2 simulation resources, and sort two test imports GET /v2/household-run-calculations/{id} reads only Supabase, so its log record no longer reads the report route group's database or compute flags. Also sort the function-level imports of two generated-client tests. Co-Authored-By: Claude Opus 5.5 --- policyengine_api/migration_logging.py | 19 ++++++++++--------- .../libs/test_simulation_generated_client.py | 7 +++---- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/policyengine_api/migration_logging.py b/policyengine_api/migration_logging.py index 6abfdd33b..ed4c04c51 100644 --- a/policyengine_api/migration_logging.py +++ b/policyengine_api/migration_logging.py @@ -79,16 +79,17 @@ "admin", } ) -# /v2/household-calculations, /v2/reports and /v2/simulations read only -# Supabase, and compute or create only through the Cloud Run simulation -# service's v2 routes, whatever their route groups' database, entrypoint and -# compute flags select. A household calculation's submission reads the -# countries row, household and policy and sends the calculation there; a -# report's or simulation's create checks the country and policies and sends -# the request there; a read reads the tables and calls nothing. They read none -# of those flags, so none of them is checked for their log records. +# /v2/household-calculations, /v2/household-run-calculations, /v2/reports and +# /v2/simulations read only Supabase, and compute or create only through the +# Cloud Run simulation service's v2 routes, whatever their route groups' +# database, entrypoint and compute flags select. A household calculation's +# submission reads the countries row, household and policy and sends the +# calculation there; a report's or simulation's create, and a request for a +# household report run's extra calculations, check the stored rows and send the +# request there; a read reads the tables and calls nothing. They read none of +# those flags, so none of them is checked for their log records. V2_SIMULATION_SERVICE_SEGMENTS = frozenset( - {"household-calculations", "reports", "simulations"} + {"household-calculations", "household-run-calculations", "reports", "simulations"} ) V2_SIMULATION_SERVICE_ENTRYPOINT = "cloud_run_simulation_entrypoint" V2_SIMULATION_SERVICE_COMPUTE = "v2_primary" diff --git a/tests/unit/libs/test_simulation_generated_client.py b/tests/unit/libs/test_simulation_generated_client.py index 1baa5020b..9df4d50d4 100644 --- a/tests/unit/libs/test_simulation_generated_client.py +++ b/tests/unit/libs/test_simulation_generated_client.py @@ -977,9 +977,6 @@ def test_a_body_the_generated_model_would_change_is_not_sent( def test_extra_calculations_are_sent_by_the_generated_operation(case: str) -> None: # Imported here: the client release that adds the operation is pinned # with the change these tests precede. - from policyengine_api.libs.simulation_household_run_calculations import ( - household_run_calculations_request, - ) from policyengine_api_simulation_client.api.default import ( create_household_run_calculations, ) @@ -987,6 +984,9 @@ def test_extra_calculations_are_sent_by_the_generated_operation(case: str) -> No HouseholdRunCalculationRequest, ) + from policyengine_api.libs.simulation_household_run_calculations import ( + household_run_calculations_request, + ) from tests.unit.libs.test_simulation_household_run_calculations import ( CALCULATIONS_CREATED, REFORM_CALCULATION_ID, @@ -1032,7 +1032,6 @@ def test_an_extra_calculation_body_the_generated_model_would_change_is_not_sent( from policyengine_api.libs.simulation_household_run_calculations import ( household_run_calculations_request, ) - from policyengine_api.libs.simulation_service_operations import ( post_household_run_calculations, ) From f090ec825a33406480fae6afdb231d3a71e79cec Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 4 Dec 2026 02:59:09 +0400 Subject: [PATCH 11/12] Add tests for one extra calculation named on both sides; the 502 message test fails before the fix A report comparing a policy with itself has one calculation on both sides. The service already reads it once for both; the 502 message, when it cannot be read back, should name its read path once rather than twice. Co-Authored-By: Claude Opus 5.5 --- .../test_household_run_calculation_creates.py | 44 ++++++++++++++++++- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/tests/unit/v2/test_household_run_calculation_creates.py b/tests/unit/v2/test_household_run_calculation_creates.py index a01add8c6..f52ebad8d 100644 --- a/tests/unit/v2/test_household_run_calculation_creates.py +++ b/tests/unit/v2/test_household_run_calculation_creates.py @@ -159,13 +159,16 @@ class CalculatingService: It inserts a pending calculation of each side's simulation run of the stored report, as the simulation service does, and names them; with - ``insert`` false it names calculations that don't exist. With ``error`` - it raises that instead. + ``insert`` false it names calculations that don't exist, and with + ``one_calculation`` it inserts the baseline's alone and names it on both + sides, as for a report comparing a policy with itself. With ``error`` it + raises that instead. """ sessions: sessionmaker[Session] stored: StoredHouseholdReport insert: bool = True + one_calculation: bool = False error: Exception | None = None requests: list[Any] = field(default_factory=list) @@ -192,6 +195,8 @@ def create_household_run_calculations(self, request: Any) -> Any: simulation_id=stored.baseline_simulation_id, axes=axes, ) + if self.one_calculation: + return _created(baseline_id, baseline_id) reform_id = None if stored.reform_run_id is not None: assert stored.reform_simulation_id is not None @@ -295,6 +300,17 @@ def test_a_report_of_the_baseline_alone_has_no_reform_calculation( assert created.reform is None +def test_one_calculation_named_on_both_sides_is_read_for_both( + sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above +) -> None: + stored = _store(sessions) + calculating = CalculatingService(sessions, stored, one_calculation=True) + + created = _create(_service(sessions, calculating), stored) + + assert created.reform == created.baseline + + def test_a_failed_run_is_refused_before_the_simulation_service_is_asked( sessions: sessionmaker[Session], # noqa: F811 # the fixture imported above ) -> None: @@ -705,6 +721,30 @@ def test_calculations_that_cannot_be_read_back_answer_502_naming_them() -> None: } +def test_one_calculation_that_cannot_be_read_back_is_named_once() -> None: + service = FakeCalculationCreates( + error=_validators().HouseholdRunCalculationsUnreadableError( + country_id="us", + report_id=REPORT_ID, + run_id=RUN_ID, + baseline_calculation_id=CALCULATION_ID, + reform_calculation_id=CALCULATION_ID, + ) + ) + + response = calculation_route_client(service).post( + CALCULATIONS, json={"variables": VARIABLES} + ) + + assert response.status_code == 502 + assert response.json()["message"] == ( + "The simulation service created the extra calculations of report " + f"{REPORT_ID}'s run {RUN_ID}, but they could not be read back. Read " + f"them with GET /v2/household-run-calculations/{CALCULATION_ID}" + "?country_id=us rather than requesting them again." + ) + + def test_the_openapi_document_describes_the_request() -> None: document = calculation_route_client().get("/v2/openapi.json").json() schemas = document["components"]["schemas"] From b11db3fac29ab1558a97e3c12d3fbe542023509a Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 4 Dec 2026 02:59:47 +0400 Subject: [PATCH 12/12] Name one extra calculation on both sides once, and say a joined re-run keeps its variables When the extra calculations cannot be read back, the 502 message names each distinct calculation's read once. The re-run description now says a run the re-run joins keeps the variables it was created with, and how to request others. Co-Authored-By: Claude Opus 5.5 --- .../v2/household_run_calculations/routes.py | 16 ++++++++++++---- .../fastapi_routes/v2/reports/routes.py | 6 +++++- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/policyengine_api/fastapi_routes/v2/household_run_calculations/routes.py b/policyengine_api/fastapi_routes/v2/household_run_calculations/routes.py index d3276af52..95da65bcb 100644 --- a/policyengine_api/fastapi_routes/v2/household_run_calculations/routes.py +++ b/policyengine_api/fastapi_routes/v2/household_run_calculations/routes.py @@ -122,16 +122,24 @@ def _unreadable_message(error: HouseholdRunCalculationsUnreadableError) -> str: - """Say where to read the calculations the simulation service named.""" - reads = " and ".join( - f"GET /v2/household-run-calculations/{calculation_id}" - f"?country_id={error.country_id}" + """Say where to read the calculations the simulation service named. + + A report comparing a policy with itself names one calculation on both + sides, so its read is named once. + """ + calculation_ids = dict.fromkeys( + calculation_id for calculation_id in ( error.baseline_calculation_id, error.reform_calculation_id, ) if calculation_id is not None ) + reads = " and ".join( + f"GET /v2/household-run-calculations/{calculation_id}" + f"?country_id={error.country_id}" + for calculation_id in calculation_ids + ) return ( "The simulation service created the extra calculations of report " f"{error.report_id}'s run {error.run_id}, but they could not be read " diff --git a/policyengine_api/fastapi_routes/v2/reports/routes.py b/policyengine_api/fastapi_routes/v2/reports/routes.py index 7306ae0a1..c9d02403f 100644 --- a/policyengine_api/fastapi_routes/v2/reports/routes.py +++ b/policyengine_api/fastapi_routes/v2/reports/routes.py @@ -448,7 +448,11 @@ def _add_report_run_routes( "changes nothing for it. A household report's re-run may list the " "variables its new runs calculate (variables), checked as a new " "household report's are; any other report listing variables " - "answers 422 before anything is asked. With include_cliffs, the " + "answers 422 before anything is asked. A run the re-run joins keeps " + "the variables it was created with, which the report read's " + "calculated_variables names; request others with POST " + "/v2/reports/{report_id}/runs/{run_id}/household-calculations. With " + "include_cliffs, the " "simulation service also starts a cliff calculation for each of an " "economy " "report run's simulation runs that has none, or whose newest one "