diff --git a/changelog.d/v2-generated-simulation-client.changed.md b/changelog.d/v2-generated-simulation-client.changed.md new file mode 100644 index 000000000..4bcefb39e --- /dev/null +++ b/changelog.d/v2-generated-simulation-client.changed.md @@ -0,0 +1 @@ +API v1 sends its requests to the simulation service (household calculations, simulations, reports and report re-runs) through the generated `policyengine-api-simulation-client`, pinned to 0.20261127.430; the requests, and the answers API v1 gives its callers, are unchanged. diff --git a/docs/migration/stage-11-v2-households.md b/docs/migration/stage-11-v2-households.md index 39b3bb3f0..0e142de1a 100644 --- a/docs/migration/stage-11-v2-households.md +++ b/docs/migration/stage-11-v2-households.md @@ -371,9 +371,12 @@ succeeded job whose result can't be read is 500. The call to the simulation service goes through `policyengine_api/libs/simulation_household_calculations.py`, at `SIMULATION_ENTRYPOINT_URL` with the gateway credentials of every other -simulation call. `post_household_calculation` is the only code that sends -the request, so moving to the generated simulation client changes that -function and the dependency. +simulation call. `post_household_calculation` +(`policyengine_api/libs/simulation_service_operations.py`) is the only code +that sends the request: it builds it with the simulation service's generated +client, `policyengine-api-simulation-client`, from its +`submit_household_calculation` operation and `HouseholdCalculationRequest` +model. The live staging job runs, after the other live tests: a submit and read cycle, six calculations submitted at once (each accepted within diff --git a/policyengine_api/libs/simulation_household_calculations.py b/policyengine_api/libs/simulation_household_calculations.py index ad451a16d..d27060549 100644 --- a/policyengine_api/libs/simulation_household_calculations.py +++ b/policyengine_api/libs/simulation_household_calculations.py @@ -87,11 +87,12 @@ which the service never received after a connection never made or a gateway token that couldn't be fetched. -Wiring the generated simulation client: ``post_household_calculation`` is the -only code that sends the request, and it returns the status and body, which -the rest of this module reads. Once a ``policyengine-api-simulation-client`` -release has the household calculation route, depend on that release and make -the function call the generated operation, as its docstring says. +The request goes through the simulation service's generated client: +``post_household_calculation`` +(``policyengine_api.libs.simulation_service_operations``) builds it with the +generated ``submit_household_calculation`` operation and +``HouseholdCalculationRequest`` model, sends it, and returns the status and +body, which the rest of this module reads. """ from __future__ import annotations @@ -120,6 +121,9 @@ status_and_code, submit_again, ) +from policyengine_api.libs.simulation_service_operations import ( + post_household_calculation, +) from policyengine_api.request_context import start_observability_id from policyengine_api.services.v2.household_calculations.types import ( HouseholdCalculationAccepted, @@ -141,6 +145,8 @@ HouseholdCalculationInput, ) +# The route's path, which tests check requests against. The generated +# operation holds its own copy, which it sends the request to. HOUSEHOLD_CALCULATIONS_PATH = "/household-calculations" UNREADABLE_ANSWER = "The simulation service's answer could not be read." # Statuses after which no job of the submission runs: the service's @@ -219,30 +225,6 @@ def household_calculation_request( return body -def post_household_calculation( - http_client: httpx.Client, body: dict[str, Any] -) -> SimulationAnswer: - """Send one submission to the simulation service and return its answer. - - Raise httpx.HTTPError when no answer arrives, and GatewayAuthError when - the gateway token cannot be fetched. ``http_client`` has the service's - base URL. To send through the generated client instead, this body - becomes, with ``Client`` from ``policyengine_api_simulation_client``, - ``submit_household_calculation`` from its ``api.default`` package and - ``HouseholdCalculationRequest`` from its ``models``, the names the - simulation service's OpenAPI document gives the route:: - - client = Client(base_url=str(http_client.base_url)) - client.set_httpx_client(http_client) - response = submit_household_calculation.sync_detailed( - client=client, body=HouseholdCalculationRequest.from_dict(body) - ) - return SimulationAnswer(int(response.status_code), response.content) - """ - response = http_client.post(HOUSEHOLD_CALCULATIONS_PATH, json=body) - return SimulationAnswer(status_code=response.status_code, content=response.content) - - def _invalid_request_reason(refusal: Refusal, code: str | None = None) -> str: """Return the service's reason, or each refused field and why. diff --git a/policyengine_api/libs/simulation_report_reruns.py b/policyengine_api/libs/simulation_report_reruns.py index 4ad1c7a1c..bec260efb 100644 --- a/policyengine_api/libs/simulation_report_reruns.py +++ b/policyengine_api/libs/simulation_report_reruns.py @@ -5,6 +5,9 @@ ``POST /reports/{report_id}/runs``, through the same HTTP client as the service's other v2 routes (``policyengine_api.libs.simulation_reports``), with ``"include_cliffs": true`` when the re-run asks for cliffs. The +request goes through the generated client's ``rerun_report`` operation +(``post_report_rerun`` in +``policyengine_api.libs.simulation_service_operations``). The service creates the stored report's new run on its default worker's versions and starts it, keeping every earlier run. Without ``force``, each side reuses a run of its own simulation that succeeded on those versions. @@ -131,7 +134,11 @@ class _RerunRefusal(Refusal): def report_runs_path(report_id: UUID) -> str: - """Return the simulation service's path for the report's runs.""" + """Return the simulation service's path for the report's runs. + + Tests check requests against it. The generated ``rerun_report`` + operation builds its own copy, which it sends the request to. + """ return f"/reports/{report_id}/runs" @@ -148,22 +155,6 @@ def report_rerun_request(rerun: ReportRerunInput) -> dict[str, Any]: return body -def post_report_rerun( - http_client: httpx.Client, report_id: UUID, body: dict[str, Any] -) -> SimulationAnswer: - """Send one re-run to the simulation service and return its answer. - - Raise httpx.HTTPError when no answer arrives, and GatewayAuthError when - the gateway token cannot be fetched. ``http_client`` has the service's - base URL. With the generated simulation client, this body becomes the - route's operation (``rerun_report.sync_detailed`` with ``report_id`` and - ``ReportRerunRequest.from_dict(body)``), as - ``policyengine_api.libs.simulation_reports.post_report`` describes. - """ - response = http_client.post(report_runs_path(report_id), json=body) - return SimulationAnswer(status_code=response.status_code, content=response.content) - - def _refusal(answer: SimulationAnswer) -> _RerunRefusal | None: try: return _RerunRefusal.model_validate_json(answer.content) diff --git a/policyengine_api/libs/simulation_reports.py b/policyengine_api/libs/simulation_reports.py index ab7b4228c..496e74e25 100644 --- a/policyengine_api/libs/simulation_reports.py +++ b/policyengine_api/libs/simulation_reports.py @@ -98,13 +98,14 @@ ``POST /reports/{report_id}/runs``; how it reads that route's answers is in ``policyengine_api.libs.simulation_report_reruns``. -Wiring the generated simulation client: ``post_simulation``, -``post_report`` and ``post_report_rerun`` are the only code that sends a -request, and each returns the status and body, which the rest of these -modules read. Once a -``policyengine-api-simulation-client`` release has the three routes, depend -on that release and make each function call the generated operation, as its -docstring says. +Each request goes through the simulation service's generated client: +``post_simulation``, ``post_report`` and ``post_report_rerun`` +(``policyengine_api.libs.simulation_service_operations``) build it with the +route's generated operation (``create_simulation``, ``create_report`` and +``rerun_report``) and request model (``EconomySimulationRequest``; +``EconomyReportRequest``, ``BudgetWindowReportRequest`` or +``HouseholdReportRequest``; ``ReportRerunRequest``), send it, and return the +status and body, which the rest of these modules read. """ from __future__ import annotations @@ -116,10 +117,7 @@ from pydantic import ValidationError -from policyengine_api.libs.simulation_report_reruns import ( - post_report_rerun, - start_report_rerun, -) +from policyengine_api.libs.simulation_report_reruns import start_report_rerun from policyengine_api.libs.simulation_service_answers import ( CALLER_ROW_REFUSAL_CODES, CREATED_STATUSES, @@ -139,6 +137,11 @@ status_and_code, submit_again, ) +from policyengine_api.libs.simulation_service_operations import ( + post_report, + post_report_rerun, + post_simulation, +) from policyengine_api.services.v2.simulation_service.types import ( SimulationServiceAnswerUnreadableError, SimulationServiceInternalError, @@ -165,6 +168,8 @@ StartedReportRun, ) +# The routes' paths, which tests check requests against. Each generated +# operation holds its own copy, which it sends the request to. SIMULATIONS_PATH = "/simulations" REPORTS_PATH = "/reports" @@ -307,39 +312,6 @@ def household_report_request(report: HouseholdReportCreationInput) -> dict[str, } -def post_simulation( - http_client: httpx.Client, body: dict[str, Any] -) -> SimulationAnswer: - """Send one simulation to the simulation service and return its answer. - - Raise httpx.HTTPError when no answer arrives, and GatewayAuthError when - the gateway token cannot be fetched. ``http_client`` has the service's - base URL. To send through the generated client instead, this body - becomes (the operation and model names are those the simulation - service's OpenAPI document gives the route):: - - client = Client(base_url=str(http_client.base_url)) - client.set_httpx_client(http_client) - response = create_simulation.sync_detailed( - client=client, body=SimulationRequest.from_dict(body) - ) - return SimulationAnswer(int(response.status_code), response.content) - """ - response = http_client.post(SIMULATIONS_PATH, json=body) - return SimulationAnswer(status_code=response.status_code, content=response.content) - - -def post_report(http_client: httpx.Client, body: dict[str, Any]) -> SimulationAnswer: - """Send one report to the simulation service and return its answer. - - As ``post_simulation``; with the generated client, the operation is the - report route's (``create_report.sync_detailed`` with - ``ReportRequest.from_dict(body)``). - """ - response = http_client.post(REPORTS_PATH, json=body) - return SimulationAnswer(status_code=response.status_code, content=response.content) - - def _refusal(answer: SimulationAnswer) -> _Refusal | None: try: return _Refusal.model_validate_json(answer.content) diff --git a/policyengine_api/libs/simulation_service_operations.py b/policyengine_api/libs/simulation_service_operations.py new file mode 100644 index 000000000..be987c179 --- /dev/null +++ b/policyengine_api/libs/simulation_service_operations.py @@ -0,0 +1,195 @@ +"""Send API v1's requests to the simulation service through its generated client. + +``policyengine-api-simulation-client`` is generated from the simulation +service's OpenAPI document. ``pyproject.toml`` pins it to a release whose +request models hold every field API v1 sends. Each ``post_`` function here +sends one route's request: + +1. it builds the route's generated request model from the body API v1 + builds (``from_dict``); +2. the route's generated operation builds the request from that model: its + method, path, JSON body and content type; +3. it checks that the JSON body is exactly the body API v1 built + (``send_request_with_body``). A generated model keeps only the fields it + defines, so a field the pinned release lacks, at the top level or nested, + would otherwise be left out of the request without an error; it raises + ValueError instead, before sending; +4. it sends the request on ``http_client``, which + ``simulation_service_http_client`` + (``policyengine_api.libs.simulation_service_answers``) builds with the + service's base URL, gateway credentials, request and observability ID + headers, transport and instrumentation; +5. it returns the answer's status and body unread. The calling module reads + them. + +Each generated operation builds its request with ``_get_kwargs``, and these +functions call it rather than the operation's ``sync_detailed``. The +generated package treats ``_get_kwargs`` as private, so a regenerated client +could rename it; the exact pin keeps it, and the tests below show the +requests it builds. +``sync_detailed`` also parses the answer, and raises on a body that isn't +JSON or isn't the shape the route documents, and on a status +``http.HTTPStatus`` doesn't name. API v1 reads those answers itself: a +created record whose answer can't be read, and a 503 that a front end +answers in the service's place, are different errors. The generated parsers +also document only 201 for a created report or re-run, while API v1 reads a +202 as created too. + +``tests/unit/libs/test_simulation_generated_client.py`` checks that each +request is the one API v1 builds by hand and the one the generated operation +builds; run those tests when moving the pin. + +To call another of the simulation service's routes, add a function here that +builds the request with that route's generated operation and request model, +checks a JSON body with ``send_request_with_body`` and sends a request +without one with ``send_operation_request``. The detailed-save API's POST +routes call their functions through ``send_to_simulation_service`` +(``policyengine_api.libs.simulation_service_answers``), which sorts transport +errors by whether the service may have created a record. + +API v1 still sends two kinds of request to the simulation service by hand: +the v1 economy routes' ``SimulationEntrypointClient`` +(``policyengine_api.libs.simulation_entrypoint``), and the model catalog +publication's ``GET /versions`` (``fetch_simulation_versions`` in +``policyengine_api.data.v2.catalog.spm_availability``). +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from policyengine_api_simulation_client.api.default.create_report import ( + _get_kwargs as report_request_arguments, +) +from policyengine_api_simulation_client.api.default.create_simulation import ( + _get_kwargs as simulation_request_arguments, +) +from policyengine_api_simulation_client.api.default.rerun_report import ( + _get_kwargs as report_rerun_request_arguments, +) +from policyengine_api_simulation_client.api.default.submit_household_calculation import ( # noqa: E501 # a module path can't be split across lines + _get_kwargs as household_calculation_request_arguments, +) +from policyengine_api_simulation_client.models import ( + BudgetWindowReportRequest, + EconomyReportRequest, + EconomySimulationRequest, + HouseholdCalculationRequest, + HouseholdReportRequest, + ReportRerunRequest, +) + +from policyengine_api.libs.simulation_service_answers import SimulationAnswer + +if TYPE_CHECKING: + from uuid import UUID + + import httpx + +# The generated model of each kind of report sent to POST /reports, by the +# body's report_type. +REPORT_REQUEST_MODELS: dict[ + str, + type[EconomyReportRequest | BudgetWindowReportRequest | HouseholdReportRequest], +] = { + "economy": EconomyReportRequest, + "budget_window": BudgetWindowReportRequest, + "household": HouseholdReportRequest, +} + + +# A field one body has and the other doesn't. +_ABSENT = object() + + +def send_operation_request( + http_client: httpx.Client, request_arguments: dict[str, Any] +) -> SimulationAnswer: + """Send the request a generated operation built; return its status and body. + + ``request_arguments`` is what the operation's ``_get_kwargs`` returns. + Raise httpx.HTTPError when no answer arrives, and GatewayAuthError when + the gateway token cannot be fetched. + """ + response = http_client.request(**request_arguments) + return SimulationAnswer(status_code=response.status_code, content=response.content) + + +def send_request_with_body( + http_client: httpx.Client, + request_arguments: dict[str, Any], + body: dict[str, Any], +) -> SimulationAnswer: + """Send the request once its JSON body is exactly ``body``; return the answer. + + ``body`` is the body API v1 built, and ``request_arguments`` what the + generated operation built from its model. Raise ValueError, naming each + top-level field that differs, before sending anything, when the + generated request would leave out, add or change any field, nested or + not. Otherwise raise what ``send_operation_request`` raises. + """ + generated_body: dict[str, Any] = request_arguments["json"] + changed_fields = sorted( + name + for name in body.keys() | generated_body.keys() + if body.get(name, _ABSENT) != generated_body.get(name, _ABSENT) + ) + if changed_fields: + msg = ( + "The simulation service's generated client would not send these " + f"fields as API v1 built them: {', '.join(changed_fields)}" + ) + raise ValueError(msg) + return send_operation_request(http_client, request_arguments) + + +def post_household_calculation( + http_client: httpx.Client, body: dict[str, Any] +) -> SimulationAnswer: + """Send one household calculation (``POST /household-calculations``). + + Raise what ``send_request_with_body`` raises. + """ + request = HouseholdCalculationRequest.from_dict(body) + return send_request_with_body( + http_client, household_calculation_request_arguments(body=request), body + ) + + +def post_simulation( + http_client: httpx.Client, body: dict[str, Any] +) -> SimulationAnswer: + """Send one economy simulation (``POST /simulations``). + + Raise what ``send_request_with_body`` raises. + """ + request = EconomySimulationRequest.from_dict(body) + return send_request_with_body( + http_client, simulation_request_arguments(body=request), body + ) + + +def post_report(http_client: httpx.Client, body: dict[str, Any]) -> SimulationAnswer: + """Send one economy report, budget window or household report (``POST /reports``). + + The body's ``report_type``, which the simulation service's route also + reads to tell them apart, selects its generated model. Raise what + ``send_request_with_body`` raises. + """ + request = REPORT_REQUEST_MODELS[body["report_type"]].from_dict(body) + return send_request_with_body( + http_client, report_request_arguments(body=request), body + ) + + +def post_report_rerun( + http_client: httpx.Client, report_id: UUID, body: dict[str, Any] +) -> SimulationAnswer: + """Send one re-run of a stored report (``POST /reports/{report_id}/runs``). + + Raise what ``send_request_with_body`` raises. + """ + request = ReportRerunRequest.from_dict(body) + return send_request_with_body( + http_client, report_rerun_request_arguments(report_id, body=request), body + ) diff --git a/pyproject.toml b/pyproject.toml index f981d1824..bd66d5321 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -51,6 +51,13 @@ dependencies = [ # complete frozen environment from uv.lock; the generic image installs # this requirement directly. "policyengine[models]==6.20.0", + # The simulation service's generated client, which builds the requests of + # the detailed-save API's household calculation, simulation and report + # routes (policyengine_api.libs.simulation_service_operations). The pin is + # a release whose request models hold every field those requests send; + # moving it is its own change, tested by + # tests/unit/libs/test_simulation_generated_client.py. + "policyengine-api-simulation-client==0.20261127.430", "pydantic", "pymysql", "python-dotenv", diff --git a/tests/unit/libs/test_simulation_generated_client.py b/tests/unit/libs/test_simulation_generated_client.py new file mode 100644 index 000000000..7736db23b --- /dev/null +++ b/tests/unit/libs/test_simulation_generated_client.py @@ -0,0 +1,837 @@ +"""API v1 sends each request to the simulation service through its generated client. + +``policyengine-api-simulation-client`` is generated from the simulation +service's OpenAPI document. For each route API v1 calls, these tests check +that the request API v1 sends is the one the route's generated operation +builds from its generated request model, and that it is still the request +API v1 built by hand: the same method, URL, content type and JSON body. + +They also check that API v1 still reads the answers that the generated +operations' own parsers raise on: a body that is not JSON, or not the shape +the route documents, and a status ``http.HTTPStatus`` doesn't name. The +generated ``create_report`` and ``rerun_report`` document only 201 for a +created record, so a 202 is checked too. +""" + +from __future__ import annotations + +import json +from contextlib import contextmanager +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any +from uuid import UUID + +import httpx +import pytest +from policyengine_api_simulation_client.api.default import ( + create_report, + create_simulation, + rerun_report, + submit_household_calculation, +) +from policyengine_api_simulation_client.models import ( + BudgetWindowReportRequest, + EconomyReportRequest, + EconomySimulationRequest, + HouseholdCalculationRequest, + HouseholdReportRequest, + ReportRerunRequest, +) + +from policyengine_api.libs.simulation_household_calculations import ( + SimulationHouseholdCalculationClient, + household_calculation_request, +) +from policyengine_api.libs.simulation_report_reruns import report_rerun_request +from policyengine_api.libs.simulation_reports import ( + SimulationServiceReportClient, + budget_window_request, + household_report_request, + report_request, + simulation_request, +) +from policyengine_api.libs.simulation_service_answers import ( + simulation_service_http_client, +) +from policyengine_api.libs.simulation_service_operations import ( + post_household_calculation, + post_report, + post_report_rerun, + post_simulation, +) +from policyengine_api.request_context import _asgi_observability_id +from policyengine_api.services.v2.household_calculations.types import ( + HouseholdCalculationAccepted, +) +from policyengine_api.services.v2.simulation_service.types import ( + SimulationServiceAnswerUnreadableError, + SimulationServiceUnavailableError, + StartedReportRun, + SubmittedBudgetWindow, + SubmittedReport, + SubmittedSimulation, +) +from tests.fixtures.household_calculation_documents import JOB_ID +from tests.unit.libs.test_simulation_budget_window_reports import ( + BUDGET_WINDOW_RUN_ID, + WINDOW_CREATED, + window_input, +) +from tests.unit.libs.test_simulation_household_calculations import ( + created_but_failed_message, + lost_answer_message, +) +from tests.unit.libs.test_simulation_household_report_requests import ( + OTHER_DYNAMIC_ID, + household_report_input, +) +from tests.unit.libs.test_simulation_report_reruns import ( + RERUN_STARTED, + possibly_started_message, + rerun_input, +) +from tests.unit.libs.test_simulation_reports import ( + DYNAMIC_ID, + POLICY_ID, + REPORT_CREATED, + REPORT_ID, + REPORT_RUN_ID, + SIMULATION_CREATED, + SIMULATION_ID, + SIMULATION_RUN_ID, + report_input, + simulation_input, +) +from tests.unit.v2.household_calculation_support import calculation_input +from tests.unit.v2.simulation_service_messages import possibly_created_message + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + +SIMULATION_URL = "https://simulation.example.test" +ENVIRONMENT_VARIABLES = ( + "GATEWAY_AUTH_ISSUER", + "GATEWAY_AUTH_AUDIENCE", + "GATEWAY_AUTH_CLIENT_ID", + "GATEWAY_AUTH_CLIENT_SECRET", + "GATEWAY_AUTH_CLIENT_SECRET_RESOURCE", + "GATEWAY_AUTH_REQUIRED", + "SIM_ENTRYPOINT", + "OLD_SIMULATION_GATEWAY_URL", + "SIMULATION_ENTRYPOINT_URL", +) +# The generated models of the request bodies API v1 sends. +GENERATED_REQUEST_MODELS = ( + HouseholdCalculationRequest, + EconomySimulationRequest, + EconomyReportRequest, + BudgetWindowReportRequest, + HouseholdReportRequest, + ReportRerunRequest, +) +# SPM settings naming every option, and settings naming options as null. +EVERY_SPM_OPTION = { + "forecast_content_sha256": "a" * 64, + "scenario": "ce_trend", + "geography_kind": "metro", + "geography_id": "31080", + "county_vintage": "2020", + "as_of": "2026-01-31", +} +NULL_SPM_OPTIONS = {"scenario": None, "as_of": None, "geography_kind": "national"} +HOUSEHOLD_JOB_ACCEPTED = {"job_id": str(JOB_ID), "status": "pending"} +# A front end's own error page, which is not JSON. +FRONT_END_PAGE = b"Service Unavailable" +# A status http.HTTPStatus doesn't name, so the generated Response refuses it. +UNNAMED_STATUS = 599 + + +@pytest.fixture(autouse=True) +def configured_simulation_service(monkeypatch): + """Name the Cloud Run simulation service; set no gateway credentials.""" + for name in ENVIRONMENT_VARIABLES: + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("SIMULATION_ENTRYPOINT_URL", f"{SIMULATION_URL}/") + monkeypatch.setenv("SIM_ENTRYPOINT", "old_gateway_direct") + monkeypatch.setenv("OLD_SIMULATION_GATEWAY_URL", "https://old.example.test") + + +@pytest.fixture(autouse=True) +def restored_observability_id(): + """Undo the observability ID each household submission binds.""" + token = _asgi_observability_id.set(None) + yield + _asgi_observability_id.reset(token) + + +@dataclass(frozen=True) +class Serialization: + """A request body a generated request model wrote, and the model's name.""" + + model_name: str + body: dict[str, Any] + + +def _recording_to_dict( + original: Callable[[Any], dict[str, Any]], serializations: list[Serialization] +) -> Callable[[Any], dict[str, Any]]: + def to_dict(model: Any) -> dict[str, Any]: + body = original(model) + serializations.append(Serialization(type(model).__name__, body)) + return body + + return to_dict + + +@contextmanager +def recorded_serializations() -> Iterator[list[Serialization]]: + """Record each body a generated request model writes inside the block.""" + serializations: list[Serialization] = [] + with pytest.MonkeyPatch.context() as patch: + for model in GENERATED_REQUEST_MODELS: + patch.setattr( + model, "to_dict", _recording_to_dict(model.to_dict, serializations) + ) + yield serializations + + +class ScriptedService: + """The simulation service, answering every request with one scripted answer.""" + + def __init__(self, status_code: int, body: object) -> None: + self.status_code = status_code + self.body = body + self.requests: list[httpx.Request] = [] + + def answer(self, request: httpx.Request) -> httpx.Response: + self.requests.append(request) + if isinstance(self.body, bytes): + return httpx.Response(self.status_code, content=self.body) + return httpx.Response(self.status_code, json=self.body) + + def household_client(self) -> SimulationHouseholdCalculationClient: + return SimulationHouseholdCalculationClient.from_environment( + transport=httpx.MockTransport(self.answer) + ) + + def report_client(self) -> SimulationServiceReportClient: + return SimulationServiceReportClient.from_environment( + transport=httpx.MockTransport(self.answer) + ) + + def sent_request(self) -> httpx.Request: + (request,) = self.requests + return request + + +def generated_request(request_arguments: dict[str, Any]) -> httpx.Request: + """Return the request a generated operation's arguments make at the service.""" + return httpx.Client(base_url=SIMULATION_URL).build_request(**request_arguments) + + +def assert_sent_through_generated_operation( + sent: httpx.Request, + serializations: list[Serialization], + *, + expected: httpx.Request, + model_name: str, + hand_built_body: dict[str, Any], +) -> None: + """Check the sent request is the generated operation's and the hand-built one. + + ``expected`` is the request the generated operation builds from the + generated model of ``hand_built_body``, the body API v1 builds by hand. + """ + sent_body = json.loads(sent.content) + assert serializations == [Serialization(model_name, sent_body)], ( + f"API v1 did not send the body {model_name} wrote" + ) + assert sent.method == expected.method + assert sent.url == expected.url + assert sent.headers["Content-Type"] == expected.headers["Content-Type"] + assert sent.content == expected.content + assert sent_body == hand_built_body + + +HOUSEHOLD_CALCULATION_CHANGES = { + "current law": {"policy_id": None}, + "a reform": {}, + "every option": { + "dynamic_id": DYNAMIC_ID, + "add_missing_variables": True, + "axes": [ + [{"name": "employment_income", "count": 3, "min": 0, "max": 90_000.5}], + [ + { + "name": "age", + "count": 2, + "min": 20, + "max": 60, + "period": "2026", + "index": 1, + } + ], + ], + "spm": EVERY_SPM_OPTION, + }, + "options named as null": { + "axes": [ + [ + { + "name": "employment_income", + "count": 2, + "min": 0, + "max": 1, + "period": None, + "index": None, + } + ] + ], + "spm": NULL_SPM_OPTIONS, + }, +} + + +@pytest.mark.parametrize("case", list(HOUSEHOLD_CALCULATION_CHANGES)) +def test_a_household_calculation_is_sent_by_the_generated_operation( + case: str, +) -> None: + calculation = calculation_input(**HOUSEHOLD_CALCULATION_CHANGES[case]) + hand_built_body = household_calculation_request(calculation) + expected = generated_request( + submit_household_calculation._get_kwargs( + body=HouseholdCalculationRequest.from_dict(hand_built_body) + ) + ) + service = ScriptedService(202, HOUSEHOLD_JOB_ACCEPTED) + + with recorded_serializations() as serializations: + accepted = service.household_client().submit(calculation) + + assert accepted == HouseholdCalculationAccepted( + calculation_id=JOB_ID, status="pending" + ) + assert_sent_through_generated_operation( + service.sent_request(), + serializations, + expected=expected, + model_name="HouseholdCalculationRequest", + hand_built_body=hand_built_body, + ) + + +@pytest.mark.parametrize( + ("status_code", "body", "error_type", "message"), + [ + pytest.param( + 202, + b"not json", + SimulationServiceAnswerUnreadableError, + created_but_failed_message("202"), + id="accepted, not JSON", + ), + pytest.param( + 202, + {"job_id": str(JOB_ID)}, + SimulationServiceAnswerUnreadableError, + created_but_failed_message("202"), + id="accepted, without a status", + ), + pytest.param( + 400, + ["not", "an", "object"], + SimulationServiceUnavailableError, + "The simulation service refused the calculation (400).", + id="refused, not an object", + ), + pytest.param( + 422, + b"not json", + SimulationServiceUnavailableError, + "The simulation service's answer could not be read.", + id="unprocessable, not JSON", + ), + pytest.param( + 503, + FRONT_END_PAGE, + SimulationServiceAnswerUnreadableError, + lost_answer_message("a proxy answered 503"), + id="a front end's 503", + ), + pytest.param( + UNNAMED_STATUS, + b"", + SimulationServiceAnswerUnreadableError, + created_but_failed_message(str(UNNAMED_STATUS)), + id="a status HTTPStatus doesn't name", + ), + ], +) +def test_household_calculation_answers_the_generated_parser_refuses_are_read( + status_code: int, body: object, error_type: type[Exception], message: str +) -> None: + service = ScriptedService(status_code, body) + + with ( + recorded_serializations() as serializations, + pytest.raises(error_type) as raised, + ): + service.household_client().submit(calculation_input()) + + assert str(raised.value) == message + assert [serialization.model_name for serialization in serializations] == [ + "HouseholdCalculationRequest" + ] + + +SIMULATION_CHANGES = { + "current law": {"policy_id": None}, + "a reform": {}, + "a reform and a dynamic": {"dynamic_id": str(DYNAMIC_ID)}, +} + + +@pytest.mark.parametrize("case", list(SIMULATION_CHANGES)) +def test_a_simulation_is_sent_by_the_generated_operation(case: str) -> None: + simulation = simulation_input(**SIMULATION_CHANGES[case]) + hand_built_body = simulation_request(simulation) + expected = generated_request( + create_simulation._get_kwargs( + body=EconomySimulationRequest.from_dict(hand_built_body) + ) + ) + service = ScriptedService(201, SIMULATION_CREATED) + + with recorded_serializations() as serializations: + submitted = service.report_client().submit_simulation(simulation) + + assert submitted == SubmittedSimulation( + simulation_id=SIMULATION_ID, simulation_run_id=SIMULATION_RUN_ID + ) + assert_sent_through_generated_operation( + service.sent_request(), + serializations, + expected=expected, + model_name="EconomySimulationRequest", + hand_built_body=hand_built_body, + ) + + +@pytest.mark.parametrize( + ("status_code", "body", "error_type", "message"), + [ + pytest.param( + 201, + b"not json", + SimulationServiceAnswerUnreadableError, + "The simulation service created the simulation, but its answer " + "could not be read.", + id="created, not JSON", + ), + pytest.param( + 422, + b"not json", + SimulationServiceUnavailableError, + "The simulation service answered 422 unreadably.", + id="unprocessable, not JSON", + ), + pytest.param( + 503, + FRONT_END_PAGE, + SimulationServiceAnswerUnreadableError, + possibly_created_message("503", "simulation"), + id="a front end's 503", + ), + pytest.param( + UNNAMED_STATUS, + b"", + SimulationServiceAnswerUnreadableError, + possibly_created_message(str(UNNAMED_STATUS), "simulation"), + id="a status HTTPStatus doesn't name", + ), + ], +) +def test_simulation_answers_the_generated_parser_refuses_are_read( + status_code: int, body: object, error_type: type[Exception], message: str +) -> None: + service = ScriptedService(status_code, body) + + with ( + recorded_serializations() as serializations, + pytest.raises(error_type) as raised, + ): + service.report_client().submit_simulation(simulation_input()) + + assert str(raised.value) == message + assert [serialization.model_name for serialization in serializations] == [ + "EconomySimulationRequest" + ] + + +@dataclass(frozen=True) +class ReportCase: + """A report API v1 submits, how it builds the body, and its generated model.""" + + submit: Callable[[SimulationServiceReportClient], object] + hand_built_body: Callable[[], dict[str, Any]] + generated_model: type[ + EconomyReportRequest | BudgetWindowReportRequest | HouseholdReportRequest + ] + created: dict[str, Any] + submitted: object + + +def economy_report_case(**changes: Any) -> ReportCase: + return ReportCase( + submit=lambda client: client.submit_report(report_input(**changes)), + hand_built_body=lambda: report_request(report_input(**changes)), + generated_model=EconomyReportRequest, + created=REPORT_CREATED, + submitted=SubmittedReport(report_id=REPORT_ID, report_run_id=REPORT_RUN_ID), + ) + + +def budget_window_case(**changes: Any) -> ReportCase: + return ReportCase( + submit=lambda client: client.submit_budget_window(window_input(**changes)), + hand_built_body=lambda: budget_window_request(window_input(**changes)), + generated_model=BudgetWindowReportRequest, + created=WINDOW_CREATED, + submitted=SubmittedBudgetWindow( + report_id=UUID(WINDOW_CREATED["report_id"]), + budget_window_run_id=BUDGET_WINDOW_RUN_ID, + ), + ) + + +def household_report_case(**changes: Any) -> ReportCase: + return ReportCase( + submit=lambda client: client.submit_household_report( + household_report_input(**changes) + ), + hand_built_body=lambda: household_report_request( + household_report_input(**changes) + ), + generated_model=HouseholdReportRequest, + created=REPORT_CREATED, + submitted=SubmittedReport(report_id=REPORT_ID, report_run_id=REPORT_RUN_ID), + ) + + +REPORT_CASES = { + "an economy report": economy_report_case(), + "an economy report with every option": economy_report_case( + baseline={"dynamic_id": str(DYNAMIC_ID)}, + reform={"policy_id": str(POLICY_ID), "dynamic_id": str(DYNAMIC_ID)}, + include_cliffs=True, + spm=EVERY_SPM_OPTION, + data_source="local_area_dataset", + region_code="country/wales", + country_id="uk", + ), + "an economy report with SPM options named as null": economy_report_case( + spm=NULL_SPM_OPTIONS + ), + "a budget window": budget_window_case(), + "a budget window with SPM settings and dynamics": budget_window_case( + baseline={"dynamic_id": str(DYNAMIC_ID)}, + spm=EVERY_SPM_OPTION, + ), + "a household report of the baseline alone": household_report_case(reform=None), + "a household report": household_report_case(), + "a household report with dynamics": household_report_case( + baseline={"dynamic_id": str(DYNAMIC_ID)}, + reform={"policy_id": str(POLICY_ID), "dynamic_id": str(OTHER_DYNAMIC_ID)}, + ), +} + + +@pytest.mark.parametrize("case", list(REPORT_CASES)) +def test_a_report_is_sent_by_the_generated_operation(case: str) -> None: + report = REPORT_CASES[case] + hand_built_body = report.hand_built_body() + expected = generated_request( + create_report._get_kwargs( + body=report.generated_model.from_dict(hand_built_body) + ) + ) + service = ScriptedService(201, report.created) + + with recorded_serializations() as serializations: + submitted = report.submit(service.report_client()) + + assert submitted == report.submitted + assert_sent_through_generated_operation( + service.sent_request(), + serializations, + expected=expected, + model_name=report.generated_model.__name__, + hand_built_body=hand_built_body, + ) + + +@pytest.mark.parametrize( + "case", ["an economy report", "a budget window", "a household report"] +) +def test_a_report_created_with_202_is_read(case: str) -> None: + report = REPORT_CASES[case] + service = ScriptedService(202, report.created) + + with recorded_serializations() as serializations: + submitted = report.submit(service.report_client()) + + assert submitted == report.submitted + assert [serialization.model_name for serialization in serializations] == [ + report.generated_model.__name__ + ] + + +@pytest.mark.parametrize( + ("case", "status_code", "body", "error_type", "message"), + [ + pytest.param( + "an economy report", + 201, + b"not json", + SimulationServiceAnswerUnreadableError, + "The simulation service created the report, but its answer could " + "not be read.", + id="economy report created, not JSON", + ), + pytest.param( + "a budget window", + 201, + {"report_id": str(REPORT_ID)}, + SimulationServiceAnswerUnreadableError, + "The simulation service created the budget window, but its answer " + "could not be read.", + id="budget window created, without its run", + ), + pytest.param( + "a household report", + 201, + [], + SimulationServiceAnswerUnreadableError, + "The simulation service created the report, but its answer could " + "not be read.", + id="household report created, not an object", + ), + pytest.param( + "an economy report", + 400, + b"not json", + SimulationServiceUnavailableError, + "The simulation service answered 400 unreadably.", + id="refused, not JSON", + ), + pytest.param( + "an economy report", + 503, + FRONT_END_PAGE, + SimulationServiceAnswerUnreadableError, + possibly_created_message("503", "report"), + id="a front end's 503", + ), + pytest.param( + "a budget window", + UNNAMED_STATUS, + b"", + SimulationServiceAnswerUnreadableError, + possibly_created_message(str(UNNAMED_STATUS), "report"), + id="a status HTTPStatus doesn't name", + ), + ], +) +def test_report_answers_the_generated_parser_refuses_are_read( + case: str, + status_code: int, + body: object, + error_type: type[Exception], + message: str, +) -> None: + report = REPORT_CASES[case] + service = ScriptedService(status_code, body) + + with ( + recorded_serializations() as serializations, + pytest.raises(error_type) as raised, + ): + report.submit(service.report_client()) + + assert str(raised.value) == message + assert [serialization.model_name for serialization in serializations] == [ + report.generated_model.__name__ + ] + + +RERUN_CHANGES = { + "without force": {"force": False}, + "with force": {"force": True}, + "with cliffs": {"include_cliffs": True}, + "with force and cliffs": {"force": True, "include_cliffs": True}, +} +STARTED_RUN = StartedReportRun( + report_run_id=UUID(RERUN_STARTED["report_run_id"]), + budget_window_run_id=None, +) + + +@pytest.mark.parametrize("case", list(RERUN_CHANGES)) +def test_a_rerun_is_sent_by_the_generated_operation(case: str) -> None: + rerun = rerun_input(**RERUN_CHANGES[case]) + hand_built_body = report_rerun_request(rerun) + expected = generated_request( + rerun_report._get_kwargs( + rerun.report_id, body=ReportRerunRequest.from_dict(hand_built_body) + ) + ) + service = ScriptedService(201, RERUN_STARTED) + + with recorded_serializations() as serializations: + started = service.report_client().rerun_report(rerun) + + assert started == STARTED_RUN + assert_sent_through_generated_operation( + service.sent_request(), + serializations, + expected=expected, + model_name="ReportRerunRequest", + hand_built_body=hand_built_body, + ) + + +@pytest.mark.parametrize( + ("status_code", "body", "error_type", "message"), + [ + pytest.param( + 201, + b"not json", + SimulationServiceAnswerUnreadableError, + "The simulation service answered that it started a new run of the " + "report, but its answer could not be read. Read the report to see " + "whether it has a new run before running it again.", + id="started, not JSON", + ), + pytest.param( + 409, + b"not json", + SimulationServiceUnavailableError, + "The simulation service answered 409 unreadably.", + id="conflict, not JSON", + ), + pytest.param( + 503, + FRONT_END_PAGE, + SimulationServiceAnswerUnreadableError, + possibly_started_message("503"), + id="a front end's 503", + ), + pytest.param( + UNNAMED_STATUS, + b"", + SimulationServiceAnswerUnreadableError, + possibly_started_message(str(UNNAMED_STATUS)), + id="a status HTTPStatus doesn't name", + ), + ], +) +def test_rerun_answers_the_generated_parser_refuses_are_read( + status_code: int, body: object, error_type: type[Exception], message: str +) -> None: + service = ScriptedService(status_code, body) + + with ( + recorded_serializations() as serializations, + pytest.raises(error_type) as raised, + ): + service.report_client().rerun_report(rerun_input()) + + assert str(raised.value) == message + assert [serialization.model_name for serialization in serializations] == [ + "ReportRerunRequest" + ] + + +def test_a_rerun_started_with_202_is_read() -> None: + service = ScriptedService(202, RERUN_STARTED) + + with recorded_serializations() as serializations: + started = service.report_client().rerun_report(rerun_input()) + + assert started == STARTED_RUN + assert [serialization.model_name for serialization in serializations] == [ + "ReportRerunRequest" + ] + + +def send_rerun(http_client: httpx.Client, body: dict[str, Any]) -> object: + return post_report_rerun(http_client, rerun_input().report_id, body) + + +@pytest.mark.parametrize( + ("send", "hand_built_body", "changed_field"), + [ + pytest.param( + post_household_calculation, + { + **household_calculation_request(calculation_input()), + "field_the_model_lacks": 1, + }, + "field_the_model_lacks", + id="household calculation, a field the model lacks", + ), + pytest.param( + post_simulation, + { + **simulation_request(simulation_input()), + "field_the_model_lacks": 1, + }, + "field_the_model_lacks", + id="simulation, a field the model lacks", + ), + pytest.param( + post_report, + {**report_request(report_input()), "field_the_model_lacks": 1}, + "field_the_model_lacks", + id="economy report, a field the model lacks", + ), + pytest.param( + post_report, + { + **budget_window_request(window_input()), + "spm": {"geography_kind": "national", "option_the_model_lacks": 1}, + }, + "spm", + id="budget window, an SPM option the model lacks", + ), + pytest.param( + post_report, + { + **household_report_request(household_report_input()), + "reform": {"policy_id": str(POLICY_ID), "field_the_model_lacks": 1}, + }, + "reform", + id="household report, a side's field the model lacks", + ), + pytest.param( + send_rerun, + {**report_rerun_request(rerun_input()), "field_the_model_lacks": 1}, + "field_the_model_lacks", + id="rerun, a field the model lacks", + ), + ], +) +def test_a_body_the_generated_model_would_change_is_not_sent( + send: Callable[[httpx.Client, dict[str, Any]], object], + hand_built_body: dict[str, Any], + changed_field: str, +) -> None: + service = ScriptedService(201, {}) + http_client = simulation_service_http_client( + transport=httpx.MockTransport(service.answer) + ) + + with pytest.raises(ValueError, match=changed_field): + send(http_client, hand_built_body) + + assert service.requests == [] diff --git a/uv.lock b/uv.lock index f38ff731a..06a32bdf2 100644 --- a/uv.lock +++ b/uv.lock @@ -3006,6 +3006,7 @@ dependencies = [ { name = "openai" }, { name = "packaging" }, { name = "policyengine", extra = ["models"] }, + { name = "policyengine-api-simulation-client" }, { name = "policyengine-observability", extra = ["flask", "google", "httpx", "otlp-grpc"] }, { name = "psycopg", extra = ["binary"] }, { name = "pydantic" }, @@ -3073,6 +3074,7 @@ requires-dist = [ { name = "openai" }, { name = "packaging", specifier = ">=24,<27" }, { name = "policyengine", extras = ["models"], specifier = "==6.20.0" }, + { name = "policyengine-api-simulation-client", specifier = "==0.20261127.430" }, { name = "policyengine-observability", extras = ["flask", "google", "httpx", "otlp-grpc"], specifier = ">=3.0.3,<4" }, { name = "psycopg", extras = ["binary"], specifier = ">=3.3,<4" }, { name = "pydantic" }, @@ -3099,6 +3101,19 @@ provides-extras = ["dev"] [package.metadata.requires-dev] telemetry-error-issues = [{ name = "google-cloud-bigquery", specifier = ">=3.30,<4" }] +[[package]] +name = "policyengine-api-simulation-client" +version = "0.20261127.430" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "httpx" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ee/5b/23ee4708a81ca8cb80da3f299d66530f2c9b014dbef7298b017394e5ef2a/policyengine_api_simulation_client-0.20261127.430.tar.gz", hash = "sha256:fd65475e32eeb3eec9478565df42a524c2fa0a5d66945e5ce8f45f67846d5da4", size = 73000, upload-time = "2026-11-27T16:28:23.425Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2e/c4/bf8755ea496cf6dd774c944952baf9e14e41355ea70beb20dfcaa5fff095/policyengine_api_simulation_client-0.20261127.430-py3-none-any.whl", hash = "sha256:bfa200907750af00adee1c310cec7b851c1a2a0d3d5a3c717d33f65ccd17b444", size = 161942, upload-time = "2026-11-27T16:28:22.018Z" }, +] + [[package]] name = "policyengine-core" version = "3.33.3"