From 5413e9eeb3032a47a58957da9b4785532cdd738d Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:23:42 +0400 Subject: [PATCH 1/4] Add tests for dynamics on household calculations and household reports (failing) /v2/household-calculations and household reports are to accept a dynamic_id, check it in the request's country through the economy path's dynamic check, send it to the simulation service only when named, and map the simulation service's unknown_dynamic refusal as the economy path does. These tests fail until that change. Co-Authored-By: Claude Opus 5.5 --- .../test_v2_household_calculation_reads.py | 37 ++- .../integration/test_v2_household_reports.py | 234 +++++++++++++++++- .../test_simulation_household_calculations.py | 85 +++++++ ...st_simulation_household_report_requests.py | 94 +++++++ .../unit/v2/household_calculation_support.py | 55 ++++ ...t_household_calculation_database_routes.py | 129 +++++++++- .../v2/test_household_calculation_inputs.py | 17 ++ .../v2/test_household_calculation_routes.py | 68 +++++ .../v2/test_household_calculation_service.py | 124 ++++++++++ tests/unit/v2/test_household_report_routes.py | 69 ++++++ .../v2/test_household_report_submissions.py | 161 +++++++++++- .../unit/v2/test_report_rerun_submissions.py | 21 ++ 12 files changed, 1076 insertions(+), 18 deletions(-) diff --git a/tests/integration/test_v2_household_calculation_reads.py b/tests/integration/test_v2_household_calculation_reads.py index 7540aaf15..bb51123ed 100644 --- a/tests/integration/test_v2_household_calculation_reads.py +++ b/tests/integration/test_v2_household_calculation_reads.py @@ -22,11 +22,15 @@ from sqlmodel import col from policyengine_api.constants import REPO -from policyengine_api.data.v2.models import HouseholdJob +from policyengine_api.data.v2.models import Dynamic, HouseholdJob from policyengine_api.services.v2.countries.database_session import ( CountryDatabaseSession, ) from policyengine_api.services.v2.countries.services import V2CountryService +from policyengine_api.services.v2.dynamics.database_session import ( + DynamicDatabaseSession, +) +from policyengine_api.services.v2.dynamics.services import V2DynamicService from policyengine_api.services.v2.household_calculations.database_session import ( HouseholdCalculationDatabaseSession, ) @@ -82,6 +86,8 @@ class StoredJobs: refused: UUID failed_unexpectedly: UUID pending: UUID + with_dynamic: UUID + dynamic_id: UUID def _insert_job( @@ -124,6 +130,18 @@ def stored_jobs( refused=uuid4(), failed_unexpectedly=uuid4(), pending=uuid4(), + with_dynamic=uuid4(), + dynamic_id=uuid4(), + ) + add_row( + session, + Dynamic, + id=jobs.dynamic_id, + country_id="us", + tax_benefit_model_id=rows.model_id, + tax_benefit_model_version_id=rows.version_id, + canonicalization_version=1, + content_hash=uuid4().hex * 2, ) _insert_job( session, @@ -152,6 +170,9 @@ def stored_jobs( completed_at=COMPLETED_AT, ) _insert_job(session, rows, jobs.pending, "pending") + _insert_job( + session, rows, jobs.with_dynamic, "pending", dynamic_id=jobs.dynamic_id + ) try: yield jobs finally: @@ -161,6 +182,7 @@ def stored_jobs( col(HouseholdJob.household_id) == rows.household_id ) ) + session.execute(delete(Dynamic).where(col(Dynamic.id) == jobs.dynamic_id)) delete_public_api_rows(session, rows) @@ -182,6 +204,9 @@ def runtime_service( policies=V2PolicyService( PolicyDatabaseSession(sessions), running_policyengine_version="6.10.0" ), + dynamics=V2DynamicService( + DynamicDatabaseSession(sessions), running_policyengine_version="6.10.0" + ), database_session=HouseholdCalculationDatabaseSession(sessions), simulation_factory=_no_simulation_service, ) @@ -196,6 +221,7 @@ def test_the_runtime_role_reads_a_succeeded_calculation_in_its_stored_order( assert calculation.household_id == stored_jobs.public_api_rows.household_id assert calculation.catalog_version_id == stored_jobs.public_api_rows.version_id assert calculation.policy_id is None + assert calculation.dynamic_id is None assert calculation.status == "succeeded" assert calculation.completed_at == COMPLETED_AT assert calculation.error is None @@ -242,3 +268,12 @@ def test_the_runtime_role_reads_an_unfinished_calculation( def test_an_unknown_calculation_is_not_found(stored_jobs, runtime_service) -> None: with pytest.raises(HouseholdCalculationNotFoundError): runtime_service.get_calculation(uuid4()) + + +def test_the_runtime_role_reads_the_dynamic_a_calculation_names( + stored_jobs, runtime_service +) -> None: + calculation = runtime_service.get_calculation(stored_jobs.with_dynamic) + + assert calculation.dynamic_id == stored_jobs.dynamic_id + assert calculation.policy_id is None diff --git a/tests/integration/test_v2_household_reports.py b/tests/integration/test_v2_household_reports.py index 76dd5320f..8daa6244f 100644 --- a/tests/integration/test_v2_household_reports.py +++ b/tests/integration/test_v2_household_reports.py @@ -1,8 +1,8 @@ """Create, read and list household reports through /v2/reports on migrated PostgreSQL. The routes run as API v1's runtime role, so the tests prove its -declared privileges cover every read: the countries row, the stored household -and policies the checks read, and the reports, simulations, runs and +declared privileges cover every read: the countries row, the stored household, +policies and dynamics the checks read, and the reports, simulations, runs and calculated households the reads return (rule ``api.v2.runtime-privileges-tested-as-runtime-role``). The rows the simulation service and its household functions write are stored by the @@ -22,10 +22,13 @@ from alembic.config import Config from fastapi.testclient import TestClient from flask import Flask +from sqlalchemy import delete, select +from sqlmodel import col from policyengine_api.asgi_factory import create_asgi_app from policyengine_api.constants import REPO from policyengine_api.data.v2.models import ( + Dynamic, Household, Report, ReportRun, @@ -58,6 +61,7 @@ ) from policyengine_api.services.v2.simulation_service.types import ( PackageVersions, + StartedReportRun, SubmittedReport, ) from policyengine_api.services.v2.stored_reports.database_session import ( @@ -79,6 +83,7 @@ from policyengine_api.services.v2.simulation_service.types import ( HouseholdReportCreationInput, + ReportRerunInput, ) from tests.integration.conftest import ManagedV2Roles from tests.integration.stored_report_rows import CatalogRows @@ -163,12 +168,20 @@ def finished(self) -> bool: return self.status in {"succeeded", "failed"} +@dataclass(frozen=True) +class HouseholdSideToStore: + """A household simulation's policy and dynamic, each None for none.""" + + policy_id: UUID | None + dynamic_id: UUID | None = None + + def store_household_simulation( session: Session, catalog: CatalogRows, household_id: UUID, *, - policy_id: UUID | None, + side: HouseholdSideToStore, run: SimulationRunToStore, ) -> tuple[UUID, UUID]: """Store a household simulation and one run; return both IDs.""" @@ -179,11 +192,30 @@ def store_household_simulation( id=simulation_id, simulation_type="household", household_id=household_id, - policy_id=policy_id, + policy_id=side.policy_id, + dynamic_id=side.dynamic_id, tax_benefit_model_version_id=catalog.version_id, year=2026, ) catalog.simulation_ids.append(simulation_id) + return simulation_id, store_household_simulation_run( + session, catalog, simulation_id, run + ) + + +def store_household_simulation_run( + session: Session, + catalog: CatalogRows, + simulation_id: UUID, + run: SimulationRunToStore, + *, + forced: bool = False, +) -> UUID: + """Store a run of a stored household simulation; return its ID. + + ``forced`` marks a run calculated again on versions it already has a run + on, which a household report's re-run always is. + """ run_id = uuid4() # A run without a calculated household holds SQL NULL, not JSON null. calculated = {} if run.document is None else {"household_result": run.document} @@ -197,10 +229,11 @@ def store_household_simulation( status=run.status, started_at=STARTED_AT, completed_at=STARTED_AT + timedelta(minutes=1) if run.finished else None, + forced=forced, **calculated, **CURRENT_VERSIONS, ) - return simulation_id, run_id + return run_id @dataclass(frozen=True) @@ -211,11 +244,13 @@ class HouseholdReportToStore: Without it, each side's run has the report run's status and, once succeeded, its calculated household. Without ``with_reform``, it is a report of the baseline alone, and the reform's run is not stored. + ``dynamic_ids`` are the baseline's and the reform's dynamics. """ status: str = "succeeded" with_reform: bool = True side_runs: tuple[SimulationRunToStore, SimulationRunToStore] | None = None + dynamic_ids: tuple[UUID | None, UUID | None] = (None, None) def runs(self) -> tuple[SimulationRunToStore, SimulationRunToStore]: """Return the baseline's and the reform's simulation runs to store.""" @@ -248,8 +283,13 @@ def store_household_report( status = report.status with_reform = report.with_reform baseline_run, reform_run = report.runs() + baseline_dynamic_id, reform_dynamic_id = report.dynamic_ids baseline_id, baseline_run_id = store_household_simulation( - session, catalog, household_id, policy_id=None, run=baseline_run + session, + catalog, + household_id, + side=HouseholdSideToStore(policy_id=None, dynamic_id=baseline_dynamic_id), + run=baseline_run, ) reform_id = reform_run_id = None if with_reform: @@ -257,7 +297,9 @@ def store_household_report( session, catalog, household_id, - policy_id=catalog.policy_id, + side=HouseholdSideToStore( + policy_id=catalog.policy_id, dynamic_id=reform_dynamic_id + ), run=reform_run, ) report_id = uuid4() @@ -304,6 +346,7 @@ class StoringHouseholdReportService: owner_sessions: sessionmaker[Session] catalog: CatalogRows household_reports: list[HouseholdReportCreationInput] = field(default_factory=list) + reruns: list[ReportRerunInput] = field(default_factory=list) def submit_household_report( self, report: HouseholdReportCreationInput @@ -314,12 +357,57 @@ def submit_household_report( session, self.catalog, report.household_id, - HouseholdReportToStore(status="pending"), + HouseholdReportToStore( + status="pending", + with_reform=report.reform is not None, + dynamic_ids=( + report.baseline.dynamic_id, + None if report.reform is None else report.reform.dynamic_id, + ), + ), ) return SubmittedReport( report_id=stored.report_id, report_run_id=stored.report_run_id ) + def rerun_report(self, rerun: ReportRerunInput) -> StartedReportRun: + """Store a pending run of the report's own simulations, as a re-run does. + + A household report's sides are always calculated again, so the new + runs are forced, as the simulation service creates them. + """ + self.reruns.append(rerun) + pending = SimulationRunToStore("pending", None) + with self.owner_sessions.begin() as session: + report = session.execute( + select( + col(Report.baseline_simulation_id), + col(Report.reform_simulation_id), + ).where(col(Report.id) == rerun.report_id) + ).one() + simulation_run_ids = [ + None + if simulation_id is None + else store_household_simulation_run( + session, self.catalog, simulation_id, pending, forced=True + ) + for simulation_id in report + ] + report_run_id = uuid4() + add_row( + session, + ReportRun, + id=report_run_id, + report_id=rerun.report_id, + baseline_simulation_run_id=simulation_run_ids[0], + reform_simulation_run_id=simulation_run_ids[1], + status="pending", + forced=True, + started_at=STARTED_AT + timedelta(days=1), + **CURRENT_VERSIONS, + ) + return StartedReportRun(report_run_id=report_run_id) + @pytest.fixture def owner_sessions(v2_owner_sessions: sessionmaker[Session]) -> sessionmaker[Session]: @@ -334,6 +422,40 @@ def household_only_uk(owner_sessions: sessionmaker[Session]) -> Iterator[Catalog yield uk_catalog +@pytest.fixture +def stored_dynamic_ids( + owner_sessions: sessionmaker[Session], household_only_uk: CatalogRows +) -> Iterator[list[UUID]]: + """Collect the dynamics a test stores, and delete them before their catalog.""" + dynamic_ids: list[UUID] = [] + yield dynamic_ids + with owner_sessions.begin() as session: + session.execute(delete(Dynamic).where(col(Dynamic.id).in_(dynamic_ids))) + + +def store_dynamic( + session: Session, + catalog: CatalogRows, + dynamic_ids: list[UUID], + *, + country_id: str | None = None, +) -> UUID: + """Store a dynamic on the catalog's version, in its country unless named.""" + dynamic_id = uuid4() + add_row( + session, + Dynamic, + id=dynamic_id, + country_id=country_id or catalog.country, + tax_benefit_model_id=catalog.model_id, + tax_benefit_model_version_id=catalog.version_id, + canonicalization_version=1, + content_hash=uuid4().hex * 2, + ) + dynamic_ids.append(dynamic_id) + return dynamic_id + + @pytest.fixture def runtime_sessions( managed_v2_roles: ManagedV2Roles, @@ -621,3 +743,99 @@ def test_a_household_only_country_still_refuses_economy_reports( assert response.status_code == 422 assert "Economy calculations are not available" in response.json()["message"] + + +def test_a_household_report_naming_a_dynamic_on_each_side_is_checked_and_sent( + owner_sessions: sessionmaker[Session], + household_only_uk: CatalogRows, + stored_dynamic_ids: list[UUID], + runtime_sessions: sessionmaker[Session], +) -> None: + catalog = household_only_uk + with owner_sessions.begin() as session: + household_id = store_household(session, catalog) + dynamic_id = store_dynamic(session, catalog, stored_dynamic_ids) + simulation_service = StoringHouseholdReportService(owner_sessions, catalog) + body = { + **household_body(household_id, catalog.policy_id), + "baseline": {"dynamic_id": str(dynamic_id)}, + "reform": {"policy_id": str(catalog.policy_id), "dynamic_id": str(dynamic_id)}, + } + + response = client_for(runtime_sessions, simulation_service).post( + "/v2/reports?country_id=uk", json=body + ) + + assert response.status_code == 201, response.text + (sent,) = simulation_service.household_reports + assert sent.baseline.dynamic_id == dynamic_id + assert sent.reform is not None + assert sent.reform.dynamic_id == dynamic_id + item = response.json()["result"]["item"] + assert item["baseline_simulation"]["dynamic_id"] == str(dynamic_id) + assert item["reform_simulation"]["dynamic_id"] == str(dynamic_id) + + +@pytest.mark.parametrize("stored_in", ["us", None]) +def test_a_household_reports_dynamic_the_country_does_not_store_is_not_sent( + owner_sessions: sessionmaker[Session], + household_only_uk: CatalogRows, + stored_dynamic_ids: list[UUID], + runtime_sessions: sessionmaker[Session], + stored_in: str | None, +) -> None: + catalog = household_only_uk + with owner_sessions.begin() as session: + household_id = store_household(session, catalog) + dynamic_id = ( + uuid4() + if stored_in is None + else store_dynamic( + session, catalog, stored_dynamic_ids, country_id=stored_in + ) + ) + simulation_service = StoringHouseholdReportService(owner_sessions, catalog) + body = { + **household_body(household_id, catalog.policy_id), + "reform": {"policy_id": str(catalog.policy_id), "dynamic_id": str(dynamic_id)}, + } + + response = client_for(runtime_sessions, simulation_service).post( + "/v2/reports?country_id=uk", json=body + ) + + assert response.status_code == 404, response.text + assert str(dynamic_id) in response.json()["message"] + assert simulation_service.household_reports == [] + + +def test_a_household_reports_rerun_keeps_each_sides_dynamic( + owner_sessions: sessionmaker[Session], + household_only_uk: CatalogRows, + stored_dynamic_ids: list[UUID], + runtime_sessions: sessionmaker[Session], +) -> None: + catalog = household_only_uk + with owner_sessions.begin() as session: + household_id = store_household(session, catalog) + dynamic_id = store_dynamic(session, catalog, stored_dynamic_ids) + stored = store_household_report( + session, + catalog, + household_id, + HouseholdReportToStore(dynamic_ids=(dynamic_id, dynamic_id)), + ) + simulation_service = StoringHouseholdReportService(owner_sessions, catalog) + + response = client_for(runtime_sessions, simulation_service).post( + f"/v2/reports/{stored.report_id}/runs?country_id=uk", json={} + ) + + assert response.status_code == 201, response.text + (rerun,) = simulation_service.reruns + assert (rerun.report_id, rerun.kind) == (stored.report_id, "household") + item = response.json()["result"]["item"] + assert item["status"] == "pending" + assert item["run"]["id"] != str(stored.report_run_id) + assert item["baseline_simulation"]["dynamic_id"] == str(dynamic_id) + assert item["reform_simulation"]["dynamic_id"] == str(dynamic_id) diff --git a/tests/unit/libs/test_simulation_household_calculations.py b/tests/unit/libs/test_simulation_household_calculations.py index 502e70f55..02bfe0b45 100644 --- a/tests/unit/libs/test_simulation_household_calculations.py +++ b/tests/unit/libs/test_simulation_household_calculations.py @@ -29,6 +29,8 @@ ) from tests.fixtures.household_calculation_documents import JOB_ID from tests.unit.v2.household_calculation_support import ( + ASSUMED_PARAMETER, + DYNAMIC_ID, HOUSEHOLD_ID, POLICY_ID, calculation_input, @@ -159,6 +161,30 @@ def test_current_law_sends_a_null_policy() -> None: assert service.sent_body()["policy_id"] is None +def test_a_calculation_naming_a_dynamic_sends_it() -> None: + service = RecordingService() + + service.client().submit(calculation_input(dynamic_id=DYNAMIC_ID)) + + assert service.sent_body() == { + "country": "us", + "household_id": str(HOUSEHOLD_ID), + "policy_id": str(POLICY_ID), + "dynamic_id": str(DYNAMIC_ID), + "add_missing_variables": False, + } + + +def test_a_calculation_without_a_dynamic_leaves_it_out() -> None: + # The simulation service before it took a dynamic refuses any request + # naming the field, so a null one is not sent. + service = RecordingService() + + service.client().submit(calculation_input(dynamic_id=None)) + + assert "dynamic_id" not in service.sent_body() + + def test_axes_and_spm_settings_are_sent_only_as_the_caller_gave_them() -> None: service = RecordingService() axis = {"name": "employment_income", "count": 5, "min": 0, "max": 50_000} @@ -266,6 +292,65 @@ def test_a_reference_the_service_cannot_find_is_unavailable_with_its_reason() -> ) +def test_a_dynamic_the_service_cannot_find_is_the_callers_error() -> None: + # As for an economy report: the 400 names a row the caller chose. + service = RecordingService( + 400, {"code": "unknown_dynamic", "detail": f"us has no dynamic {DYNAMIC_ID}"} + ) + + with pytest.raises(SimulationServiceInvalidRequestError) as refused: + service.client().submit(calculation_input(dynamic_id=DYNAMIC_ID)) + + assert _route_status(refused.value) == 422 + assert str(refused.value) == ( + "The simulation service cannot calculate this household (unknown_dynamic): " + f"us has no dynamic {DYNAMIC_ID}" + ) + + +def test_a_dynamic_refusal_whose_reason_cannot_be_read_is_unavailable() -> None: + service = RecordingService(400, {"code": "unknown_dynamic"}) + + with pytest.raises(SimulationServiceUnavailableError) as refused: + service.client().submit(calculation_input(dynamic_id=DYNAMIC_ID)) + + assert _route_status(refused.value) == 503 + assert str(refused.value) == ( + "The simulation service refused the calculation (400 unknown_dynamic)." + ) + + +def test_a_dynamic_the_service_cannot_calculate_is_refused_at_its_field() -> None: + service = RecordingService( + 422, + { + "detail": [ + { + "loc": ["body", "dynamic_id", ASSUMED_PARAMETER], + "msg": "the catalog version for .py 6.10.0 has no such parameter", + "type": "missing_parameter", + }, + { + "loc": ["body", "dynamic_id", "gov.simulation.example"], + "msg": "the policy and the dynamic both set this parameter", + "type": "overlapping_parameter", + }, + ] + }, + ) + + with pytest.raises(SimulationServiceInvalidRequestError) as refused: + service.client().submit(calculation_input(dynamic_id=DYNAMIC_ID)) + + assert _route_status(refused.value) == 422 + assert str(refused.value) == ( + "The simulation service cannot calculate this household: " + f"dynamic_id.{ASSUMED_PARAMETER}: the catalog version for .py 6.10.0 has " + "no such parameter; dynamic_id.gov.simulation.example: the policy and the " + "dynamic both set this parameter" + ) + + def test_a_refused_modal_call_gives_only_its_status_and_code() -> None: service = RecordingService( 503, diff --git a/tests/unit/libs/test_simulation_household_report_requests.py b/tests/unit/libs/test_simulation_household_report_requests.py index 1fba85fb7..f9dc327b3 100644 --- a/tests/unit/libs/test_simulation_household_report_requests.py +++ b/tests/unit/libs/test_simulation_household_report_requests.py @@ -24,6 +24,7 @@ SubmittedReport, ) from tests.unit.libs.test_simulation_reports import ( + DYNAMIC_ID, ENVIRONMENT_VARIABLES, POLICY_ID, REPORT_CREATED, @@ -34,6 +35,8 @@ ) HOUSEHOLD_ID = UUID("00000000-0000-0000-0000-00000000b101") +OTHER_DYNAMIC_ID = UUID("00000000-0000-0000-0000-00000000b102") +ASSUMED_PARAMETER = "gov.simulation.labour_supply_responses.income_elasticity" @pytest.fixture(autouse=True) @@ -93,6 +96,97 @@ def test_a_report_of_the_baseline_alone_sends_a_null_reform() -> None: } +def test_each_sides_dynamic_is_sent_with_its_policy() -> None: + # A report has one set of model assumptions (C1 · 35's Q5), but each side + # names its own dynamic, as for an economy report. + body = household_report_input( + baseline={"dynamic_id": str(DYNAMIC_ID)}, + reform={"policy_id": str(POLICY_ID), "dynamic_id": str(OTHER_DYNAMIC_ID)}, + ) + + assert household_report_request(body) == { + "country": "uk", + "report_type": "household", + "household_id": str(HOUSEHOLD_ID), + "baseline": {"policy_id": None, "dynamic_id": str(DYNAMIC_ID)}, + "reform": {"policy_id": str(POLICY_ID), "dynamic_id": str(OTHER_DYNAMIC_ID)}, + } + + +def test_a_side_without_a_dynamic_leaves_it_out() -> None: + # The simulation service before it took a dynamic refuses any side naming + # the field, so a null one is not sent. + body = household_report_input( + baseline={"policy_id": None, "dynamic_id": None}, + reform={"policy_id": str(POLICY_ID), "dynamic_id": str(DYNAMIC_ID)}, + ) + + request = household_report_request(body) + + assert request["baseline"] == {"policy_id": None} + assert request["reform"] == { + "policy_id": str(POLICY_ID), + "dynamic_id": str(DYNAMIC_ID), + } + + +def test_a_report_of_the_baseline_alone_sends_its_dynamic() -> None: + body = household_report_input(baseline={"dynamic_id": str(DYNAMIC_ID)}, reform=None) + + request = household_report_request(body) + + assert request["baseline"] == {"policy_id": None, "dynamic_id": str(DYNAMIC_ID)} + assert request["reform"] is None + + +def test_a_dynamic_the_service_cannot_find_is_the_callers_error() -> None: + service = RecordingService( + status_code=400, + body={ + "code": "unknown_dynamic", + "detail": "uk has no stored dynamic the request's reform names.", + }, + ) + + # The route answers SimulationServiceInvalidRequestError with 422. + with pytest.raises(SimulationServiceInvalidRequestError) as refused: + service.client().submit_household_report( + household_report_input(reform={"dynamic_id": str(DYNAMIC_ID)}) + ) + + assert str(refused.value) == ( + "The simulation service cannot run this request (unknown_dynamic): " + "uk has no stored dynamic the request's reform names." + ) + + +def test_a_sides_dynamic_the_service_cannot_calculate_is_refused_at_its_field() -> None: + service = RecordingService( + status_code=422, + body={ + "code": "missing_parameters", + "detail": [ + { + "loc": ["body", "reform", "dynamic_id", ASSUMED_PARAMETER], + "msg": "the catalog version for .py 6.10.0 has no such parameter", + "type": "missing_parameter", + } + ], + }, + ) + + with pytest.raises(SimulationServiceInvalidRequestError) as refused: + service.client().submit_household_report( + household_report_input(reform={"dynamic_id": str(DYNAMIC_ID)}) + ) + + assert str(refused.value) == ( + "The simulation service cannot run this request (missing_parameters): " + f"reform.dynamic_id.{ASSUMED_PARAMETER}: the catalog version for .py " + "6.10.0 has no such parameter" + ) + + def test_a_household_report_the_service_refuses_is_reported_with_its_reason() -> None: service = RecordingService( status_code=422, diff --git a/tests/unit/v2/household_calculation_support.py b/tests/unit/v2/household_calculation_support.py index a26486e72..9afce8335 100644 --- a/tests/unit/v2/household_calculation_support.py +++ b/tests/unit/v2/household_calculation_support.py @@ -7,6 +7,8 @@ from uuid import UUID from policyengine_api.services.v2.countries.types import CountryRead +from policyengine_api.services.v2.dynamics.types import CheckedDynamicRead +from policyengine_api.services.v2.dynamics.validators import DynamicNotFoundError from policyengine_api.services.v2.household_calculations.types import ( HouseholdCalculationAccepted, HouseholdCalculationInput, @@ -22,10 +24,12 @@ HOUSEHOLD_ID = UUID("00000000-0000-4000-8000-0000000000a1") POLICY_ID = UUID("00000000-0000-4000-8000-0000000000b1") +DYNAMIC_ID = UUID("00000000-0000-4000-8000-0000000000c1") MODEL_ID = UUID("00000000-0000-4000-8000-0000000000d1") CATALOG_VERSION_ID = UUID("00000000-0000-4000-8000-0000000000e1") CREATED_AT = datetime(2026, 11, 10, 12, 0, tzinfo=UTC) REFORMED_PARAMETER = "gov.irs.credits.ctc.amount.base[0].amount" +ASSUMED_PARAMETER = "gov.simulation.labor_supply_responses.elasticities.income" def household_read(*, default_year: int | None = 2026) -> HouseholdRead: @@ -65,6 +69,31 @@ def policy_read( ) +def dynamic_read( + *, missing_parameters: tuple[str, ...] | None = () +) -> CheckedDynamicRead: + """Return the stored US dynamic, checked against the running catalog.""" + return CheckedDynamicRead( + id=DYNAMIC_ID, + country_id="us", + tax_benefit_model_id=MODEL_ID, + tax_benefit_model_version_id=CATALOG_VERSION_ID, + created_at=CREATED_AT, + updated_at=CREATED_AT, + parameter_values=( + PolicyParameterValueRead( + id=DYNAMIC_ID, + parameter_id=DYNAMIC_ID, + parameter_name=ASSUMED_PARAMETER, + value=0.1, + start_date=datetime(2026, 1, 1, tzinfo=UTC), + end_date=None, + ), + ), + missing_parameters=missing_parameters, + ) + + def calculation_input(**changes: object) -> HouseholdCalculationInput: """Return a calculation of the stored household under the stored reform.""" fields: dict[str, object] = { @@ -131,6 +160,32 @@ def get_policy(self, *, country_id: str, policy_id: UUID) -> CheckedPolicyRead: return policy +@dataclass +class FakeDynamics: + """Stored dynamics by country and ID; records each read. + + With ``error``, every read raises it, as a database or catalog that + cannot be read does. + """ + + dynamics: dict[tuple[str, UUID], CheckedDynamicRead] = field( + default_factory=lambda: {("us", DYNAMIC_ID): dynamic_read()} + ) + error: Exception | None = None + reads: list[tuple[str, UUID]] = field(default_factory=list) + + def get_dynamic(self, *, country_id: str, dynamic_id: UUID) -> CheckedDynamicRead: + """Return the dynamic or raise DynamicNotFoundError.""" + self.reads.append((country_id, dynamic_id)) + if self.error is not None: + raise self.error + dynamic = self.dynamics.get((country_id, dynamic_id)) + if dynamic is None: + msg = f"Dynamic {dynamic_id} not found." + raise DynamicNotFoundError(msg) + return dynamic + + @dataclass class FakeSimulation: """The simulation service's household submission, as a scripted answer.""" diff --git a/tests/unit/v2/test_household_calculation_database_routes.py b/tests/unit/v2/test_household_calculation_database_routes.py index ad30ba9df..8002ae0da 100644 --- a/tests/unit/v2/test_household_calculation_database_routes.py +++ b/tests/unit/v2/test_household_calculation_database_routes.py @@ -1,8 +1,8 @@ """Submit household calculations through the route and the database-backed services. -The countries, households and policies services read a SQLite database with -the v2 tables, so the policy check runs the real catalog query; only the -simulation service is a stand-in. +The countries, households, policies and dynamics services read a SQLite +database with the v2 tables, so the policy and dynamic checks run the real +catalog query; only the simulation service is a stand-in. """ from __future__ import annotations @@ -20,6 +20,7 @@ from policyengine_api.asgi_factory import create_asgi_app from policyengine_api.data.v2.models import ( Country, + Dynamic, Household, Parameter, ParameterValue, @@ -41,6 +42,10 @@ CountryDatabaseSession, ) from policyengine_api.services.v2.countries.services import V2CountryService +from policyengine_api.services.v2.dynamics.database_session import ( + DynamicDatabaseSession, +) +from policyengine_api.services.v2.dynamics.services import V2DynamicService from policyengine_api.services.v2.household_calculations.database_session import ( HouseholdCalculationDatabaseSession, ) @@ -69,6 +74,8 @@ EARLIER_VERSION = "6.9.0" KEPT_PARAMETER = "gov.example.rate" REMOVED_PARAMETER = "gov.example.removed_rate" +KEPT_ASSUMPTION = "gov.simulation.example_elasticity" +REMOVED_ASSUMPTION = "gov.simulation.removed_elasticity" CALCULATIONS = "/v2/household-calculations" STORED_AT = datetime(2026, 11, 10, tzinfo=UTC) @@ -97,6 +104,32 @@ def _catalog_version( return parameters +def _dynamic(session: Session, parameters: dict[str, Parameter], hash_seed: str): + model_version = next(iter(parameters.values())).tax_benefit_model_version + dynamic = Dynamic( + country_id="us", + tax_benefit_model_id=model_version.model_id, + tax_benefit_model_version_id=model_version.id, + canonicalization_version=1, + content_hash=hash_seed * 64, + created_at=STORED_AT, + updated_at=STORED_AT, + ) + session.add(dynamic) + session.flush() + session.add_all( + ParameterValue( + parameter_id=parameter.id, + value_json=0.1, + start_date=STORED_AT, + dynamic_id=dynamic.id, + ) + for name, parameter in parameters.items() + if name.startswith("gov.simulation.") + ) + return dynamic + + def _policy(session: Session, parameters: dict[str, Parameter], hash_seed: str): model_version = next(iter(parameters.values())).tax_benefit_model_version policy = Policy( @@ -117,21 +150,27 @@ def _policy(session: Session, parameters: dict[str, Parameter], hash_seed: str): start_date=STORED_AT, policy_id=policy.id, ) - for parameter in parameters.values() + for name, parameter in parameters.items() + if not name.startswith("gov.simulation.") ) return policy @pytest.fixture def stored(sessions) -> dict[str, object]: - """Store the US, a household, and a policy on each of two catalog versions.""" + """Store the US, a household, and a policy and a dynamic on two catalog versions.""" with sessions() as session: session.add(Country(id="us", household_enabled=True, society_wide_enabled=True)) model = TaxBenefitModel(name="policyengine-us") earlier = _catalog_version( - session, model, EARLIER_VERSION, [KEPT_PARAMETER, REMOVED_PARAMETER] + session, + model, + EARLIER_VERSION, + [KEPT_PARAMETER, REMOVED_PARAMETER, KEPT_ASSUMPTION, REMOVED_ASSUMPTION], + ) + running = _catalog_version( + session, model, RUNNING_VERSION, [KEPT_PARAMETER, KEPT_ASSUMPTION] ) - running = _catalog_version(session, model, RUNNING_VERSION, [KEPT_PARAMETER]) household = Household( country_id="us", default_year=2026, @@ -144,6 +183,8 @@ def stored(sessions) -> dict[str, object]: "household": household, "earlier_policy": _policy(session, earlier, "a"), "running_policy": _policy(session, running, "b"), + "earlier_dynamic": _dynamic(session, earlier, "c"), + "running_dynamic": _dynamic(session, running, "d"), } session.commit() return {name: row.id for name, row in rows.items()} @@ -164,6 +205,10 @@ def service() -> V2HouseholdCalculationService: PolicyDatabaseSession(sessions), running_policyengine_version=RUNNING_VERSION, ), + dynamics=V2DynamicService( + DynamicDatabaseSession(sessions), + running_policyengine_version=RUNNING_VERSION, + ), database_session=HouseholdCalculationDatabaseSession(sessions), simulation_factory=lambda: simulation, ) @@ -217,6 +262,51 @@ def test_a_policy_setting_parameters_the_running_catalog_lacks_is_refused( assert simulation.submissions == [] +def test_a_dynamic_stored_on_the_running_catalog_is_submitted( + client, stored, simulation +) -> None: + body = { + **_body(stored, "running_policy"), + "dynamic_id": str(stored["running_dynamic"]), + } + + response = client.post(CALCULATIONS, json=body) + + assert response.status_code == 202 + assert response.json()["result"]["item"]["dynamic_id"] == str( + stored["running_dynamic"] + ) + (sent,) = simulation.submissions + assert sent.dynamic_id == stored["running_dynamic"] + + +def test_a_dynamic_setting_parameters_the_running_catalog_lacks_is_refused( + client, stored, simulation +) -> None: + body = {**_body(stored, None), "dynamic_id": str(stored["earlier_dynamic"])} + + response = client.post(CALCULATIONS, json=body) + + assert response.status_code == 422 + assert response.json()["code"] == "missing_parameters" + assert response.json()["missing_parameters"] == [REMOVED_ASSUMPTION] + assert response.json()["message"].startswith( + f"Dynamic {stored['earlier_dynamic']} sets" + ) + assert simulation.submissions == [] + + +def test_an_unknown_dynamic_is_not_found_in_the_database( + client, stored, simulation +) -> None: + body = {**_body(stored, "running_policy"), "dynamic_id": str(uuid4())} + + response = client.post(CALCULATIONS, json=body) + + assert response.status_code == 404 + assert simulation.submissions == [] + + def test_an_unknown_household_is_not_found_in_the_database( client, stored, simulation ) -> None: @@ -299,6 +389,10 @@ def service() -> V2HouseholdCalculationService: PolicyDatabaseSession(sessions), running_policyengine_version=RUNNING_VERSION, ), + dynamics=V2DynamicService( + DynamicDatabaseSession(sessions), + running_policyengine_version=RUNNING_VERSION, + ), database_session=HouseholdCalculationDatabaseSession(sessions), simulation_factory=lambda: ( SimulationHouseholdCalculationClient.from_environment( @@ -453,3 +547,24 @@ def test_a_failed_attempt_returns_the_attempts_observability_id( response.headers[OBSERVABILITY_ID_HEADER] == (attempted.headers[OBSERVABILITY_ID_HEADER]) ) + + +def test_a_dynamic_is_sent_to_the_simulation_service_only_when_named( + client_with_simulation_client, stored, simulation_recorder +) -> None: + with_dynamic = { + **_body(stored, "running_policy"), + "dynamic_id": str(stored["running_dynamic"]), + } + + named = client_with_simulation_client.post(CALCULATIONS, json=with_dynamic) + unnamed = client_with_simulation_client.post( + CALCULATIONS, json=_body(stored, "running_policy") + ) + + assert [named.status_code, unnamed.status_code] == [202, 202] + sent_with, sent_without = ( + json.loads(request.content) for request in simulation_recorder.requests + ) + assert sent_with["dynamic_id"] == str(stored["running_dynamic"]) + assert "dynamic_id" not in sent_without diff --git a/tests/unit/v2/test_household_calculation_inputs.py b/tests/unit/v2/test_household_calculation_inputs.py index 6a3e5864f..8bca9af33 100644 --- a/tests/unit/v2/test_household_calculation_inputs.py +++ b/tests/unit/v2/test_household_calculation_inputs.py @@ -25,6 +25,7 @@ HOUSEHOLD_ID = UUID("00000000-0000-4000-8000-0000000000a1") POLICY_ID = UUID("00000000-0000-4000-8000-0000000000b1") +DYNAMIC_ID = UUID("00000000-0000-4000-8000-0000000000c1") COUNTRIES = ( CountryRead(id="uk", household_enabled=True, society_wide_enabled=False), CountryRead(id="us", household_enabled=True, society_wide_enabled=True), @@ -46,11 +47,26 @@ def test_a_calculation_needs_only_a_country_and_a_household() -> None: assert calculation.country_id == "us" assert calculation.policy_id is None + assert calculation.dynamic_id is None assert calculation.axes is None assert calculation.add_missing_variables is False assert calculation.spm is None +@pytest.mark.parametrize("policy_id", [POLICY_ID, None]) +def test_a_calculation_may_name_a_dynamic_with_or_without_a_policy( + policy_id: UUID | None, +) -> None: + calculation = _calculation(policy_id=policy_id, dynamic_id=str(DYNAMIC_ID)) + + assert calculation.dynamic_id == DYNAMIC_ID + assert calculation.policy_id == policy_id + + +def test_a_null_dynamic_names_none() -> None: + assert _calculation(dynamic_id=None).dynamic_id is None + + def test_axis_groups_whose_grid_reaches_the_point_limit_are_accepted() -> None: calculation = _calculation( axes=[[_axis(100), _axis(100, "self_employment_income")], [_axis(100)]] @@ -94,6 +110,7 @@ def test_an_axis_keeps_only_the_keys_its_caller_gave() -> None: pytest.param({"spm": {"geography_kind": "metro"}}, id="metro-without-id"), pytest.param({"add_missing_variables": "sometimes"}, id="not-a-boolean"), pytest.param({"country_id": "fr"}, id="unsupported-country"), + pytest.param({"dynamic_id": "not-a-uuid"}, id="dynamic-not-a-uuid"), ], ) def test_a_malformed_calculation_is_refused(changes) -> None: diff --git a/tests/unit/v2/test_household_calculation_routes.py b/tests/unit/v2/test_household_calculation_routes.py index 74850a2b8..b1fccb178 100644 --- a/tests/unit/v2/test_household_calculation_routes.py +++ b/tests/unit/v2/test_household_calculation_routes.py @@ -16,6 +16,10 @@ RouteImplementation, RouteImplementationSettings, ) +from policyengine_api.services.v2.dynamics.validators import ( + DynamicNotFoundError, + DynamicParametersMissingError, +) from policyengine_api.services.v2.household_calculations.types import ( HouseholdCalculationFailure, HouseholdCalculationOutput, @@ -49,8 +53,10 @@ WARNING, ) from tests.unit.v2.household_calculation_support import ( + ASSUMED_PARAMETER, CATALOG_VERSION_ID, CREATED_AT, + DYNAMIC_ID, HOUSEHOLD_ID, POLICY_ID, REFORMED_PARAMETER, @@ -66,6 +72,7 @@ def _read(**changes: object) -> HouseholdCalculationRead: "country_id": "us", "household_id": HOUSEHOLD_ID, "policy_id": POLICY_ID, + "dynamic_id": None, "year": 2026, "catalog_version_id": CATALOG_VERSION_ID, "country_package_version": "1.450.0", @@ -105,6 +112,7 @@ def submit_calculation(self, calculation) -> HouseholdCalculationSubmitted: country_id=calculation.country_id, household_id=calculation.household_id, policy_id=calculation.policy_id, + dynamic_id=calculation.dynamic_id, year=2026, ) @@ -169,6 +177,7 @@ def test_a_calculation_is_accepted_without_an_account(client, service) -> None: "country_id": "us", "household_id": str(HOUSEHOLD_ID), "policy_id": str(POLICY_ID), + "dynamic_id": None, "year": 2026, } }, @@ -177,6 +186,19 @@ def test_a_calculation_is_accepted_without_an_account(client, service) -> None: assert calculation.country_id == "us" assert calculation.household_id == HOUSEHOLD_ID assert calculation.policy_id == POLICY_ID + assert calculation.dynamic_id is None + + +def test_a_calculation_naming_a_dynamic_reaches_the_service_and_is_answered( + client, service +) -> None: + response = client.post(CALCULATIONS, json=_body(dynamic_id=str(DYNAMIC_ID))) + + assert response.status_code == 202 + item = response.json()["result"]["item"] + assert (item["policy_id"], item["dynamic_id"]) == (str(POLICY_ID), str(DYNAMIC_ID)) + (calculation,) = service.submissions + assert calculation.dynamic_id == DYNAMIC_ID def test_axes_options_and_spm_settings_reach_the_service(client, service) -> None: @@ -251,6 +273,7 @@ def test_a_malformed_request_is_refused_before_anything_is_read( ), (HouseholdNotFoundError("Household not found."), 404, "Household not found."), (PolicyNotFoundError("Policy not found."), 404, "Policy not found."), + (DynamicNotFoundError("Dynamic not found."), 404, "Dynamic not found."), ( SimulationServiceUnavailableError("The simulation service answered 503."), 503, @@ -312,6 +335,25 @@ def test_a_policy_with_missing_parameters_is_refused_with_their_names( } +def test_a_dynamic_with_missing_parameters_is_refused_with_their_names( + client, service +) -> None: + service.error = DynamicParametersMissingError(DYNAMIC_ID, (ASSUMED_PARAMETER,)) + + response = client.post(CALCULATIONS, json=_body(dynamic_id=str(DYNAMIC_ID))) + + assert response.status_code == 422 + assert response.json() == { + "status": "error", + "message": ( + f"Dynamic {DYNAMIC_ID} sets parameters the running catalog version " + f"does not have: {ASSUMED_PARAMETER}" + ), + "code": "missing_parameters", + "missing_parameters": [ASSUMED_PARAMETER], + } + + def test_v2_storage_that_is_not_configured_answers_503() -> None: def unconfigured(): msg = "V2_RUNTIME_DATABASE_URL is required" @@ -340,6 +382,7 @@ def test_a_succeeded_calculation_reads_back_its_household(client, service) -> No "country_id": "us", "household_id": str(HOUSEHOLD_ID), "policy_id": str(POLICY_ID), + "dynamic_id": None, "year": 2026, "catalog_version_id": str(CATALOG_VERSION_ID), "country_package_version": "1.450.0", @@ -362,6 +405,16 @@ def test_a_succeeded_calculation_reads_back_its_household(client, service) -> No ] +def test_a_calculation_naming_a_dynamic_reads_it_back(client, service) -> None: + service.read_answer = _read(policy_id=None, dynamic_id=DYNAMIC_ID) + + response = client.get(f"{CALCULATIONS}/{JOB_ID}") + + assert response.status_code == 200 + item = response.json()["result"]["item"] + assert (item["policy_id"], item["dynamic_id"]) == (None, str(DYNAMIC_ID)) + + def test_a_failed_calculation_reads_back_its_error(client, service) -> None: service.read_answer = _read( status="failed", @@ -455,3 +508,18 @@ def test_openapi_documents_both_routes_and_the_missing_parameter_refusal( "code", "missing_parameters", } + + +def test_openapi_documents_the_dynamic_a_calculation_names(client) -> None: + schema = client.get("/v2/openapi.json").json() + components = schema["components"]["schemas"] + + assert "dynamic_id" in components["HouseholdCalculationRequest"]["properties"] + assert "dynamic_id" not in components["HouseholdCalculationRequest"].get( + "required", [] + ) + for item in ("HouseholdCalculationSubmittedItem", "HouseholdCalculationItem"): + assert "dynamic_id" in components[item]["required"] + submit = schema["paths"][CALCULATIONS]["post"] + assert "dynamic" in submit["responses"]["404"]["description"] + assert "dynamic" in submit["responses"]["422"]["description"] diff --git a/tests/unit/v2/test_household_calculation_service.py b/tests/unit/v2/test_household_calculation_service.py index 73335e8ab..1ae6f7cc2 100644 --- a/tests/unit/v2/test_household_calculation_service.py +++ b/tests/unit/v2/test_household_calculation_service.py @@ -8,6 +8,14 @@ import pytest from sqlalchemy.exc import OperationalError +from policyengine_api.data.v2.catalog.catalog_selection_validation import ( + MetadataCatalogUnavailableError, +) +from policyengine_api.services.v2.dynamics.validators import ( + DynamicNotFoundError, + DynamicParametersMissingError, + DynamicStorageError, +) from policyengine_api.services.v2.household_calculations.services import ( V2HouseholdCalculationService, ) @@ -27,14 +35,18 @@ ) from tests.fixtures.household_calculation_documents import JOB_ID from tests.unit.v2.household_calculation_support import ( + ASSUMED_PARAMETER, + DYNAMIC_ID, HOUSEHOLD_ID, POLICY_ID, REFORMED_PARAMETER, FakeCountries, + FakeDynamics, FakeHouseholds, FakePolicies, FakeSimulation, calculation_input, + dynamic_read, household_read, policy_read, ) @@ -57,6 +69,7 @@ def __init__(self) -> None: self.countries = FakeCountries() self.households = FakeHouseholds() self.policies = FakePolicies() + self.dynamics = FakeDynamics() self.simulation = FakeSimulation() self.simulation_requests = 0 @@ -69,6 +82,7 @@ def service(self, database=None) -> V2HouseholdCalculationService: countries=self.countries, households=self.households, policies=self.policies, + dynamics=self.dynamics, database_session=database or UnreadableDatabase(), simulation_factory=self.simulation_factory, ) @@ -200,6 +214,116 @@ def test_the_simulation_services_refusals_reach_the_caller(services, refusal) -> services.service().submit_calculation(calculation_input()) +def test_a_calculation_without_a_dynamic_reads_none(services) -> None: + submitted = services.service().submit_calculation(calculation_input()) + + assert services.dynamics.reads == [] + assert submitted.dynamic_id is None + (sent,) = services.simulation.submissions + assert sent.dynamic_id is None + + +def test_a_calculation_naming_a_dynamic_is_sent_once_it_is_checked(services) -> None: + calculation = calculation_input(dynamic_id=DYNAMIC_ID) + + submitted = services.service().submit_calculation(calculation) + + assert services.dynamics.reads == [("us", DYNAMIC_ID)] + assert services.simulation.submissions == [calculation] + assert submitted.dynamic_id == DYNAMIC_ID + assert submitted.policy_id == POLICY_ID + + +def test_a_dynamic_of_current_law_is_checked_and_sent(services) -> None: + submitted = services.service().submit_calculation( + calculation_input(policy_id=None, dynamic_id=DYNAMIC_ID) + ) + + assert services.policies.reads == [] + assert services.dynamics.reads == [("us", DYNAMIC_ID)] + assert (submitted.policy_id, submitted.dynamic_id) == (None, DYNAMIC_ID) + + +@pytest.mark.parametrize("stored_in", ["uk", None]) +def test_another_countrys_or_no_stored_dynamic_is_not_found( + services, stored_in +) -> None: + del services.dynamics.dynamics[("us", DYNAMIC_ID)] + if stored_in is not None: + services.dynamics.dynamics[(stored_in, DYNAMIC_ID)] = dynamic_read() + + with pytest.raises(DynamicNotFoundError, match=str(DYNAMIC_ID)): + services.service().submit_calculation(calculation_input(dynamic_id=DYNAMIC_ID)) + + assert services.dynamics.reads == [("us", DYNAMIC_ID)] + assert services.simulation_requests == 0 + + +def test_a_dynamic_setting_parameters_the_catalog_lacks_is_refused(services) -> None: + services.dynamics.dynamics[("us", DYNAMIC_ID)] = dynamic_read( + missing_parameters=(ASSUMED_PARAMETER,) + ) + + with pytest.raises(DynamicParametersMissingError) as refused: + services.service().submit_calculation(calculation_input(dynamic_id=DYNAMIC_ID)) + + assert isinstance(refused.value, PolicyParametersMissingError) + assert refused.value.dynamic_id == DYNAMIC_ID + assert refused.value.missing_parameters == (ASSUMED_PARAMETER,) + assert services.simulation_requests == 0 + + +def test_a_dynamic_no_published_catalog_could_check_is_sent(services) -> None: + services.dynamics.dynamics[("us", DYNAMIC_ID)] = dynamic_read( + missing_parameters=None + ) + + services.service().submit_calculation(calculation_input(dynamic_id=DYNAMIC_ID)) + + assert len(services.simulation.submissions) == 1 + + +def test_the_policy_is_checked_before_the_dynamic(services) -> None: + services.policies.policies[("us", POLICY_ID)] = policy_read( + missing_parameters=(REFORMED_PARAMETER,) + ) + + with pytest.raises(PolicyParametersMissingError) as refused: + services.service().submit_calculation(calculation_input(dynamic_id=uuid4())) + + assert not isinstance(refused.value, DynamicParametersMissingError) + assert services.dynamics.reads == [] + assert services.simulation_requests == 0 + + +def test_the_default_year_is_checked_before_the_dynamic(services) -> None: + services.households.households[("us", HOUSEHOLD_ID)] = household_read( + default_year=None + ) + + with pytest.raises(HouseholdCalculationYearError): + services.service().submit_calculation(calculation_input(dynamic_id=uuid4())) + + assert services.dynamics.reads == [] + + +@pytest.mark.parametrize( + "error", + [ + DynamicStorageError("dynamics cannot be read"), + OperationalError("SELECT dynamics", {}, Exception("connection refused")), + MetadataCatalogUnavailableError("catalog cannot be queried"), + ], +) +def test_a_dynamic_read_that_fails_is_a_storage_error(services, error) -> None: + services.dynamics.error = error + + with pytest.raises(HouseholdCalculationStorageError): + services.service().submit_calculation(calculation_input(dynamic_id=DYNAMIC_ID)) + + assert services.simulation_requests == 0 + + def test_an_unreadable_database_while_checking_is_a_storage_error(services) -> None: services.countries.error = OperationalError( "SELECT countries", {}, Exception("connection refused") diff --git a/tests/unit/v2/test_household_report_routes.py b/tests/unit/v2/test_household_report_routes.py index c78a7bd1c..e9d1cf2f0 100644 --- a/tests/unit/v2/test_household_report_routes.py +++ b/tests/unit/v2/test_household_report_routes.py @@ -8,6 +8,10 @@ import pytest +from policyengine_api.services.v2.dynamics.validators import ( + DynamicNotFoundError, + DynamicParametersMissingError, +) from policyengine_api.services.v2.household_calculations.types import ( HouseholdCalculationOutput, ) @@ -46,6 +50,8 @@ ) HOUSEHOLD_ID = UUID("00000000-0000-0000-0000-00000000e001") +DYNAMIC_ID = UUID("00000000-0000-0000-0000-00000000e002") +ASSUMED_PARAMETER = "gov.simulation.labor_supply_responses.elasticities.income" REPORTS = "/v2/reports?country_id=us" BASELINE_HOUSEHOLD = {"people": {"you": {"net_income": {"2026": 30_000.0}}}} REFORM_HOUSEHOLD = {"people": {"you": {"net_income": {"2026": 31_250.5}}}} @@ -153,6 +159,36 @@ def test_a_household_report_of_the_baseline_alone_can_be_created() -> None: assert arguments["report_input"].reform is None +def test_each_sides_dynamic_reaches_the_service_and_is_answered() -> None: + # A report has one set of model assumptions, which v3 sends on both sides + # (C1 · 35's Q5); the API keeps each side's own. + service = FakeReportService( + report=household_report_read( + baseline_simulation=ReportSimulationRead( + id=BASELINE_SIMULATION_ID, policy_id=None, dynamic_id=DYNAMIC_ID + ), + reform_simulation=ReportSimulationRead( + id=REFORM_SIMULATION_ID, policy_id=POLICY_ID, dynamic_id=DYNAMIC_ID + ), + ) + ) + body = household_body( + baseline={"dynamic_id": str(DYNAMIC_ID)}, + reform={"policy_id": str(POLICY_ID), "dynamic_id": str(DYNAMIC_ID)}, + ) + + response = report_route_client(reports=service).post(REPORTS, json=body) + + assert response.status_code == 201 + item = response.json()["result"]["item"] + assert item["baseline_simulation"]["dynamic_id"] == str(DYNAMIC_ID) + assert item["reform_simulation"]["dynamic_id"] == str(DYNAMIC_ID) + ((_, arguments),) = service.calls + report_input = arguments["report_input"] + assert report_input.baseline.dynamic_id == DYNAMIC_ID + assert report_input.reform.dynamic_id == DYNAMIC_ID + + @pytest.mark.parametrize( "changes", [ @@ -166,6 +202,9 @@ def test_a_household_report_of_the_baseline_alone_can_be_created() -> None: pytest.param({"kind": "budget"}, id="unknown-kind"), # A household report always adds every variable the household lacks. pytest.param({"add_missing_variables": True}, id="add-missing-variables"), + pytest.param( + {"baseline": {"dynamic_id": "not-a-uuid"}}, id="dynamic-not-a-uuid" + ), ], ) def test_a_household_report_outside_its_schema_is_refused_with_422( @@ -230,6 +269,33 @@ def test_a_household_report_the_checks_refuse_is_answered_with_its_reason( assert response.json()["message"] == str(error) +def test_a_household_report_naming_a_dynamic_the_country_lacks_is_404() -> None: + error = DynamicNotFoundError(f"Dynamic {DYNAMIC_ID} was not found") + service = FakeReportService(error=error) + + response = report_route_client(reports=service).post( + REPORTS, json=household_body(reform={"dynamic_id": str(DYNAMIC_ID)}) + ) + + assert response.status_code == 404 + assert response.json()["message"] == str(error) + + +def test_a_household_reports_dynamic_with_missing_parameters_is_422() -> None: + service = FakeReportService( + error=DynamicParametersMissingError(DYNAMIC_ID, (ASSUMED_PARAMETER,)) + ) + + response = report_route_client(reports=service).post( + REPORTS, json=household_body(reform={"dynamic_id": str(DYNAMIC_ID)}) + ) + + assert response.status_code == 422 + assert response.json()["code"] == "missing_parameters" + assert response.json()["missing_parameters"] == [ASSUMED_PARAMETER] + assert response.json()["message"].startswith(f"Dynamic {DYNAMIC_ID} sets") + + def test_a_household_report_answers_both_calculated_households() -> None: service = FakeReportService(report=household_report_read()) @@ -365,6 +431,9 @@ def test_the_create_routes_schema_offers_the_household_kind() -> None: # A report's name is each user's saved report's. assert "label" not in household_request["required"] assert "year" not in household_request["properties"] + side = components["HouseholdPolicyChoice"] + assert set(side["properties"]) == {"policy_id", "dynamic_id"} + assert "required" not in side # Each side's failure is read from the household function's failure # document, which always names its code. side_failure = components["HouseholdReportSideFailureItem"] diff --git a/tests/unit/v2/test_household_report_submissions.py b/tests/unit/v2/test_household_report_submissions.py index 3a8f32d54..a8c6ca16d 100644 --- a/tests/unit/v2/test_household_report_submissions.py +++ b/tests/unit/v2/test_household_report_submissions.py @@ -15,6 +15,11 @@ MetadataCatalogUnavailableError, ) from policyengine_api.services.v2.countries.types import CountryRead +from policyengine_api.services.v2.dynamics.validators import ( + DynamicNotFoundError, + DynamicParametersMissingError, + DynamicStorageError, +) from policyengine_api.services.v2.household_calculations.validators import ( HouseholdCalculationCountryError, HouseholdCalculationYearError, @@ -40,11 +45,15 @@ from tests.unit.v2.test_simulation_submissions import ( HOUSEHOLD_ONLY_UK, OTHER_POLICY_ID, + OUTDATED_DYNAMIC_ID, OUTDATED_POLICY_ID, + REMOVED_ASSUMPTIONS, REMOVED_PARAMETERS, SECOND_OUTDATED_POLICY_ID, SERVED_COUNTRIES, + STORED_DYNAMIC_ID, STORED_POLICY_ID, + UK_DYNAMIC_ID, StoredCountries, StoredDynamics, StoredPolicies, @@ -130,12 +139,13 @@ def household_submissions( countries: list[CountryRead] = SERVED_COUNTRIES, households: StoredHouseholds | None = None, policies: StoredPolicies | None = None, + dynamics: StoredDynamics | None = None, ) -> SimulationSubmissionService: return SimulationSubmissionService( countries=StoredCountries(countries=countries), households=households or StoredHouseholds(), policies=policies or StoredPolicies(), - dynamics=StoredDynamics(), + dynamics=dynamics or StoredDynamics(), client_factory=client_factory, ) @@ -273,6 +283,151 @@ def test_a_report_of_the_baseline_alone_checks_only_the_baselines_policy() -> No assert client.household_reports[0].reform is None +def test_each_sides_dynamic_is_checked_in_the_country_and_sent() -> None: + client = RecordingHouseholdReportService() + dynamics = StoredDynamics() + report = household_report_input( + baseline={"dynamic_id": str(STORED_DYNAMIC_ID)}, + reform={ + "policy_id": str(STORED_POLICY_ID), + "dynamic_id": str(STORED_DYNAMIC_ID), + }, + ) + + household_submissions(lambda: client, dynamics=dynamics).submit_household_report( + report + ) + + assert client.household_reports == [report] + assert client.household_reports[0].baseline.dynamic_id == STORED_DYNAMIC_ID + assert client.household_reports[0].reform is not None + assert client.household_reports[0].reform.dynamic_id == STORED_DYNAMIC_ID + # The one dynamic both sides name is read once. + assert dynamics.asked == [("us", STORED_DYNAMIC_ID)] + + +@pytest.mark.parametrize("side", ["baseline", "reform"]) +def test_one_side_may_name_a_dynamic_the_other_does_not(side: str) -> None: + # As for an economy report, each side keeps its own dynamic, and nothing + # requires the two to match. + client = RecordingHouseholdReportService() + dynamics = StoredDynamics() + report = household_report_input(**{side: {"dynamic_id": str(STORED_DYNAMIC_ID)}}) + + household_submissions(lambda: client, dynamics=dynamics).submit_household_report( + report + ) + + assert client.household_reports == [report] + assert dynamics.asked == [("us", STORED_DYNAMIC_ID)] + + +def test_a_household_report_without_dynamics_reads_none() -> None: + dynamics = StoredDynamics() + client = RecordingHouseholdReportService() + + household_submissions(lambda: client, dynamics=dynamics).submit_household_report( + household_report_input() + ) + + assert dynamics.asked == [] + + +@pytest.mark.parametrize("side", ["baseline", "reform"]) +def test_a_sides_dynamic_of_another_country_is_not_found(side: str) -> None: + service = household_submissions(unconfigured_client) + + with pytest.raises(DynamicNotFoundError, match=str(UK_DYNAMIC_ID)): + service.submit_household_report( + household_report_input(**{side: {"dynamic_id": str(UK_DYNAMIC_ID)}}) + ) + + +def test_a_uk_household_report_takes_a_uk_dynamic() -> None: + client = RecordingHouseholdReportService() + dynamics = StoredDynamics() + report = household_report_input( + country_id="uk", baseline={"dynamic_id": str(UK_DYNAMIC_ID)}, reform=None + ) + + household_submissions( + lambda: client, countries=HOUSEHOLD_ONLY_UK, dynamics=dynamics + ).submit_household_report(report) + + assert client.household_reports == [report] + assert dynamics.asked == [("uk", UK_DYNAMIC_ID)] + + +def test_a_sides_dynamic_setting_parameters_the_catalog_lacks_is_refused() -> None: + service = household_submissions(unconfigured_client) + + with pytest.raises(DynamicParametersMissingError) as refused: + service.submit_household_report( + household_report_input( + reform={ + "policy_id": str(STORED_POLICY_ID), + "dynamic_id": str(OUTDATED_DYNAMIC_ID), + } + ) + ) + + assert isinstance(refused.value, PolicyParametersMissingError) + assert refused.value.dynamic_id == OUTDATED_DYNAMIC_ID + assert refused.value.missing_parameters == REMOVED_ASSUMPTIONS + + +def test_a_household_reports_policies_are_checked_before_its_dynamics() -> None: + dynamics = StoredDynamics() + service = household_submissions(unconfigured_client, dynamics=dynamics) + + with pytest.raises(PolicyNotFoundError): + service.submit_household_report( + household_report_input( + baseline={"dynamic_id": str(UK_DYNAMIC_ID)}, + reform={"policy_id": str(OTHER_POLICY_ID)}, + ) + ) + + assert dynamics.asked == [] + + +def test_a_report_of_the_baseline_alone_checks_only_the_baselines_dynamic() -> None: + client = RecordingHouseholdReportService() + dynamics = StoredDynamics() + report = household_report_input( + baseline={"dynamic_id": str(STORED_DYNAMIC_ID)}, reform=None + ) + + household_submissions(lambda: client, dynamics=dynamics).submit_household_report( + report + ) + + assert dynamics.asked == [("us", STORED_DYNAMIC_ID)] + + +@pytest.mark.parametrize( + "error", + [ + DynamicStorageError("dynamics cannot be read"), + OperationalError("SELECT dynamics", {}, Exception("connection refused")), + MetadataCatalogUnavailableError("catalog cannot be queried"), + ], +) +def test_a_household_reports_dynamic_read_that_fails_is_a_storage_failure( + error: Exception, +) -> None: + service = household_submissions( + unconfigured_client, dynamics=StoredDynamics(error=error) + ) + + with pytest.raises(SubmissionStorageError) as failure: + service.submit_household_report( + household_report_input(baseline={"dynamic_id": str(STORED_DYNAMIC_ID)}) + ) + + assert failure.value.__cause__ is error + + @pytest.mark.parametrize( ("households", "policies"), [ @@ -327,7 +482,9 @@ def test_a_household_report_without_a_reform_is_of_the_baseline_alone() -> None: pytest.param({"year": 2026}, id="year"), # A household report always adds every variable the household lacks. pytest.param({"add_missing_variables": True}, id="add-missing-variables"), - pytest.param({"baseline": {"dynamic_id": str(uuid4())}}, id="dynamic"), + pytest.param( + {"baseline": {"dynamic_id": "not-a-uuid"}}, id="dynamic-not-a-uuid" + ), pytest.param({"region_code": "us"}, id="region"), pytest.param({"household_id": "not-a-uuid"}, id="household-not-a-uuid"), pytest.param({"kind": "economy"}, id="another-kind"), diff --git a/tests/unit/v2/test_report_rerun_submissions.py b/tests/unit/v2/test_report_rerun_submissions.py index 6c9552a3e..8da5511bb 100644 --- a/tests/unit/v2/test_report_rerun_submissions.py +++ b/tests/unit/v2/test_report_rerun_submissions.py @@ -246,6 +246,27 @@ def test_a_household_reports_rerun_is_sent_where_only_households_are_calculated( assert policies.asked == [STORED_POLICY_ID] +def test_a_household_reports_rerun_reads_no_dynamic() -> None: + # The re-run names only the report: the simulation service reads each + # stored side's policy and dynamic itself, so each side keeps its dynamic, + # which was checked when the report was created. + client = RecordingSimulationService() + dynamics = StoredDynamics() + service = SimulationSubmissionService( + countries=StoredCountries(society_wide_enabled=False), + households=UnreadHouseholds(), + policies=StoredPolicies(), + dynamics=dynamics, + client_factory=lambda: client, + ) + rerun = rerun_input(None, STORED_POLICY_ID, kind="household") + + service.rerun_report(rerun) + + assert client.reruns == [rerun] + assert dynamics.asked == [] + + def test_a_household_report_of_the_baseline_alone_checks_the_baseline_policy() -> None: client = RecordingSimulationService() policies = StoredPolicies() From 92b7053cbc4b7115cb3b6e0fa3edf2ac57b26161 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:32:17 +0400 Subject: [PATCH 2/4] Take a dynamic on household calculations and household reports /v2/household-calculations and each side of a household report on /v2/reports accept an optional dynamic_id. It is checked as an economy simulation's dynamic is, through require_runnable_dynamics and the same DynamicSource as /v2/dynamics: 404 when the request's country does not store it, and 422 missing_parameters when it sets parameters the running catalog version lacks, after the policy checks. Each household report side keeps its own dynamic, as economy reports do. API v1 sends a named dynamic to the simulation service and leaves a null one out of the request body, so the simulation service's release before it took a household dynamic still accepts every request without one. The household calculation client answers the simulation service's 400 unknown_dynamic as the caller's error (422), as the report client already does. Household calculations answer the dynamic_id they apply, read from household_jobs.dynamic_id. Household report re-runs still send only the report, so the simulation service keeps each side's stored dynamic. The household calculation service now takes its countries, households, policies and dynamics sources as one HouseholdCalculationSources value, and the test helpers that build it change with it. Co-Authored-By: Claude Opus 5.5 --- changelog.d/household-dynamics.added.md | 1 + docs/engineering/migration-contracts.md | 4 +- docs/generated/migration_contracts.json | 2 + .../fastapi_routes/dependencies.py | 12 ++- .../household_calculations/request_models.py | 18 +++-- .../household_calculations/response_models.py | 28 ++++--- .../v2/household_calculations/routes.py | 2 + .../libs/simulation_household_calculations.py | 59 +++++++++----- policyengine_api/libs/simulation_reports.py | 30 +++++--- .../libs/simulation_service_answers.py | 9 ++- .../v2/household_calculations/services.py | 77 ++++++++++++------- .../household_calculations/transformations.py | 2 + .../v2/household_calculations/types.py | 40 ++++++++-- .../v2/simulation_service/services.py | 36 +++++---- .../services/v2/simulation_service/types.py | 10 ++- tests/contract/registry.py | 2 + .../test_v2_household_calculation_reads.py | 20 +++-- ...t_household_calculation_database_routes.py | 41 +++++----- .../v2/test_household_calculation_service.py | 13 +++- 19 files changed, 273 insertions(+), 133 deletions(-) create mode 100644 changelog.d/household-dynamics.added.md diff --git a/changelog.d/household-dynamics.added.md b/changelog.d/household-dynamics.added.md new file mode 100644 index 000000000..b07b31e81 --- /dev/null +++ b/changelog.d/household-dynamics.added.md @@ -0,0 +1 @@ +`/v2/household-calculations` and household reports on `/v2/reports` take an optional `dynamic_id` (each report side its own), checked as economy reports check one: 404 when the request's country does not store it, and 422 `missing_parameters` for parameters the running catalog version lacks. API v1 sends a named dynamic to the simulation service, which applies it, and household calculations answer the `dynamic_id` they apply. diff --git a/docs/engineering/migration-contracts.md b/docs/engineering/migration-contracts.md index 3533d11c3..b58ae2e45 100644 --- a/docs/engineering/migration-contracts.md +++ b/docs/engineering/migration-contracts.md @@ -105,8 +105,8 @@ Generated from `policyengine_api/migration_registry.py` and `tests/contract/regi | Method | Path | Status | Route group | Required headers | Stable response fields | | --- | --- | ---: | --- | --- | --- | -| `POST` | `/v2/household-calculations` | 202 | `household` | none | `status`, `message`, `result.item.calculation_id`, `result.item.status`, `result.item.country_id`, `result.item.household_id`, `result.item.policy_id`, `result.item.year` | -| `GET` | `/v2/household-calculations/{calculation_id}` | 200 | `household` | none | `status`, `message`, `result.item.calculation_id`, `result.item.country_id`, `result.item.household_id`, `result.item.policy_id`, `result.item.year`, `result.item.catalog_version_id`, `result.item.country_package_version`, `result.item.policyengine_version`, `result.item.status`, `result.item.created_at`, `result.item.started_at`, `result.item.completed_at`, `result.item.result`, `result.item.error` | +| `POST` | `/v2/household-calculations` | 202 | `household` | none | `status`, `message`, `result.item.calculation_id`, `result.item.status`, `result.item.country_id`, `result.item.household_id`, `result.item.policy_id`, `result.item.dynamic_id`, `result.item.year` | +| `GET` | `/v2/household-calculations/{calculation_id}` | 200 | `household` | none | `status`, `message`, `result.item.calculation_id`, `result.item.country_id`, `result.item.household_id`, `result.item.policy_id`, `result.item.dynamic_id`, `result.item.year`, `result.item.catalog_version_id`, `result.item.country_package_version`, `result.item.policyengine_version`, `result.item.status`, `result.item.created_at`, `result.item.started_at`, `result.item.completed_at`, `result.item.result`, `result.item.error` | ### `user_household_associations_v2` diff --git a/docs/generated/migration_contracts.json b/docs/generated/migration_contracts.json index 52e8312de..db4514d16 100644 --- a/docs/generated/migration_contracts.json +++ b/docs/generated/migration_contracts.json @@ -550,6 +550,7 @@ "result.item.country_id", "result.item.household_id", "result.item.policy_id", + "result.item.dynamic_id", "result.item.year" ] }, @@ -566,6 +567,7 @@ "result.item.country_id", "result.item.household_id", "result.item.policy_id", + "result.item.dynamic_id", "result.item.year", "result.item.catalog_version_id", "result.item.country_package_version", diff --git a/policyengine_api/fastapi_routes/dependencies.py b/policyengine_api/fastapi_routes/dependencies.py index e886b9250..96cc1c35e 100644 --- a/policyengine_api/fastapi_routes/dependencies.py +++ b/policyengine_api/fastapi_routes/dependencies.py @@ -46,6 +46,9 @@ ) from policyengine_api.readiness import is_ready from policyengine_api.request_caller import current_request_caller +from policyengine_api.services.v2.household_calculations.types import ( + HouseholdCalculationSources, +) from policyengine_api.services.v2.metadata.process_state import ( SelectedCatalogStore, ) @@ -222,9 +225,12 @@ def _default_v2_household_calculation_service_factory() -> ( ) return V2HouseholdCalculationService( - countries=_default_v2_country_service_factory(), - households=_default_v2_household_service_factory(), - policies=_default_v2_policy_service_factory(), + sources=HouseholdCalculationSources( + countries=_default_v2_country_service_factory(), + households=_default_v2_household_service_factory(), + policies=_default_v2_policy_service_factory(), + dynamics=_default_v2_dynamic_service_factory(), + ), database_session=HouseholdCalculationDatabaseSession(get_v2_session_factory()), simulation_factory=process_simulation_household_calculation_client, ) diff --git a/policyengine_api/fastapi_routes/v2/household_calculations/request_models.py b/policyengine_api/fastapi_routes/v2/household_calculations/request_models.py index 4379aaa83..1c9aa5ac9 100644 --- a/policyengine_api/fastapi_routes/v2/household_calculations/request_models.py +++ b/policyengine_api/fastapi_routes/v2/household_calculations/request_models.py @@ -10,14 +10,16 @@ class HouseholdCalculationRequest(HouseholdCalculationInput): """A stored household to calculate under a stored policy, or current law. - ``household_id`` and ``policy_id`` name records of ``country_id`` stored - through ``/v2/households`` and ``/v2/policies``; without ``policy_id`` the - household is calculated under current law, for the household's - ``default_year``. Each group in ``axes`` varies its inputs together across - ``count`` points; several groups form a grid of at most 10,000 points. - ``add_missing_variables`` adds every variable the household lacks before - calculating. ``spm`` selects the SPM forecast scenario and geography for - a US household. Each submission starts a new calculation. + ``household_id``, ``policy_id`` and ``dynamic_id`` name records of + ``country_id`` stored through ``/v2/households``, ``/v2/policies`` and + ``/v2/dynamics``; without ``policy_id`` the household is calculated under + current law, and without ``dynamic_id`` with no model assumptions beyond + the model's defaults, for the household's ``default_year``. Each group + in ``axes`` varies its inputs together across ``count`` points; several + groups form a grid of at most 10,000 points. ``add_missing_variables`` + adds every variable the household lacks before calculating. ``spm`` + selects the SPM forecast scenario and geography for a US household. Each + submission starts a new calculation. """ def to_service_input(self) -> HouseholdCalculationInput: diff --git a/policyengine_api/fastapi_routes/v2/household_calculations/response_models.py b/policyengine_api/fastapi_routes/v2/household_calculations/response_models.py index a73f71491..1b69f656f 100644 --- a/policyengine_api/fastapi_routes/v2/household_calculations/response_models.py +++ b/policyengine_api/fastapi_routes/v2/household_calculations/response_models.py @@ -32,8 +32,9 @@ class HouseholdCalculationSubmittedItem(StrictHouseholdCalculationAPIModel): """A calculation the simulation service accepted. Poll ``GET /v2/household-calculations/{calculation_id}`` until ``status`` - is ``succeeded`` or ``failed``. ``year`` is the household's default year, - which is calculated. + is ``succeeded`` or ``failed``. ``dynamic_id`` is the dynamic whose model + assumptions apply, null for none. ``year`` is the household's default + year, which is calculated. """ calculation_id: UUID @@ -41,6 +42,7 @@ class HouseholdCalculationSubmittedItem(StrictHouseholdCalculationAPIModel): country_id: str household_id: UUID policy_id: UUID | None + dynamic_id: UUID | None year: int @classmethod @@ -90,15 +92,17 @@ class HouseholdCalculationItem(StrictHouseholdCalculationAPIModel): """A household calculation and its outcome. ``status`` moves from ``pending`` through ``running`` to ``succeeded``, - with ``result``, or ``failed``, with ``error``. ``catalog_version_id``, - ``country_package_version`` and ``policyengine_version`` are those the - calculation runs with. + with ``result``, or ``failed``, with ``error``. ``dynamic_id`` is the + dynamic whose model assumptions apply, null for none or once the dynamic + is deleted. ``catalog_version_id``, ``country_package_version`` and + ``policyengine_version`` are those the calculation runs with. """ calculation_id: UUID country_id: str household_id: UUID policy_id: UUID | None + dynamic_id: UUID | None year: int catalog_version_id: UUID country_package_version: str @@ -158,7 +162,10 @@ class HouseholdCalculationResponse( HOUSEHOLD_CALCULATION_ERROR_RESPONSES: dict[int | str, dict[str, Any]] = { 404: { "model": V2ErrorResponse, - "description": "The household, policy or calculation does not exist.", + "description": ( + "The household, policy, dynamic or calculation does not exist in " + "the country." + ), }, 422: { "model": V2ErrorResponse, @@ -199,9 +206,12 @@ class HouseholdCalculationResponse( "description": ( "The request does not match the schema; the country does not offer " "household calculations; the household has no default year; the " - "policy sets parameters the running catalog version does not have " - "(code missing_parameters, which names them); or the simulation " - "service refuses the caller's data, with its reason in the message." + "policy or the dynamic sets parameters the running catalog version " + "does not have (code missing_parameters, which names them; the " + "policy is checked first); or the simulation service refuses the " + "caller's data, with its reason in the message: its 422, such as a " + "parameter both the policy and the dynamic set, or its 400 for a " + "dynamic it does not find, with its code." ), }, 503: { diff --git a/policyengine_api/fastapi_routes/v2/household_calculations/routes.py b/policyengine_api/fastapi_routes/v2/household_calculations/routes.py index f78611256..607b75da9 100644 --- a/policyengine_api/fastapi_routes/v2/household_calculations/routes.py +++ b/policyengine_api/fastapi_routes/v2/household_calculations/routes.py @@ -39,6 +39,7 @@ ) from policyengine_api.observability.identifiers import OBSERVABILITY_ID_HEADER from policyengine_api.request_context import current_observability_id +from policyengine_api.services.v2.dynamics.validators import DynamicNotFoundError from policyengine_api.services.v2.household_calculations.validators import ( HouseholdCalculationCountryError, HouseholdCalculationNotFoundError, @@ -82,6 +83,7 @@ ( HouseholdNotFoundError, PolicyNotFoundError, + DynamicNotFoundError, HouseholdCalculationNotFoundError, ), 404, diff --git a/policyengine_api/libs/simulation_household_calculations.py b/policyengine_api/libs/simulation_household_calculations.py index 467f097db..ad451a16d 100644 --- a/policyengine_api/libs/simulation_household_calculations.py +++ b/policyengine_api/libs/simulation_household_calculations.py @@ -9,9 +9,11 @@ ID headers, transport and instrumentation as every other simulation call. The request names the country, the stored household and the stored policy -(null for current law), ``add_missing_variables``, and the axes and SPM -settings only when the caller gave them. The simulation service's answers -are read as follows. +(null for current law), ``add_missing_variables``, and the stored dynamic, +the axes and the SPM settings only when the caller gave them: the +simulation service's release before it took a dynamic refuses any request +naming the field, so a calculation without one is accepted by either +release. The simulation service's answers are read as follows. The job was created: @@ -21,7 +23,8 @@ (SimulationServiceUnavailableError, which the route answers 503): - 400 when a household, policy or catalog version it names does not exist - (the Public API checks the first two first), with the service's reason; + (the Public API checks the first two first), with the service's reason, + unless its code names a row the caller chose (below); - 401, 403, 404, 405, 413 and 429, which its authentication, routing, body-size and rate limits answer before its route runs; - its own 503, which names its code, when it is not configured, cannot read @@ -33,10 +36,17 @@ The caller's data was refused: -- 422 with its reasons (a malformed request, or one its household contract - refuses), one per field as FastAPI writes them, which reach the caller as - SimulationServiceInvalidRequestError. A 422 of another shape is - unavailable. +- 422 with its reasons (a malformed request, one its household contract + refuses, a dynamic setting parameters its catalog version lacks, or a + parameter both the policy and the dynamic set, each located at + ``dynamic_id``), one per field as FastAPI writes them, which reach the + caller as SimulationServiceInvalidRequestError. A 422 of another shape is + unavailable; +- 400 with a code in ``CALLER_ROW_REFUSAL_CODES`` and a readable reason, + as the report route's: ``unknown_dynamic`` for a dynamic the country does + not store (API v1 checks it first), which reaches the caller as + SimulationServiceInvalidRequestError with its code and reason, as on the + economy routes. One whose reason cannot be read is unavailable. The job may exist, and no route finds a household job without its ID, so the message asks the caller to submit the calculation again and says that this @@ -95,6 +105,7 @@ from pydantic import ValidationError from policyengine_api.libs.simulation_service_answers import ( + CALLER_ROW_REFUSAL_CODES, PROXY_STAND_IN_STATUSES, AnswerModel, Refusal, @@ -184,8 +195,9 @@ def household_calculation_request( ) -> dict[str, Any]: """Return the simulation service's request body for the calculation. - ``axes`` and ``spm`` are sent only when the caller gave them; each axis - and the SPM settings keep only the fields the caller gave. + ``dynamic_id``, ``axes`` and ``spm`` are sent only when the caller gave + them; each axis and the SPM settings keep only the fields the caller + gave. """ body: dict[str, Any] = { "country": calculation.country_id, @@ -193,8 +205,10 @@ def household_calculation_request( "policy_id": ( None if calculation.policy_id is None else str(calculation.policy_id) ), - "add_missing_variables": calculation.add_missing_variables, } + if calculation.dynamic_id is not None: + body["dynamic_id"] = str(calculation.dynamic_id) + body["add_missing_variables"] = calculation.add_missing_variables if calculation.axes is not None: body["axes"] = [ [axis.model_dump(mode="json", exclude_unset=True) for axis in group] @@ -229,10 +243,14 @@ def post_household_calculation( return SimulationAnswer(status_code=response.status_code, content=response.content) -def _invalid_request_reason(refusal: Refusal) -> str: - """Return the service's reason, or each refused field and why.""" +def _invalid_request_reason(refusal: Refusal, code: str | None = None) -> str: + """Return the service's reason, or each refused field and why. + + ``code`` is the service's code, named when given. + """ + named_code = "" if code is None else f" ({code})" return ( - "The simulation service cannot calculate this household: " + f"The simulation service cannot calculate this household{named_code}: " f"{refusal_reason(refusal)}" ) @@ -336,11 +354,12 @@ def submit( """Submit the calculation and return the job the service created. Raise SimulationServiceInvalidRequestError with the service's reasons - when it refuses the caller's data (422); + when it refuses the caller's data (422, or 400 naming a row the + caller chose, such as ``unknown_dynamic``); SimulationServiceUnavailableError when no job of the submission will - run (its 400, the statuses it answers before its route runs, its own - 503, a connection never made or a gateway token that cannot be - fetched); SimulationServiceInternalError when it failed (500); and + run (any other 400, the statuses it answers before its route runs, + its own 503, a connection never made or a gateway token that cannot + be fetched); SimulationServiceInternalError when it failed (500); and SimulationServiceAnswerUnreadableError when it accepted the calculation but its answer cannot be read, it answered any other status, its answer was lost after the submission may have reached it, @@ -384,6 +403,10 @@ def _accepted_job(answer: SimulationAnswer) -> HouseholdCalculationAccepted: _invalid_request_reason(read.refusal) ) if read.status_code == HTTPStatus.BAD_REQUEST: + if read.refusal is not None and read.code in CALLER_ROW_REFUSAL_CODES: + raise SimulationServiceInvalidRequestError( + _invalid_request_reason(read.refusal, read.code) + ) raise SimulationServiceUnavailableError(_refused(read)) if read.status_code in STATUSES_AFTER_WHICH_NO_JOB_RUNS: raise SimulationServiceUnavailableError(_unavailable(read)) diff --git a/policyengine_api/libs/simulation_reports.py b/policyengine_api/libs/simulation_reports.py index 5549c4b8b..ab7b4228c 100644 --- a/policyengine_api/libs/simulation_reports.py +++ b/policyengine_api/libs/simulation_reports.py @@ -21,13 +21,13 @@ ``POST /reports`` as ``report_type`` ``budget_window``, naming its first year and ``budget_window_size`` in place of the year, and no ``include_cliffs``. A household report goes there too, as ``report_type`` -``household``, naming the stored household, each simulation's policy (the -reform null for a report of the baseline alone), but no year: the -simulation service calculates the household's default year, adding every -variable the household lacks. None names a PolicyEngine.py version: the -simulation service runs its default worker's. None names a label or a -description, which belong to users' saved reports. The simulation service -answers: +``household``, naming the stored household, each simulation's policy, and +its dynamic only when it names one (the reform null for a report of the +baseline alone), but no year: the simulation service calculates the +household's default year, adding every variable the household lacks. None +names a PolicyEngine.py version: the simulation service runs its default +worker's. None names a label or a description, which belong to users' +saved reports. The simulation service answers: - 201 or 202 with the created record's ID and its first run's ID: for a budget window, its budget-window run's ID (``budget_window_run_id``). One @@ -276,13 +276,25 @@ def budget_window_request(report: BudgetWindowReportCreationInput) -> dict[str, def _household_policy_choice(choice: HouseholdPolicyChoice) -> dict[str, str | None]: - return {"policy_id": None if choice.policy_id is None else str(choice.policy_id)} + """Return a household side's policy, and its dynamic only when it names one. + + The simulation service's release before it took a household side's + dynamic refuses any side naming the field, so a side without one sends + none and is accepted by either release. + """ + side: dict[str, str | None] = { + "policy_id": None if choice.policy_id is None else str(choice.policy_id) + } + if choice.dynamic_id is not None: + side["dynamic_id"] = str(choice.dynamic_id) + return side def household_report_request(report: HouseholdReportCreationInput) -> dict[str, Any]: """Return the simulation service's request body for the household report. - ``reform`` is null for a report of the baseline alone. + ``reform`` is null for a report of the baseline alone. Each side names + its dynamic only when it has one. """ return { "country": report.country_id, diff --git a/policyengine_api/libs/simulation_service_answers.py b/policyengine_api/libs/simulation_service_answers.py index 1f557e7c1..7721576bc 100644 --- a/policyengine_api/libs/simulation_service_answers.py +++ b/policyengine_api/libs/simulation_service_answers.py @@ -26,8 +26,9 @@ and the report re-run client, the statuses of a created record (``CREATED_STATUSES``), of a refusal (``REFUSAL_STATUSES``) and of an answer sent before the service's route writes anything - (``SENT_BEFORE_ROUTE_STATUSES``), and the codes of a refusal of a row the - Public API does not check (``CALLER_ROW_REFUSAL_CODES``); + (``SENT_BEFORE_ROUTE_STATUSES``), and, for those and the household + calculation client, the codes of a refusal of a row the caller chose + (``CALLER_ROW_REFUSAL_CODES``); - the messages for an answer lost after the request may have arrived (``answer_lost``) and for a failure after the service may have created what was submitted (``created_but_failed``), each ending with @@ -78,7 +79,9 @@ # dataset), or a dynamic the catalog version its default worker runs does not # have. Each is the caller's error and answers 422. Any other 400 is a state # of the service, such as a catalog version missing while a release deploys, -# or a row the Public API already checked, and answers 503. +# or a row the Public API already checked, and answers 503. Of these, the +# household calculation route answers only ``unknown_dynamic``, for a dynamic +# the country does not store. CALLER_ROW_REFUSAL_CODES = frozenset( {"unknown_region", "unknown_dataset", "unknown_dynamic"} ) diff --git a/policyengine_api/services/v2/household_calculations/services.py b/policyengine_api/services/v2/household_calculations/services.py index 3360040f0..cf899f3b7 100644 --- a/policyengine_api/services/v2/household_calculations/services.py +++ b/policyengine_api/services/v2/household_calculations/services.py @@ -5,11 +5,15 @@ stored household and policy exist in that country, through the same services as ``/v2/households`` and ``/v2/policies`` (so one of another country, or none, is not found), that the household has a default year, and -that the policy sets no parameter the running catalog version lacks. Only -then does it send the simulation service the IDs and options. The simulation -service reads the household, the policy's parameter values and the catalog -version from the Public API's tables itself, inserts the job and calculates -the household's default year; each submission creates a new job. +that the policy sets no parameter the running catalog version lacks. A +dynamic the calculation names is then checked as an economy simulation's +is, by ``simulation_service.services.require_runnable_dynamics`` through the +same service as ``/v2/dynamics``: stored in the country, and setting no +parameter the running catalog version lacks. Only then does it send the +simulation service the IDs and options. The simulation service reads the +household, the policy's and the dynamic's parameter values and the catalog +version from API v1's tables itself, inserts the job and calculates the +household's default year; each submission creates a new job. Reading a calculation reads its job from ``household_jobs``, which the simulation service inserts and its household function completes; it never @@ -43,6 +47,9 @@ from policyengine_api.services.v2.policies.validators import ( require_policy_parameters_present, ) +from policyengine_api.services.v2.simulation_service.validators import ( + SubmissionStorageError, +) if TYPE_CHECKING: from collections.abc import Callable, Iterator @@ -52,13 +59,11 @@ HouseholdCalculationDatabaseSession, ) from policyengine_api.services.v2.household_calculations.types import ( - CountrySource, HouseholdCalculationInput, HouseholdCalculationRead, + HouseholdCalculationSources, HouseholdCalculationSubmitted, HouseholdCalculationSubmitter, - HouseholdSource, - PolicySource, ) @@ -67,11 +72,17 @@ def _storage_failures() -> Iterator[None]: """Raise HouseholdCalculationStorageError for a failed database read. That includes the policy check's catalog query, which the policy service - reports as MetadataCatalogUnavailableError. + reports as MetadataCatalogUnavailableError, and the dynamic check's + reads, which ``require_runnable_dynamics`` reports as + SubmissionStorageError. """ try: yield - except (SQLAlchemyError, MetadataCatalogUnavailableError) as error: + except ( + SQLAlchemyError, + MetadataCatalogUnavailableError, + SubmissionStorageError, + ) as error: msg = "V2 household calculation storage is unavailable" raise HouseholdCalculationStorageError(msg) from error @@ -82,22 +93,19 @@ class V2HouseholdCalculationService: def __init__( self, *, - countries: CountrySource, - households: HouseholdSource, - policies: PolicySource, + sources: HouseholdCalculationSources, database_session: HouseholdCalculationDatabaseSession, simulation_factory: Callable[[], HouseholdCalculationSubmitter], ) -> None: """Read through these services and sessions for one request. - ``simulation_factory`` returns the simulation service's client only - once a submission is sent to it, so a request the Public API refuses - gets its own answer even when the simulation service is not - configured, and a read never needs it. + A submission is checked against ``sources``; a read reads only + ``database_session``. ``simulation_factory`` returns the simulation + service's client only once a submission is sent to it, so a request + the Public API refuses gets its own answer even when the simulation + service is not configured, and a read never needs it. """ - self._countries = countries - self._households = households - self._policies = policies + self._sources = sources self._database_session = database_session self._simulation_factory = simulation_factory @@ -107,27 +115,42 @@ def submit_calculation( """Send the calculation to the simulation service and return its new job. Raise HouseholdCalculationCountryError, HouseholdNotFoundError, - PolicyNotFoundError, HouseholdCalculationYearError or - PolicyParametersMissingError, in that order, before anything is sent; - HouseholdCalculationStorageError when the database cannot be read; - and the simulation service's errors when it refuses the calculation. + PolicyNotFoundError, HouseholdCalculationYearError, + PolicyParametersMissingError, DynamicNotFoundError or + DynamicParametersMissingError, in that order, before anything is + sent; HouseholdCalculationStorageError when the database cannot be + read; and the simulation service's errors when it refuses the + calculation. """ + # Imported here: ruff's banned-module-level-imports lists every v2 + # services module, so each loads only when a request uses it. + from policyengine_api.services.v2.simulation_service.services import ( + require_runnable_dynamics, + ) + country_id = calculation.country_id + sources = self._sources with _storage_failures(): - require_household_country(self._countries.list_countries(), country_id) - household = self._households.get_household( + require_household_country(sources.countries.list_countries(), country_id) + household = sources.households.get_household( country_id=country_id, household_id=calculation.household_id ) policy = ( None if calculation.policy_id is None - else self._policies.get_policy( + else sources.policies.get_policy( country_id=country_id, policy_id=calculation.policy_id ) ) year = require_default_year(household.default_year) if policy is not None: require_policy_parameters_present(policy.id, policy.missing_parameters) + with _storage_failures(): + require_runnable_dynamics( + sources.dynamics, + country_id=country_id, + dynamic_ids=(calculation.dynamic_id,), + ) accepted = self._simulation_factory().submit(calculation) return household_calculation_submitted(calculation, accepted, year=year) diff --git a/policyengine_api/services/v2/household_calculations/transformations.py b/policyengine_api/services/v2/household_calculations/transformations.py index 06d4cc64e..15be76e87 100644 --- a/policyengine_api/services/v2/household_calculations/transformations.py +++ b/policyengine_api/services/v2/household_calculations/transformations.py @@ -62,6 +62,7 @@ def household_calculation_read( country_id=job.country, household_id=job.household_id, policy_id=job.policy_id, + dynamic_id=job.dynamic_id, year=job.year, catalog_version_id=job.tax_benefit_model_version_id, country_package_version=job.country_package_version, @@ -99,5 +100,6 @@ def household_calculation_submitted( country_id=calculation.country_id, household_id=calculation.household_id, policy_id=calculation.policy_id, + dynamic_id=calculation.dynamic_id, year=year, ) diff --git a/policyengine_api/services/v2/household_calculations/types.py b/policyengine_api/services/v2/household_calculations/types.py index fbae62f5b..5ff2fcf6c 100644 --- a/policyengine_api/services/v2/household_calculations/types.py +++ b/policyengine_api/services/v2/household_calculations/types.py @@ -19,6 +19,7 @@ from policyengine_api.services.v2.countries.types import CountryRead from policyengine_api.services.v2.households.types import HouseholdRead from policyengine_api.services.v2.policies.types import CheckedPolicyRead + from policyengine_api.services.v2.simulation_service.types import DynamicSource # The simulation service's limits on axes, as its household contract sets # them: at most MAXIMUM_AXIS_GROUPS groups of at most MAXIMUM_PARALLEL_AXES @@ -70,7 +71,9 @@ def _omit_spm_default(schema: dict[str, Any]) -> None: class HouseholdCalculationInput(StrictCalculationModel): """A stored household to calculate under a stored policy, or current law. - The calculation's year is the household's default year, the year its + ``dynamic_id`` names a stored dynamic, whose model assumptions apply + too; none means no assumptions beyond the model's defaults. The + calculation's year is the household's default year, the year its values name. ``axes`` vary inputs across points: 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. ``add_missing_variables`` adds every yearly, @@ -82,6 +85,7 @@ class HouseholdCalculationInput(StrictCalculationModel): country_id: CountryId household_id: UUID policy_id: UUID | None = None + dynamic_id: UUID | None = None axes: Annotated[list[AxisGroup], Field(max_length=MAXIMUM_AXIS_GROUPS)] | None = ( None ) @@ -130,7 +134,7 @@ class HouseholdCalculationSubmitted: """A calculation the simulation service accepted, and what it calculates. ``year`` is the household's default year, which the simulation service - calculates. + calculates. ``dynamic_id`` is the dynamic it applies, None for none. """ calculation_id: UUID @@ -138,6 +142,7 @@ class HouseholdCalculationSubmitted: country_id: str household_id: UUID policy_id: UUID | None + dynamic_id: UUID | None year: int @@ -181,15 +186,17 @@ class HouseholdCalculationFailure: class HouseholdCalculationRead: """A household calculation as household_jobs records it. - ``catalog_version_id`` and the package versions are those the simulation - service ran it with. ``result`` is set once it succeeded and ``error`` - once it failed. + ``dynamic_id`` is the dynamic it applies, None for none, or once the + dynamic was deleted. ``catalog_version_id`` and the package versions + are those the simulation service ran it with. ``result`` is set once it + succeeded and ``error`` once it failed. """ calculation_id: UUID country_id: str household_id: UUID policy_id: UUID | None + dynamic_id: UUID | None year: int catalog_version_id: UUID country_package_version: str @@ -306,12 +313,29 @@ def get_policy(self, *, country_id: str, policy_id: UUID) -> CheckedPolicyRead: ... +@dataclass(frozen=True) +class HouseholdCalculationSources: + """The stored rows a submission is checked against, each through its service. + + ``countries``, ``households``, ``policies`` and ``dynamics`` are read + through the services of ``/v2/countries``, ``/v2/households``, + ``/v2/policies`` and ``/v2/dynamics``; ``dynamics`` is the economy + path's ``DynamicSource``, read only for a submission that names a + dynamic. + """ + + countries: CountrySource + households: HouseholdSource + policies: PolicySource + dynamics: DynamicSource + + class HouseholdCalculationSubmitter(Protocol): """The simulation service's ``POST /household-calculations``. - The simulation service reads the household, the policy's parameter values - and the catalog version from the Public API's tables itself, inserts the - job and starts its Modal call. + The simulation service reads the household, the policy's and the + dynamic's parameter values and the catalog version from API v1's tables + itself, inserts the job and starts its Modal call. """ def submit( diff --git a/policyengine_api/services/v2/simulation_service/services.py b/policyengine_api/services/v2/simulation_service/services.py index f363d6d00..40a777d56 100644 --- a/policyengine_api/services/v2/simulation_service/services.py +++ b/policyengine_api/services/v2/simulation_service/services.py @@ -8,12 +8,11 @@ country does not), that each policy the submission names is stored in the country, through the same service as ``/v2/policies`` (current law names none), and that none of those policies sets a parameter the running catalog -version lacks (``require_runnable_policies``, which re-runs call too). An -economy simulation, economy report or budget window then has each dynamic it -names checked the same way, through the same service as ``/v2/dynamics`` -(none means no assumptions beyond the model's defaults): -``require_runnable_dynamics``. -Only then is the simulation service asked. The submission's region is +version lacks (``require_runnable_policies``, which re-runs call too). Each +dynamic the submission names is then checked the same way, through the same +service as ``/v2/dynamics`` (none means no assumptions beyond the model's +defaults): ``require_runnable_dynamics``, which household calculations call +too. Only then is the simulation service asked. The submission's region is checked by the simulation service, which reads it, and the region's dataset, in the catalog version its default worker runs. @@ -21,8 +20,9 @@ must allow household calculations instead (a household-only country passes), 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. These are the -checks ``/v2/household-calculations`` makes, with the same errors. +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. 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 @@ -237,10 +237,11 @@ def submit_household_report( allows household calculations, then HouseholdNotFoundError for a household the country does not store, then HouseholdCalculationYearError for one with no default year, then the - policy checks' errors - (the baseline's policy first, and only the baseline's for a report of - the baseline alone), SubmissionStorageError when the database or its + 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. """ country_id = report.country_id with _storage_failures(): @@ -249,11 +250,18 @@ def submit_household_report( country_id=country_id, household_id=report.household_id ) require_default_year(household.default_year) - policy_ids = [report.baseline.policy_id] + sides = [report.baseline] if report.reform is not None: - policy_ids.append(report.reform.policy_id) + sides.append(report.reform) require_runnable_policies( - self._policies, country_id=country_id, policy_ids=policy_ids + self._policies, + country_id=country_id, + policy_ids=[side.policy_id for side in sides], + ) + require_runnable_dynamics( + self._dynamics, + country_id=country_id, + dynamic_ids=[side.dynamic_id for side in sides], ) return self._client_factory().submit_household_report(report) diff --git a/policyengine_api/services/v2/simulation_service/types.py b/policyengine_api/services/v2/simulation_service/types.py index 6d7f674bb..b7e68bb36 100644 --- a/policyengine_api/services/v2/simulation_service/types.py +++ b/policyengine_api/services/v2/simulation_service/types.py @@ -295,9 +295,15 @@ class EconomyReportCreationInput(EconomyReportFields): class HouseholdPolicyChoice(StrictSubmissionModel): - """A household simulation's stored policy; none means current law.""" + """A household simulation's stored policy and dynamic; neither means current law. + + No policy is current law, and no dynamic no model assumptions beyond the + model's defaults. The simulation service applies the dynamic's values + with the policy's, and refuses a parameter both set. + """ policy_id: ResourceId | None = None + dynamic_id: ResourceId | None = None class HouseholdReportFields(StrictSubmissionModel): @@ -307,6 +313,8 @@ class HouseholdReportFields(StrictSubmissionModel): the report's country, and both simulations calculate it in its default 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 diff --git a/tests/contract/registry.py b/tests/contract/registry.py index 0bf798576..fca94f498 100644 --- a/tests/contract/registry.py +++ b/tests/contract/registry.py @@ -368,6 +368,7 @@ class WorkflowContract: "result.item.country_id", "result.item.household_id", "result.item.policy_id", + "result.item.dynamic_id", "result.item.year", ), route_group="household", @@ -383,6 +384,7 @@ class WorkflowContract: "result.item.country_id", "result.item.household_id", "result.item.policy_id", + "result.item.dynamic_id", "result.item.year", "result.item.catalog_version_id", "result.item.country_package_version", diff --git a/tests/integration/test_v2_household_calculation_reads.py b/tests/integration/test_v2_household_calculation_reads.py index bb51123ed..9a90ffe74 100644 --- a/tests/integration/test_v2_household_calculation_reads.py +++ b/tests/integration/test_v2_household_calculation_reads.py @@ -37,6 +37,9 @@ from policyengine_api.services.v2.household_calculations.services import ( V2HouseholdCalculationService, ) +from policyengine_api.services.v2.household_calculations.types import ( + HouseholdCalculationSources, +) from policyengine_api.services.v2.household_calculations.validators import ( HouseholdCalculationNotFoundError, ) @@ -199,13 +202,16 @@ def runtime_service( """Return the household calculation service, reading as the runtime role.""" sessions = v2_sessions_as_role(managed_v2_roles.runtime) return V2HouseholdCalculationService( - countries=V2CountryService(CountryDatabaseSession(sessions)), - households=V2HouseholdService(HouseholdDatabaseSession(sessions)), - policies=V2PolicyService( - PolicyDatabaseSession(sessions), running_policyengine_version="6.10.0" - ), - dynamics=V2DynamicService( - DynamicDatabaseSession(sessions), running_policyengine_version="6.10.0" + sources=HouseholdCalculationSources( + countries=V2CountryService(CountryDatabaseSession(sessions)), + households=V2HouseholdService(HouseholdDatabaseSession(sessions)), + policies=V2PolicyService( + PolicyDatabaseSession(sessions), running_policyengine_version="6.10.0" + ), + dynamics=V2DynamicService( + DynamicDatabaseSession(sessions), + running_policyengine_version="6.10.0", + ), ), database_session=HouseholdCalculationDatabaseSession(sessions), simulation_factory=_no_simulation_service, diff --git a/tests/unit/v2/test_household_calculation_database_routes.py b/tests/unit/v2/test_household_calculation_database_routes.py index 8002ae0da..9e2718bf0 100644 --- a/tests/unit/v2/test_household_calculation_database_routes.py +++ b/tests/unit/v2/test_household_calculation_database_routes.py @@ -52,6 +52,9 @@ from policyengine_api.services.v2.household_calculations.services import ( V2HouseholdCalculationService, ) +from policyengine_api.services.v2.household_calculations.types import ( + HouseholdCalculationSources, +) from policyengine_api.services.v2.households.database_session import ( HouseholdDatabaseSession, ) @@ -190,6 +193,22 @@ def stored(sessions) -> dict[str, object]: return {name: row.id for name, row in rows.items()} +def _sources(sessions: sessionmaker[Session]) -> HouseholdCalculationSources: + """Read the countries, households, policies and dynamics from ``sessions``.""" + return HouseholdCalculationSources( + countries=V2CountryService(CountryDatabaseSession(sessions)), + households=V2HouseholdService(HouseholdDatabaseSession(sessions)), + policies=V2PolicyService( + PolicyDatabaseSession(sessions), + running_policyengine_version=RUNNING_VERSION, + ), + dynamics=V2DynamicService( + DynamicDatabaseSession(sessions), + running_policyengine_version=RUNNING_VERSION, + ), + ) + + @pytest.fixture def simulation() -> FakeSimulation: return FakeSimulation() @@ -199,16 +218,7 @@ def simulation() -> FakeSimulation: def client(sessions, simulation) -> TestClient: def service() -> V2HouseholdCalculationService: return V2HouseholdCalculationService( - countries=V2CountryService(CountryDatabaseSession(sessions)), - households=V2HouseholdService(HouseholdDatabaseSession(sessions)), - policies=V2PolicyService( - PolicyDatabaseSession(sessions), - running_policyengine_version=RUNNING_VERSION, - ), - dynamics=V2DynamicService( - DynamicDatabaseSession(sessions), - running_policyengine_version=RUNNING_VERSION, - ), + sources=_sources(sessions), database_session=HouseholdCalculationDatabaseSession(sessions), simulation_factory=lambda: simulation, ) @@ -383,16 +393,7 @@ def client_with_simulation_client(sessions, simulation_recorder) -> TestClient: def service() -> V2HouseholdCalculationService: return V2HouseholdCalculationService( - countries=V2CountryService(CountryDatabaseSession(sessions)), - households=V2HouseholdService(HouseholdDatabaseSession(sessions)), - policies=V2PolicyService( - PolicyDatabaseSession(sessions), - running_policyengine_version=RUNNING_VERSION, - ), - dynamics=V2DynamicService( - DynamicDatabaseSession(sessions), - running_policyengine_version=RUNNING_VERSION, - ), + sources=_sources(sessions), database_session=HouseholdCalculationDatabaseSession(sessions), simulation_factory=lambda: ( SimulationHouseholdCalculationClient.from_environment( diff --git a/tests/unit/v2/test_household_calculation_service.py b/tests/unit/v2/test_household_calculation_service.py index 1ae6f7cc2..5a7e0e4bb 100644 --- a/tests/unit/v2/test_household_calculation_service.py +++ b/tests/unit/v2/test_household_calculation_service.py @@ -19,6 +19,9 @@ from policyengine_api.services.v2.household_calculations.services import ( V2HouseholdCalculationService, ) +from policyengine_api.services.v2.household_calculations.types import ( + HouseholdCalculationSources, +) from policyengine_api.services.v2.household_calculations.validators import ( HouseholdCalculationCountryError, HouseholdCalculationStorageError, @@ -79,10 +82,12 @@ def simulation_factory(self) -> FakeSimulation: def service(self, database=None) -> V2HouseholdCalculationService: return V2HouseholdCalculationService( - countries=self.countries, - households=self.households, - policies=self.policies, - dynamics=self.dynamics, + sources=HouseholdCalculationSources( + countries=self.countries, + households=self.households, + policies=self.policies, + dynamics=self.dynamics, + ), database_session=database or UnreadableDatabase(), simulation_factory=self.simulation_factory, ) From 4259adfe9557f347eed174f0d61a7669adc02c2e Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:48:52 +0400 Subject: [PATCH 3/4] Test the dynamic refusals the OpenAPI descriptions name, and another country's dynamic (failing) From review round 1: the report create route's 422 description should name the simulation service's 400 for a dynamic, and the household calculation routes' 404 description should not say a calculation is read in a country. The database-backed household calculation route also refuses a dynamic stored for another country, and the household report re-run test says what it checks. Co-Authored-By: Claude Opus 5.5 --- .../integration/test_v2_household_reports.py | 5 ++- ...t_household_calculation_database_routes.py | 31 +++++++++++++++++-- .../v2/test_household_calculation_routes.py | 9 +++++- tests/unit/v2/test_household_report_routes.py | 12 +++++++ 4 files changed, 53 insertions(+), 4 deletions(-) diff --git a/tests/integration/test_v2_household_reports.py b/tests/integration/test_v2_household_reports.py index 8daa6244f..97ea58a35 100644 --- a/tests/integration/test_v2_household_reports.py +++ b/tests/integration/test_v2_household_reports.py @@ -809,7 +809,7 @@ def test_a_household_reports_dynamic_the_country_does_not_store_is_not_sent( assert simulation_service.household_reports == [] -def test_a_household_reports_rerun_keeps_each_sides_dynamic( +def test_a_household_reports_rerun_answers_each_sides_stored_dynamic( owner_sessions: sessionmaker[Session], household_only_uk: CatalogRows, stored_dynamic_ids: list[UUID], @@ -827,6 +827,9 @@ def test_a_household_reports_rerun_keeps_each_sides_dynamic( ) simulation_service = StoringHouseholdReportService(owner_sessions, catalog) + # API v1 sends only the report: the simulation service reads and applies + # each side's stored dynamic itself, which its own tests check. This + # checks the re-run is sent, and its answer reads both sides' dynamics. response = client_for(runtime_sessions, simulation_service).post( f"/v2/reports/{stored.report_id}/runs?country_id=uk", json={} ) diff --git a/tests/unit/v2/test_household_calculation_database_routes.py b/tests/unit/v2/test_household_calculation_database_routes.py index 9e2718bf0..fcccdb432 100644 --- a/tests/unit/v2/test_household_calculation_database_routes.py +++ b/tests/unit/v2/test_household_calculation_database_routes.py @@ -107,10 +107,16 @@ def _catalog_version( return parameters -def _dynamic(session: Session, parameters: dict[str, Parameter], hash_seed: str): +def _dynamic( + session: Session, + parameters: dict[str, Parameter], + hash_seed: str, + *, + country_id: str = "us", +): model_version = next(iter(parameters.values())).tax_benefit_model_version dynamic = Dynamic( - country_id="us", + country_id=country_id, tax_benefit_model_id=model_version.model_id, tax_benefit_model_version_id=model_version.id, canonicalization_version=1, @@ -159,6 +165,14 @@ def _policy(session: Session, parameters: dict[str, Parameter], hash_seed: str): return policy +def _uk_dynamic(session: Session) -> Dynamic: + """Store the UK, a UK catalog version and a dynamic of it.""" + session.add(Country(id="uk", household_enabled=True, society_wide_enabled=True)) + model = TaxBenefitModel(name="policyengine-uk") + parameters = _catalog_version(session, model, RUNNING_VERSION, [KEPT_ASSUMPTION]) + return _dynamic(session, parameters, "e", country_id="uk") + + @pytest.fixture def stored(sessions) -> dict[str, object]: """Store the US, a household, and a policy and a dynamic on two catalog versions.""" @@ -188,6 +202,7 @@ def stored(sessions) -> dict[str, object]: "running_policy": _policy(session, running, "b"), "earlier_dynamic": _dynamic(session, earlier, "c"), "running_dynamic": _dynamic(session, running, "d"), + "uk_dynamic": _uk_dynamic(session), } session.commit() return {name: row.id for name, row in rows.items()} @@ -306,6 +321,18 @@ def test_a_dynamic_setting_parameters_the_running_catalog_lacks_is_refused( assert simulation.submissions == [] +def test_another_countrys_dynamic_is_not_found_in_the_database( + client, stored, simulation +) -> None: + body = {**_body(stored, "running_policy"), "dynamic_id": str(stored["uk_dynamic"])} + + response = client.post(CALCULATIONS, json=body) + + assert response.status_code == 404 + assert str(stored["uk_dynamic"]) in response.json()["message"] + assert simulation.submissions == [] + + def test_an_unknown_dynamic_is_not_found_in_the_database( client, stored, simulation ) -> None: diff --git a/tests/unit/v2/test_household_calculation_routes.py b/tests/unit/v2/test_household_calculation_routes.py index b1fccb178..5fd336d10 100644 --- a/tests/unit/v2/test_household_calculation_routes.py +++ b/tests/unit/v2/test_household_calculation_routes.py @@ -521,5 +521,12 @@ def test_openapi_documents_the_dynamic_a_calculation_names(client) -> None: for item in ("HouseholdCalculationSubmittedItem", "HouseholdCalculationItem"): assert "dynamic_id" in components[item]["required"] submit = schema["paths"][CALCULATIONS]["post"] - assert "dynamic" in submit["responses"]["404"]["description"] + read = schema["paths"][f"{CALCULATIONS}/{{calculation_id}}"]["get"] + # Reading a calculation takes no country, so only the stored records a + # submission names are looked up in one. + for route in (submit, read): + assert route["responses"]["404"]["description"] == ( + "The household, policy or dynamic a submission names is not stored " + "in its country, or the calculation does not exist." + ) assert "dynamic" in submit["responses"]["422"]["description"] diff --git a/tests/unit/v2/test_household_report_routes.py b/tests/unit/v2/test_household_report_routes.py index e9d1cf2f0..1165a0018 100644 --- a/tests/unit/v2/test_household_report_routes.py +++ b/tests/unit/v2/test_household_report_routes.py @@ -416,6 +416,18 @@ def test_a_list_answers_household_and_economy_reports_by_kind_without_results() assert "result" not in economy_item +def test_the_create_routes_refusal_names_a_dynamic_the_service_cannot_find() -> None: + # A household report's side, like an economy report's, may name a dynamic + # the simulation service answers 400 unknown_dynamic for. + schema = report_route_client(reports=FakeReportService()).get("/v2/openapi.json") + + create = schema.json()["paths"]["/v2/reports"]["post"] + assert ( + "its 400 for a region, dynamic or dataset it does not have" + in (create["responses"]["422"]["description"]) + ) + + def test_the_create_routes_schema_offers_the_household_kind() -> None: schema = report_route_client(reports=FakeReportService()).get("/v2/openapi.json") From 80041ff9527add176df6f8db66007f5da0f0099b Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:52:44 +0400 Subject: [PATCH 4/4] Name the dynamic in the refusal descriptions and docstrings review round 1 found The report create route's 422 description names the simulation service's 400 for a region, dynamic or dataset. The household calculation routes' 404 description no longer says a calculation is read in a country. The household calculation route module and the resource service protocol name the dynamic and its refusals. Co-Authored-By: Claude Opus 5.5 --- .../fastapi_routes/resource_service_protocols.py | 13 +++++++------ .../v2/household_calculations/response_models.py | 4 ++-- .../v2/household_calculations/routes.py | 4 ++-- .../fastapi_routes/v2/reports/response_models.py | 2 +- 4 files changed, 12 insertions(+), 11 deletions(-) diff --git a/policyengine_api/fastapi_routes/resource_service_protocols.py b/policyengine_api/fastapi_routes/resource_service_protocols.py index cb710ff6b..b911a978d 100644 --- a/policyengine_api/fastapi_routes/resource_service_protocols.py +++ b/policyengine_api/fastapi_routes/resource_service_protocols.py @@ -196,12 +196,13 @@ def submit_calculation( """Send a stored household's calculation to the simulation service. Raise ``HouseholdCalculationCountryError`` for a country without - household calculations, ``HouseholdNotFoundError`` or - ``PolicyNotFoundError`` for a record not stored in that country, - ``HouseholdCalculationYearError`` for a household without a default - year, ``PolicyParametersMissingError`` for a policy setting parameters - the running catalog version lacks, and the simulation service errors - when it refuses the calculation. + household calculations, ``HouseholdNotFoundError``, + ``PolicyNotFoundError`` or ``DynamicNotFoundError`` for a record not + stored in that country, ``HouseholdCalculationYearError`` for a + household without a default year, ``PolicyParametersMissingError`` + (``DynamicParametersMissingError`` for a dynamic) for one setting + parameters the running catalog version lacks, and the simulation + service errors when it refuses the calculation. """ ... diff --git a/policyengine_api/fastapi_routes/v2/household_calculations/response_models.py b/policyengine_api/fastapi_routes/v2/household_calculations/response_models.py index 1b69f656f..992e0549c 100644 --- a/policyengine_api/fastapi_routes/v2/household_calculations/response_models.py +++ b/policyengine_api/fastapi_routes/v2/household_calculations/response_models.py @@ -163,8 +163,8 @@ class HouseholdCalculationResponse( 404: { "model": V2ErrorResponse, "description": ( - "The household, policy, dynamic or calculation does not exist in " - "the country." + "The household, policy or dynamic a submission names is not stored " + "in its country, or the calculation does not exist." ), }, 422: { diff --git a/policyengine_api/fastapi_routes/v2/household_calculations/routes.py b/policyengine_api/fastapi_routes/v2/household_calculations/routes.py index 607b75da9..7d3a83c78 100644 --- a/policyengine_api/fastapi_routes/v2/household_calculations/routes.py +++ b/policyengine_api/fastapi_routes/v2/household_calculations/routes.py @@ -2,8 +2,8 @@ The calculation runs on the simulation service, which records it as a job in ``household_jobs``; the routes need no account. Submitting sends the -simulation service the stored household's and policy's IDs once the Public -API's own checks pass; reading reads the job from the database and never +simulation service the stored household's, policy's and dynamic's IDs once +API v1's own checks pass; reading reads the job from the database and never calls the simulation service. """ diff --git a/policyengine_api/fastapi_routes/v2/reports/response_models.py b/policyengine_api/fastapi_routes/v2/reports/response_models.py index c21f0188c..f12dc7219 100644 --- a/policyengine_api/fastapi_routes/v2/reports/response_models.py +++ b/policyengine_api/fastapi_routes/v2/reports/response_models.py @@ -502,7 +502,7 @@ class ReportRunNotRecordedResponse(V2ErrorResponse): "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 " - "422, or its 400 for a region or dataset it does not have. The " + "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 " "status."