From 0564ac15b4b010850054074e286308987832e489 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:58:43 +0400 Subject: [PATCH 1/9] Add tests that fail before household calculations accept a variables list POST /v2/household-calculations is to accept `variables`, a list of the variables to calculate, for a stored household and for one given in the request. The tests cover its limits (at most 10,000 distinct names, not with add_missing_variables true, no empty name), the body sent to the simulation service (the list only when given), the check of each name against the running catalog version (a 422 with code unknown_variables naming the names it lacks, nothing checked when that version has no published catalog), and the OpenAPI document. Co-Authored-By: Claude Opus 5.5 --- .../v2/test_household_calculation_routes.py | 7 +- .../test_household_calculation_variables.py | 433 ++++++++++++++++++ 2 files changed, 439 insertions(+), 1 deletion(-) create mode 100644 tests/unit/v2/test_household_calculation_variables.py diff --git a/tests/unit/v2/test_household_calculation_routes.py b/tests/unit/v2/test_household_calculation_routes.py index 51202ec20..b974a17d5 100644 --- a/tests/unit/v2/test_household_calculation_routes.py +++ b/tests/unit/v2/test_household_calculation_routes.py @@ -567,7 +567,11 @@ def test_openapi_documents_both_routes_and_the_missing_parameter_refusal( assert "security" not in submit refusal_schema = submit["responses"]["422"]["content"]["application/json"]["schema"] refusals = {option["$ref"].rsplit("/", 1)[-1] for option in refusal_schema["anyOf"]} - assert refusals == {"V2ErrorResponse", "V2MissingParametersErrorResponse"} + assert refusals == { + "V2ErrorResponse", + "V2MissingParametersErrorResponse", + "V2UnknownVariablesErrorResponse", + } missing_parameters = schema["components"]["schemas"][ "V2MissingParametersErrorResponse" ] @@ -617,6 +621,7 @@ def test_openapi_documents_the_stored_and_the_inline_request(client) -> None: "policy", "axes", "add_missing_variables", + "variables", "spm", } assert set(inline["required"]) == {"country_id", "year", "household"} diff --git a/tests/unit/v2/test_household_calculation_variables.py b/tests/unit/v2/test_household_calculation_variables.py new file mode 100644 index 000000000..03f886f94 --- /dev/null +++ b/tests/unit/v2/test_household_calculation_variables.py @@ -0,0 +1,433 @@ +"""A household calculation's list of variables: its limits, its check, what is sent. + +A calculation may list the variables to calculate (``variables``). The list +holds at most 10,000 distinct names and is not given together with +``add_missing_variables: true``. Before anything is sent, each name is +checked against the running catalog version, the one policy parameters are +checked against; the simulation service is sent the list as given, and a +calculation without one is sent as before. The route tests read SQLite +copies of the v2 tables through the database-backed services; only the +simulation service is a stand-in. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, TypeVar + +import pytest +from fastapi.testclient import TestClient +from flask import Flask +from pydantic import BaseModel, ValidationError + +from policyengine_api.asgi_factory import create_asgi_app +from policyengine_api.constants import POLICYENGINE_VERSION +from policyengine_api.data.v2.models import ( + Country, + Household, + TaxBenefitModel, + TaxBenefitModelVersion, + Variable, +) +from policyengine_api.fastapi_routes.dependencies import NativeRouteDependencies +from policyengine_api.libs.simulation_household_calculations import ( + household_calculation_request, +) +from policyengine_api.migration_flags import ( + RouteImplementation, + RouteImplementationSettings, +) +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, +) +from policyengine_api.services.v2.household_calculations.services import ( + V2HouseholdCalculationService, +) +from policyengine_api.services.v2.household_calculations.types import ( + HouseholdCalculationInput, + HouseholdCalculationSources, + InlineHouseholdCalculationInput, +) +from policyengine_api.services.v2.households.database_session import ( + HouseholdDatabaseSession, +) +from policyengine_api.services.v2.households.services import V2HouseholdService +from policyengine_api.services.v2.policies.database_session import ( + PolicyDatabaseSession, +) +from policyengine_api.services.v2.policies.services import V2PolicyService +from tests.fixtures.database_sessions import sqlite_v2_sessions +from tests.unit.v2.household_calculation_support import HOUSEHOLD_ID, FakeSimulation + +if TYPE_CHECKING: + from collections.abc import Iterator + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + +CALCULATIONS = "/v2/household-calculations" +EARLIER_VERSION = "0.0.1" +# The running catalog version's variables, and one only an earlier version has. +RUNNING_VARIABLES = ("employment_income", "household_net_income", "snap") +REMOVED_VARIABLE = "removed_benefit" +MAXIMUM_LISTED_VARIABLES = 10_000 +INLINE_HOUSEHOLD = { + "people": {"you": {"age": 40}}, + "households": {"your household": {"members": ["you"]}}, +} +INVALID_REQUEST = {"status": "error", "message": "Invalid API v2 request"} +ModelT = TypeVar("ModelT", bound=BaseModel) + + +def _stored_fields(**changes: object) -> dict[str, object]: + fields: dict[str, object] = {"country_id": "us", "household_id": str(HOUSEHOLD_ID)} + fields.update(changes) + return fields + + +def _inline_fields(**changes: object) -> dict[str, object]: + fields: dict[str, object] = { + "country_id": "us", + "year": 2026, + "household": INLINE_HOUSEHOLD, + } + fields.update(changes) + return fields + + +# Each request form: its service input type and a body of that form. +FORMS = { + "stored": (HouseholdCalculationInput, _stored_fields), + "inline": (InlineHouseholdCalculationInput, _inline_fields), +} + + +def _refusals(model: type[BaseModel], fields: dict[str, object]) -> list[Any]: + """Return the validation errors refusing ``fields``, none when they are accepted.""" + try: + model.model_validate(fields) + except ValidationError as refusal: + return refusal.errors(include_url=False, include_input=False) + return [] + + +def _accepted(model: type[ModelT], fields: dict[str, object]) -> ModelT: + """Return ``fields`` as ``model``, asserting first that nothing refuses them.""" + refusals = _refusals(model, fields) + assert refusals == [], refusals + return model.model_validate(fields) + + +def _names(count: int) -> list[str]: + return [f"variable_{index}" for index in range(count)] + + +@pytest.mark.parametrize("form", list(FORMS)) +def test_a_calculation_lists_its_variables_in_the_order_given(form: str) -> None: + model, fields = FORMS[form] + + calculation = _accepted(model, fields(variables=["snap", "eitc"])) + + assert calculation.model_dump().get("variables") == ["snap", "eitc"] + + +@pytest.mark.parametrize("form", list(FORMS)) +@pytest.mark.parametrize( + "changes", [{}, {"variables": None}], ids=["omitted", "explicit-null"] +) +def test_a_calculation_without_a_list_lists_no_variables( + form: str, changes: dict[str, object] +) -> None: + model, fields = FORMS[form] + + calculation = _accepted(model, fields(**changes)) + + assert calculation.model_dump().get("variables", "absent") is None + + +def test_an_empty_list_of_variables_is_accepted() -> None: + calculation = _accepted(HouseholdCalculationInput, _stored_fields(variables=[])) + + assert calculation.model_dump().get("variables") == [] + + +def test_a_list_of_the_simulation_services_maximum_length_is_accepted() -> None: + names = _names(MAXIMUM_LISTED_VARIABLES) + + calculation = _accepted(HouseholdCalculationInput, _stored_fields(variables=names)) + + assert calculation.model_dump().get("variables") == names + + +def test_a_list_longer_than_the_simulation_services_maximum_is_refused() -> None: + refusals = _refusals( + HouseholdCalculationInput, + _stored_fields(variables=_names(MAXIMUM_LISTED_VARIABLES + 1)), + ) + + assert [(refusal["loc"], refusal["type"]) for refusal in refusals] == [ + (("variables",), "too_long") + ] + + +@pytest.mark.parametrize("form", list(FORMS)) +def test_a_variable_listed_twice_is_refused_by_name(form: str) -> None: + model, fields = FORMS[form] + + refusals = _refusals(model, fields(variables=["snap", "eitc", "snap"])) + + assert [refusal["loc"] for refusal in refusals] == [("variables",)] + assert "snap" in refusals[0]["msg"] + assert "more than once" in refusals[0]["msg"] + + +@pytest.mark.parametrize("form", list(FORMS)) +def test_a_list_with_add_missing_variables_true_is_refused(form: str) -> None: + model, fields = FORMS[form] + + refusals = _refusals(model, fields(add_missing_variables=True, variables=["snap"])) + + assert [refusal["loc"] for refusal in refusals] == [("variables",)] + assert "add_missing_variables" in refusals[0]["msg"] + + +def test_a_list_with_add_missing_variables_false_is_accepted() -> None: + calculation = _accepted( + HouseholdCalculationInput, + _stored_fields(add_missing_variables=False, variables=["snap"]), + ) + + assert calculation.model_dump().get("variables") == ["snap"] + + +def test_an_empty_variable_name_is_refused() -> None: + refusals = _refusals(HouseholdCalculationInput, _stored_fields(variables=[""])) + + assert [(refusal["loc"], refusal["type"]) for refusal in refusals] == [ + (("variables", 0), "string_too_short") + ] + + +@pytest.mark.parametrize("form", list(FORMS)) +def test_listed_variables_are_sent_to_the_simulation_service(form: str) -> None: + model, fields = FORMS[form] + calculation = _accepted(model, fields(variables=["snap", "eitc"])) + + body = household_calculation_request(calculation) + + assert body.get("variables") == ["snap", "eitc"] + assert body["add_missing_variables"] is False + + +@pytest.mark.parametrize("form", list(FORMS)) +@pytest.mark.parametrize( + "changes", [{}, {"variables": None}], ids=["omitted", "explicit-null"] +) +def test_a_calculation_without_a_list_sends_none( + form: str, changes: dict[str, object] +) -> None: + model, fields = FORMS[form] + calculation = _accepted(model, fields(**changes)) + + body = household_calculation_request(calculation) + + assert "variables" not in body + + +@pytest.fixture +def sessions() -> Iterator[sessionmaker[Session]]: + # Every Session shares one connection, so the route's worker thread reads + # the same in-memory database. + with sqlite_v2_sessions() as session_factory: + yield session_factory + + +def _catalog_version( + session: Session, model: TaxBenefitModel, version: str, names: tuple[str, ...] +) -> None: + """Store a US catalog version with these variables.""" + model_version = TaxBenefitModelVersion( + model=model, version=version, current_law_id=1, metadata_time_periods=[2026] + ) + session.add(model_version) + session.add_all( + Variable(name=name, entity="person", tax_benefit_model_version=model_version) + for name in names + ) + + +def _store(sessions: sessionmaker[Session], *, running_catalog: bool = True) -> None: + """Store the US, its household, and an earlier and the running catalog version. + + Without ``running_catalog``, the running .py version has no published + catalog, only the earlier one. + """ + with sessions() as session: + session.add(Country(id="us", household_enabled=True, society_wide_enabled=True)) + session.add( + Household( + id=HOUSEHOLD_ID, + country_id="us", + default_year=2026, + household_data={"people": []}, + canonicalization_version=1, + content_hash="c" * 64, + ) + ) + model = TaxBenefitModel(name="policyengine-us") + _catalog_version( + session, model, EARLIER_VERSION, (*RUNNING_VARIABLES, REMOVED_VARIABLE) + ) + if running_catalog: + _catalog_version(session, model, POLICYENGINE_VERSION, RUNNING_VARIABLES) + session.commit() + + +@pytest.fixture +def simulation() -> FakeSimulation: + return FakeSimulation() + + +@pytest.fixture +def client(sessions, simulation) -> TestClient: + """Serve the routes on the database-backed services, with the stand-in service.""" + + def service() -> V2HouseholdCalculationService: + return V2HouseholdCalculationService( + sources=HouseholdCalculationSources( + countries=V2CountryService(CountryDatabaseSession(sessions)), + households=V2HouseholdService(HouseholdDatabaseSession(sessions)), + policies=V2PolicyService( + PolicyDatabaseSession(sessions), + running_policyengine_version=POLICYENGINE_VERSION, + ), + dynamics=V2DynamicService( + DynamicDatabaseSession(sessions), + running_policyengine_version=POLICYENGINE_VERSION, + ), + ), + database_session=HouseholdCalculationDatabaseSession(sessions), + simulation_factory=lambda: simulation, + ) + + dependencies = NativeRouteDependencies( + readiness_probe=lambda: True, + gateway_client_factory=lambda: None, + metadata_reader_factory=lambda: None, + v2_household_calculation_service_factory=service, + ) + settings = RouteImplementationSettings( + health=RouteImplementation.FLASK_FALLBACK, + specification=RouteImplementation.FLASK_FALLBACK, + metadata=RouteImplementation.FLASK_FALLBACK, + ) + return TestClient( + create_asgi_app( + Flask(__name__), dependencies=dependencies, route_settings=settings + ), + raise_server_exceptions=False, + ) + + +@pytest.mark.parametrize("form", list(FORMS)) +def test_variables_the_running_catalog_has_are_sent( + client, sessions, simulation, form: str +) -> None: + _store(sessions) + _, fields = FORMS[form] + + response = client.post( + CALCULATIONS, json=fields(variables=["snap", "household_net_income"]) + ) + + assert response.status_code == 202, response.json() + (sent,) = simulation.submissions + assert sent.model_dump().get("variables") == ["snap", "household_net_income"] + + +@pytest.mark.parametrize("form", list(FORMS)) +def test_variables_the_running_catalog_lacks_are_refused_by_name( + client, sessions, simulation, form: str +) -> None: + _store(sessions) + _, fields = FORMS[form] + + response = client.post( + CALCULATIONS, + json=fields(variables=["snap", "not_a_variable", REMOVED_VARIABLE]), + ) + + assert response.status_code == 422 + assert response.json() == { + "status": "error", + "message": ( + "The calculation lists variables the running catalog version does " + f"not have: not_a_variable, {REMOVED_VARIABLE}" + ), + "code": "unknown_variables", + "unknown_variables": ["not_a_variable", REMOVED_VARIABLE], + } + assert simulation.submissions == [] + + +@pytest.mark.parametrize("form", list(FORMS)) +def test_variables_are_sent_unchecked_when_the_running_version_has_no_catalog( + client, sessions, simulation, form: str +) -> None: + _store(sessions, running_catalog=False) + _, fields = FORMS[form] + + response = client.post(CALCULATIONS, json=fields(variables=["not_a_variable"])) + + assert response.status_code == 202, response.json() + (sent,) = simulation.submissions + assert sent.model_dump().get("variables") == ["not_a_variable"] + + +@pytest.mark.parametrize("form", list(FORMS)) +def test_a_list_with_add_missing_variables_true_is_refused_before_anything_is_read( + client, sessions, simulation, form: str +) -> None: + _store(sessions) + _, fields = FORMS[form] + + response = client.post( + CALCULATIONS, json=fields(add_missing_variables=True, variables=["snap"]) + ) + + assert response.status_code == 422 + assert response.json() == INVALID_REQUEST + assert simulation.submissions == [] + + +def test_openapi_documents_the_list_and_its_refusal(client) -> None: + schema = client.get("/v2/openapi.json").json() + components = schema["components"]["schemas"] + + for form in ("HouseholdCalculationRequest", "InlineHouseholdCalculationRequest"): + variables = components[form]["properties"].get("variables", {}) + (listed,) = [ + option for option in variables.get("anyOf", []) if "items" in option + ] or [{}] + assert listed.get("maxItems") == MAXIMUM_LISTED_VARIABLES, form + assert "variables" not in components[form].get("required", []) + submit = schema["paths"][CALCULATIONS]["post"] + refusal = submit["responses"]["422"] + refusal_schema = refusal["content"]["application/json"]["schema"] + refusals = {option["$ref"].rsplit("/", 1)[-1] for option in refusal_schema["anyOf"]} + assert "V2UnknownVariablesErrorResponse" in refusals + assert "unknown_variables" in refusal["description"] + unknown_variables = components.get("V2UnknownVariablesErrorResponse", {}) + assert set(unknown_variables.get("properties", ())) == { + "status", + "message", + "code", + "unknown_variables", + } From 77a057350ab85f1c591481b93f1be2e08ad663e5 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:03:38 +0400 Subject: [PATCH 2/9] Accept a list of variables on household calculations POST /v2/household-calculations takes `variables`, the variables to calculate instead of every variable add_missing_variables adds, for a stored household and for one given in the request. The list holds at most 10,000 distinct names, as the simulation service's household requests do, and is refused when given with add_missing_variables true. After the existing checks, each listed name is checked against the running catalog version, the catalog of the .py version API v1 runs, which policy parameters are checked against: names it lacks are refused with a 422 whose code is unknown_variables and which names them, sorted. When that version has no published catalog for the country, no names are checked. The simulation service is sent the list only when the caller gave one, so a calculation without it is accepted by every release. Co-Authored-By: Claude Opus 5.5 --- .../household-calculation-variables.added.md | 1 + docs/migration/stage-11-v2-households.md | 27 +++++-- .../fastapi_routes/dependencies.py | 1 + .../fastapi_routes/v2/errors_support.py | 21 ++++++ .../household_calculations/request_models.py | 13 ++-- .../household_calculations/response_models.py | 13 +++- .../v2/household_calculations/routes.py | 6 ++ .../libs/simulation_household_calculations.py | 27 +++---- .../database_session.py | 4 +- .../v2/household_calculations/services.py | 72 ++++++++++++++++--- .../v2/household_calculations/types.py | 54 +++++++++++++- .../v2/household_calculations/validators.py | 40 ++++++++++- .../database_connectors/reads_variables.py | 22 ++++++ 13 files changed, 260 insertions(+), 41 deletions(-) create mode 100644 changelog.d/household-calculation-variables.added.md diff --git a/changelog.d/household-calculation-variables.added.md b/changelog.d/household-calculation-variables.added.md new file mode 100644 index 000000000..50d8f254e --- /dev/null +++ b/changelog.d/household-calculation-variables.added.md @@ -0,0 +1 @@ +`POST /v2/household-calculations` accepts `variables`, a list of at most 10,000 distinct variable names to calculate instead of every variable, for a stored household and for one given in the request. API v1 refuses with a 422 (`code` `unknown_variables`, naming them) any name the running catalog version lacks, refuses a list given with `add_missing_variables` true, and sends the list to the simulation service only when it is given. diff --git a/docs/migration/stage-11-v2-households.md b/docs/migration/stage-11-v2-households.md index 0ac726062..a03d4f914 100644 --- a/docs/migration/stage-11-v2-households.md +++ b/docs/migration/stage-11-v2-households.md @@ -304,9 +304,15 @@ are kept. current law, on the simulation service's v2 household functions. It needs no account. The body names `country_id`, `household_id`, an optional `policy_id`, optional `axes` (at most 8 groups of at most 32 axes, one point -count per group, at most 10,000 points in all), `add_missing_variables` and -optional `spm` settings. The year calculated is the household's -`default_year`. Before anything is sent, the Public API checks, in order: +count per group, at most 10,000 points in all), `add_missing_variables`, +optional `variables` and optional `spm` settings. `variables` lists the +variables to calculate instead of every variable `add_missing_variables` +adds: the simulation service adds each, empty, wherever the household gives +it no value for the year, keeps the household's own values, and calculates +the values left empty. It holds at most 10,000 distinct names and is refused +with 422 when given with `add_missing_variables` true. The year calculated +is the household's `default_year`. Before anything is sent, the Public API +checks, in order: 1. that the country's `countries` row has `household_enabled` (422 otherwise); 2. that the household, and the policy when one is named, exist in that @@ -316,9 +322,13 @@ optional `spm` settings. The year calculated is the household's with `code` `missing_parameters` and the parameters' names in `missing_parameters`). A policy no published catalog of the running PolicyEngine.py version can check passes. +5. that every variable `variables` lists is a variable of the running + catalog version (422 with `code` `unknown_variables` and the names in + `unknown_variables`, sorted). When the running .py version has no + published catalog for the country, API v1 checks no names. It then sends the simulation service's `POST /household-calculations` the -IDs and options, with the request's ID and observability ID headers. The +IDs and options, `variables` only when given, with the request's ID and observability ID headers. The answer is 202 with the new job's `calculation_id` and `status`; each submission creates a new job. The simulation service's 422 reasons reach the caller as 422. @@ -327,7 +337,7 @@ caller as 422. Instead of naming a stored household, the body may give one: `country_id`, `year` (1900 to 2200), `household`, an optional `policy`, and the same -`axes`, `add_missing_variables` and `spm` options. A body naming both +`axes`, `add_missing_variables`, `variables` and `spm` options. A body naming both `household_id` and `household` is refused with 422, and so is one naming `policy_id` or `dynamic_id` with `household`. `household` is the situation `/calculate` takes, without axes: people and groups by plural, each record @@ -349,11 +359,14 @@ is sent, API v1 checks, in order: policy parameter or as a dynamic parameter, since `/calculate` accepts the model's assumptions in a policy (422 with `code` `missing_parameters`). As for a stored policy, a policy no published catalog of the running .py - version can check passes. + version can check passes; +4. that every variable `variables` lists is a variable of the running + catalog version, as for a stored household (422 with `code` + `unknown_variables`). It then sends the simulation service the country, the household as given, the year, the policy when one was given, `add_missing_variables`, and the -axes and SPM settings when given. Nothing is written to `households`, +list of variables, axes and SPM settings when given. Nothing is written to `households`, `policies` or the user-household associations. The 202 answer and `GET` name no household, policy or dynamic: `household_id`, `policy_id` and `dynamic_id` are null, and `year` is the year given. A variable the country diff --git a/policyengine_api/fastapi_routes/dependencies.py b/policyengine_api/fastapi_routes/dependencies.py index 2aa7833a4..6d69e581f 100644 --- a/policyengine_api/fastapi_routes/dependencies.py +++ b/policyengine_api/fastapi_routes/dependencies.py @@ -246,6 +246,7 @@ def _default_v2_household_calculation_service_factory() -> ( ), database_session=HouseholdCalculationDatabaseSession(get_v2_session_factory()), simulation_factory=process_simulation_household_calculation_client, + running_policyengine_version=_running_policyengine_version(), ) diff --git a/policyengine_api/fastapi_routes/v2/errors_support.py b/policyengine_api/fastapi_routes/v2/errors_support.py index d809815a0..d0051d214 100644 --- a/policyengine_api/fastapi_routes/v2/errors_support.py +++ b/policyengine_api/fastapi_routes/v2/errors_support.py @@ -68,6 +68,17 @@ class V2MissingParametersErrorResponse(V2ErrorResponse): missing_parameters: list[str] +class V2UnknownVariablesErrorResponse(V2ErrorResponse): + """A refused calculation listing variables the catalog lacks. + + ``unknown_variables`` names each variable the calculation lists that the + running catalog version does not have, sorted. + """ + + code: Literal["unknown_variables"] = "unknown_variables" + unknown_variables: list[str] + + def v2_error_response( status_code: int, message: str, @@ -109,6 +120,16 @@ def v2_missing_parameters_response( return JSONResponse(status_code=422, content=error.model_dump(mode="json")) +def v2_unknown_variables_response( + message: str, unknown_variables: Sequence[str] +) -> JSONResponse: + """Serialize a 422 refusing a calculation that lists variables the catalog lacks.""" + error = V2UnknownVariablesErrorResponse( + message=message, unknown_variables=list(unknown_variables) + ) + return JSONResponse(status_code=422, content=error.model_dump(mode="json")) + + OperationT = TypeVar("OperationT") 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 910231cad..58fd4f847 100644 --- a/policyengine_api/fastapi_routes/v2/household_calculations/request_models.py +++ b/policyengine_api/fastapi_routes/v2/household_calculations/request_models.py @@ -36,8 +36,13 @@ class HouseholdCalculationRequest(HouseholdCalculationInput): 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 + adds every variable the household lacks before calculating. + ``variables`` instead names the variables to calculate: each is added, + empty, wherever the household gives it no value for that year, and + calculated, and the household's own values are kept. It holds at most + 10,000 distinct names, each a variable of the running catalog version, + and is not given with ``add_missing_variables`` true. ``spm`` selects + the SPM forecast scenario and geography for a US household. Each submission starts a new calculation. """ @@ -60,8 +65,8 @@ class InlineHouseholdCalculationRequest(InlineHouseholdCalculationInput): period, as ``/calculate``'s policy does; without it the household is calculated under current law. Each group in ``axes`` varies its inputs in ``year`` across ``count`` points; several groups form a grid of at - most 10,000 points. ``add_missing_variables`` and ``spm`` are as for a - stored household. Neither the household nor the policy is stored, and + most 10,000 points. ``add_missing_variables``, ``variables`` and ``spm`` + are as for a stored household. Neither the household nor the policy is stored, and the calculation is answered with no household or policy ID. Each submission starts a new 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 19b99f0df..1104a5e97 100644 --- a/policyengine_api/fastapi_routes/v2/household_calculations/response_models.py +++ b/policyengine_api/fastapi_routes/v2/household_calculations/response_models.py @@ -11,6 +11,7 @@ from policyengine_api.fastapi_routes.v2.errors_support import ( V2ErrorResponse, V2MissingParametersErrorResponse, + V2UnknownVariablesErrorResponse, ) if TYPE_CHECKING: @@ -208,7 +209,11 @@ class HouseholdCalculationResponse( ), }, 422: { - "model": V2MissingParametersErrorResponse | V2ErrorResponse, + "model": ( + V2MissingParametersErrorResponse + | V2UnknownVariablesErrorResponse + | V2ErrorResponse + ), "description": ( "The request does not match the schema; the country does not offer " "household calculations; the household has no default year; a " @@ -218,8 +223,10 @@ class HouseholdCalculationResponse( "names; the 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 " + "which names them; the policy is checked first); the request lists " + "variables the running catalog version does not have (code " + "unknown_variables, which names them; checked last); 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." diff --git a/policyengine_api/fastapi_routes/v2/household_calculations/routes.py b/policyengine_api/fastapi_routes/v2/household_calculations/routes.py index c73db7253..50e8a4921 100644 --- a/policyengine_api/fastapi_routes/v2/household_calculations/routes.py +++ b/policyengine_api/fastapi_routes/v2/household_calculations/routes.py @@ -25,6 +25,7 @@ V2ErrorMapping, run_v2_operation, v2_missing_parameters_response, + v2_unknown_variables_response, ) from policyengine_api.fastapi_routes.v2.household_calculations.request_models import ( HouseholdCalculationBody, @@ -48,6 +49,7 @@ HouseholdCalculationNotFoundError, HouseholdCalculationResultUnreadableError, HouseholdCalculationStorageError, + HouseholdCalculationVariablesUnknownError, HouseholdCalculationYearError, InlinePolicyParametersMissingError, ) @@ -162,6 +164,10 @@ def submit() -> HouseholdCalculationSubmittedResponse | JSONResponse: return v2_missing_parameters_response( str(error), error.missing_parameters ) + except HouseholdCalculationVariablesUnknownError as error: + return v2_unknown_variables_response( + str(error), error.unknown_variables + ) return HouseholdCalculationSubmittedResponse( result=HouseholdCalculationSubmittedResult( item=HouseholdCalculationSubmittedItem.from_submitted(calculation) diff --git a/policyengine_api/libs/simulation_household_calculations.py b/policyengine_api/libs/simulation_household_calculations.py index 21cc97153..a20b90855 100644 --- a/policyengine_api/libs/simulation_household_calculations.py +++ b/policyengine_api/libs/simulation_household_calculations.py @@ -10,13 +10,14 @@ The request names the country, the stored household and the stored policy (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. A household given in the request is sent instead as the -simulation service's inline request: the country, the household as given, -the year, the parameter values only when the caller gave some (none -calculates current law), ``add_missing_variables``, and the axes and the +the list of variables, the axes and the SPM settings only when the caller +gave them: the simulation service's releases before it took a dynamic, or +a list of variables, refuse any request naming the field, so a +calculation without one is accepted by every release. A household given in +the request is sent instead as the simulation service's inline request: +the country, the household as given, the year, the parameter values only +when the caller gave some (none calculates current law), +``add_missing_variables``, and the list of variables, the axes and the SPM settings only when the caller gave them. The simulation service tells the two apart by which of ``household_id`` and ``household`` the body names. The simulation service's answers are read as follows. @@ -220,11 +221,11 @@ def household_calculation_request( ) -> dict[str, Any]: """Return the simulation service's request body for the calculation. - For a stored household, ``dynamic_id``, ``axes`` and ``spm`` are sent - only when the caller gave them. A household given in the request is sent - as given, with its year, and ``policy``, ``axes`` and ``spm`` only when - the caller gave them. Each axis and the SPM settings keep only the - fields the caller gave. + For a stored household, ``dynamic_id``, ``variables``, ``axes`` and + ``spm`` are sent only when the caller gave them. A household given in the + request is sent as given, with its year, and ``policy``, ``variables``, + ``axes`` and ``spm`` 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} if isinstance(calculation, InlineHouseholdCalculationInput): @@ -240,6 +241,8 @@ def household_calculation_request( if calculation.dynamic_id is not None: body["dynamic_id"] = str(calculation.dynamic_id) body["add_missing_variables"] = calculation.add_missing_variables + if calculation.variables is not None: + body["variables"] = list(calculation.variables) if calculation.axes is not None: body["axes"] = _axes_body(calculation.axes) if calculation.spm is not None: diff --git a/policyengine_api/services/v2/household_calculations/database_session.py b/policyengine_api/services/v2/household_calculations/database_session.py index 621c0c4fb..23a77840c 100644 --- a/policyengine_api/services/v2/household_calculations/database_session.py +++ b/policyengine_api/services/v2/household_calculations/database_session.py @@ -15,8 +15,8 @@ class HouseholdCalculationDatabaseSession: """Open the read sessions the household calculation service uses. - The Public API only reads household jobs; the simulation service writes - them. + The Public API only reads household jobs, which the simulation service + writes, and the running catalog version's variables a calculation lists. """ def __init__(self, session_factory: sessionmaker[Session]) -> None: diff --git a/policyengine_api/services/v2/household_calculations/services.py b/policyengine_api/services/v2/household_calculations/services.py index 2698feb09..e6d8be53b 100644 --- a/policyengine_api/services/v2/household_calculations/services.py +++ b/policyengine_api/services/v2/household_calculations/services.py @@ -10,7 +10,11 @@ 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 +parameter the running catalog version lacks. Last, every variable the +calculation lists must be a variable of the running catalog version (the +catalog of the .py version API v1 runs, as for parameters), unless that +version has no published catalog for the country, when nothing can be +checked. 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 @@ -24,7 +28,8 @@ catalog version must have every parameter the values set, as a policy or a dynamic parameter: ``/calculate`` accepts the model's assumptions in a policy, and the inline form names no -dynamic. Nothing is read from or written to the households and policies +dynamic. The variables it lists are then checked as for a stored +household. Nothing is read from or written to the households and policies tables; the simulation service is sent the household, the values, the year and the options, and records the job with no household or policy ID. @@ -40,7 +45,9 @@ from sqlalchemy.exc import SQLAlchemyError +from policyengine_api.constants import POLICYENGINE_VERSION from policyengine_api.data.v2.catalog.catalog_selection_validation import ( + MetadataCatalogNotPublishedError, MetadataCatalogUnavailableError, ) from policyengine_api.services.v2.household_calculations.database_connectors import ( @@ -61,8 +68,15 @@ require_household_country, require_inline_household_values, require_inline_policy_parameters_present, + require_known_variables, stored_household_outcome, ) +from policyengine_api.services.v2.metadata.database_connectors.reads import ( + read_metadata_catalog, +) +from policyengine_api.services.v2.metadata.database_connectors.reads_variables import ( + read_variable_names, +) from policyengine_api.services.v2.policies.validators import ( require_policy_parameters_present, ) @@ -92,9 +106,9 @@ 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, and the dynamic check's - reads, which ``require_runnable_dynamics`` reports as - SubmissionStorageError. + reports as MetadataCatalogUnavailableError, as the variable check's + catalog reads do, and the dynamic check's reads, which + ``require_runnable_dynamics`` reports as SubmissionStorageError. """ try: yield @@ -116,10 +130,13 @@ def __init__( sources: HouseholdCalculationSources, database_session: HouseholdCalculationDatabaseSession, simulation_factory: Callable[[], HouseholdCalculationSubmitter], + running_policyengine_version: str = POLICYENGINE_VERSION, ) -> None: """Read through these services and sessions for one request. - A submission is checked against ``sources``; a read reads only + A submission is checked against ``sources``, and the variables it + lists against the catalog of ``running_policyengine_version``, read + through ``database_session``; 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 @@ -128,6 +145,7 @@ def __init__( self._sources = sources self._database_session = database_session self._simulation_factory = simulation_factory + self._running_policyengine_version = running_policyengine_version def submit_calculation( self, calculation: HouseholdCalculationSubmission @@ -137,11 +155,12 @@ def submit_calculation( For a stored household, raise HouseholdCalculationCountryError, HouseholdNotFoundError, PolicyNotFoundError, HouseholdCalculationYearError, PolicyParametersMissingError, - DynamicNotFoundError or DynamicParametersMissingError, in that - order, before anything is sent. For a household given in the - request, raise HouseholdCalculationInputError, - HouseholdCalculationCountryError or - InlinePolicyParametersMissingError, in that order. Raise + DynamicNotFoundError, DynamicParametersMissingError or + HouseholdCalculationVariablesUnknownError, in that order, before + anything is sent. For a household given in the request, raise + HouseholdCalculationInputError, HouseholdCalculationCountryError, + InlinePolicyParametersMissingError or + HouseholdCalculationVariablesUnknownError, in that order. Raise HouseholdCalculationStorageError when the database cannot be read, and the simulation service's errors when it refuses the calculation. """ @@ -166,6 +185,7 @@ def _submit_inline_calculation( ) ) require_inline_policy_parameters_present(missing_parameters) + self._require_known_variables(country_id, calculation.variables) accepted = self._simulation_factory().submit(calculation) return household_calculation_submitted( calculation, accepted, year=calculation.year @@ -204,9 +224,39 @@ def _submit_stored_calculation( country_id=country_id, dynamic_ids=(calculation.dynamic_id,), ) + self._require_known_variables(country_id, calculation.variables) accepted = self._simulation_factory().submit(calculation) return household_calculation_submitted(calculation, accepted, year=year) + def _require_known_variables( + self, country_id: str, variables: list[str] | None + ) -> None: + """Raise HouseholdCalculationVariablesUnknownError for unknown listed names. + + The names are checked against the running catalog version; nothing is + read for a calculation listing none, and nothing is checked when the + running .py version has no published catalog for the country. + """ + if not variables: + return + with _storage_failures(), self._database_session.read() as session: + try: + selected = read_metadata_catalog( + session, + country_id=country_id, + running_policyengine_version=self._running_policyengine_version, + policyengine_version=None, + ) + except MetadataCatalogNotPublishedError: + catalog_variables = None + else: + catalog_variables = read_variable_names( + session, + model_version_id=selected.model_version.id, + names=variables, + ) + require_known_variables(variables, catalog_variables) + def get_calculation(self, calculation_id: UUID) -> HouseholdCalculationRead: """Return the calculation household_jobs records. diff --git a/policyengine_api/services/v2/household_calculations/types.py b/policyengine_api/services/v2/household_calculations/types.py index 33a8cda2e..87b0d0dcc 100644 --- a/policyengine_api/services/v2/household_calculations/types.py +++ b/policyengine_api/services/v2/household_calculations/types.py @@ -3,11 +3,19 @@ from __future__ import annotations import math +from collections import Counter from dataclasses import dataclass from typing import TYPE_CHECKING, Annotated, Any, Literal, Protocol from uuid import UUID -from pydantic import BaseModel, ConfigDict, Field, JsonValue, field_validator +from pydantic import ( + BaseModel, + ConfigDict, + Field, + JsonValue, + ValidationInfo, + field_validator, +) from pydantic.json_schema import SkipJsonSchema from policyengine_api.query_parameters import CountryId @@ -29,6 +37,12 @@ MAXIMUM_AXIS_POINTS = 10_000 MAXIMUM_AXIS_GROUPS = 8 MAXIMUM_PARALLEL_AXES = 32 +# The most variables one calculation may list, as the simulation service's +# household requests limit them. +MAXIMUM_LISTED_VARIABLES = 10_000 + +# A listed variable's name: at most as long as the variables table's names. +ListedVariableName = Annotated[str, Field(min_length=1, max_length=512)] # A household job's status, as household_jobs stores it: the simulation # service inserts the job pending, its household function sets it running, @@ -92,6 +106,13 @@ class HouseholdCalculationInputOptions(StrictCalculationModel): so they share one point count, and the groups form a grid of at most 10,000 points. ``add_missing_variables`` adds every yearly, monthly and eternal variable the household lacks, as ``/calculate-full`` does. + ``variables`` instead names the variables to calculate: the simulation + service adds each, empty, wherever the household gives it no value for + the calculation's year, keeps every value the household gives, and + calculates the values left empty, as without the list. It holds at most + 10,000 distinct names, each checked against the running catalog version + before the calculation is sent, and is not given with + ``add_missing_variables`` true; null or none lists no variables. ``spm`` selects the SPM forecast scenario and geography for this calculation; omit it, rather than sending null, to send no settings. """ @@ -100,6 +121,11 @@ class HouseholdCalculationInputOptions(StrictCalculationModel): None ) add_missing_variables: bool = False + # After add_missing_variables, whose value its check reads. + variables: ( + Annotated[list[ListedVariableName], Field(max_length=MAXIMUM_LISTED_VARIABLES)] + | None + ) = None spm: SPMSelection | SkipJsonSchema[None] = Field( default=None, json_schema_extra=_omit_spm_default ) @@ -121,6 +147,32 @@ def limit_axis_points( raise ValueError(msg) return axes + @field_validator("variables") + @classmethod + def refuse_repeated_or_redundant_variables( + cls, variables: list[str] | None, info: ValidationInfo + ) -> list[str] | None: + """Refuse a list given with ``add_missing_variables`` true, or naming one twice. + + ``add_missing_variables`` calculates every variable, which a list + would contradict, as the simulation service refuses it. + """ + if variables is None: + return None + if info.data.get("add_missing_variables"): + msg = ( + "variables can't be given with add_missing_variables true, " + "which calculates every variable" + ) + raise ValueError(msg) + repeated = sorted( + name for name, count in Counter(variables).items() if count > 1 + ) + if repeated: + msg = f"variables names {', '.join(repeated)} more than once" + raise ValueError(msg) + return variables + @field_validator("spm", mode="before") @classmethod def require_spm_object(cls, value: object) -> object: diff --git a/policyengine_api/services/v2/household_calculations/validators.py b/policyengine_api/services/v2/household_calculations/validators.py index 05bb5e96a..97994be7d 100644 --- a/policyengine_api/services/v2/household_calculations/validators.py +++ b/policyengine_api/services/v2/household_calculations/validators.py @@ -13,7 +13,7 @@ ) if TYPE_CHECKING: - from collections.abc import Iterable, Mapping + from collections.abc import Collection, Iterable, Mapping from uuid import UUID from pydantic import JsonValue @@ -73,6 +73,27 @@ def __str__(self) -> str: ) +class HouseholdCalculationVariablesUnknownError(ValueError): + """The calculation lists variables the running catalog version lacks. + + A calculation refuses them before anything runs, as it refuses parameters + the catalog lacks; ``unknown_variables`` lists them, sorted. + """ + + def __init__(self, unknown_variables: tuple[str, ...]) -> None: + """Name the listed variables that are unknown.""" + self.unknown_variables = unknown_variables + # The arguments, in order, so copy and pickle can rebuild the error. + super().__init__(unknown_variables) + + def __str__(self) -> str: + """Name each unknown variable.""" + return ( + "The calculation lists variables the running catalog version does " + f"not have: {', '.join(self.unknown_variables)}" + ) + + class HouseholdCalculationNotFoundError(LookupError): """household_jobs has no job with this ID.""" @@ -184,6 +205,23 @@ def require_inline_policy_parameters_present( raise InlinePolicyParametersMissingError(missing_parameters) +def require_known_variables( + listed_variables: Iterable[str], catalog_variables: Collection[str] | None +) -> None: + """Raise HouseholdCalculationVariablesUnknownError for unknown listed names. + + ``catalog_variables`` holds the listed names the running catalog version + has as variables. It is None when the running .py version has no + published catalog for the country, so nothing could be checked, which + passes, as it does for a policy's parameters. + """ + if catalog_variables is None: + return + unknown_variables = tuple(sorted(set(listed_variables) - set(catalog_variables))) + if unknown_variables: + raise HouseholdCalculationVariablesUnknownError(unknown_variables) + + def require_axes_in_year( axes: Iterable[Iterable[HouseholdCalculationAxis]] | None, *, year: int ) -> None: diff --git a/policyengine_api/services/v2/metadata/database_connectors/reads_variables.py b/policyengine_api/services/v2/metadata/database_connectors/reads_variables.py index 13a7888b4..797dc743c 100644 --- a/policyengine_api/services/v2/metadata/database_connectors/reads_variables.py +++ b/policyengine_api/services/v2/metadata/database_connectors/reads_variables.py @@ -11,6 +11,7 @@ from policyengine_api.services.v2.metadata.database_connectors.reads import read_rows if TYPE_CHECKING: + from collections.abc import Collection from uuid import UUID from policyengine_api.data.v2.models.metadata import CatalogEnumValue @@ -66,6 +67,27 @@ def read_variable( return rows[0] if rows else None +def read_variable_names( + session: Session, *, model_version_id: UUID, names: Collection[str] +) -> set[str]: + """Return which of ``names`` the model version has as variables. + + A calculation lists at most 10,000 names, well under PostgreSQL's limit + of 65,535 bound values in one statement. + """ + if not names: + return set() + return set( + read_rows( + session, + select(Variable.name).where( + col(Variable.tax_benefit_model_version_id) == model_version_id, + col(Variable.name).in_(sorted(set(names))), + ), + ) + ) + + def read_all_variables(session: Session, *, model_version_id: UUID) -> list[Variable]: """Return every variable of a model version in name order.""" return read_rows( From b25523294091a6f4c04fa4220de4693fbae473b9 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:06:00 +0400 Subject: [PATCH 3/9] Add a test that fails while variable names may exceed 255 characters The simulation service's household contract takes variable names of at most 255 characters, so API v1 should refuse a longer listed name before sending it, not let the simulation service refuse it. Co-Authored-By: Claude Opus 5.5 --- .../v2/test_household_calculation_variables.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/unit/v2/test_household_calculation_variables.py b/tests/unit/v2/test_household_calculation_variables.py index 03f886f94..bc6428d5e 100644 --- a/tests/unit/v2/test_household_calculation_variables.py +++ b/tests/unit/v2/test_household_calculation_variables.py @@ -78,6 +78,8 @@ RUNNING_VARIABLES = ("employment_income", "household_net_income", "snap") REMOVED_VARIABLE = "removed_benefit" MAXIMUM_LISTED_VARIABLES = 10_000 +# The longest variable name the simulation service's household contract takes. +MAXIMUM_VARIABLE_NAME_LENGTH = 255 INLINE_HOUSEHOLD = { "people": {"you": {"age": 40}}, "households": {"your household": {"members": ["you"]}}, @@ -215,6 +217,22 @@ def test_an_empty_variable_name_is_refused() -> None: ] +def test_a_name_longer_than_the_simulation_service_takes_is_refused() -> None: + longest_name = "v" * MAXIMUM_VARIABLE_NAME_LENGTH + + longest_refusals = _refusals( + HouseholdCalculationInput, _stored_fields(variables=[longest_name]) + ) + longer_refusals = _refusals( + HouseholdCalculationInput, _stored_fields(variables=[f"{longest_name}v"]) + ) + + assert longest_refusals == [] + assert [(refusal["loc"], refusal["type"]) for refusal in longer_refusals] == [ + (("variables", 0), "string_too_long") + ] + + @pytest.mark.parametrize("form", list(FORMS)) def test_listed_variables_are_sent_to_the_simulation_service(form: str) -> None: model, fields = FORMS[form] From 69443265b09649db43722f1de17e993e209fb332 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:07:19 +0400 Subject: [PATCH 4/9] Limit listed variable names to 255 characters, as the simulation service does Co-Authored-By: Claude Opus 5.5 --- policyengine_api/services/v2/household_calculations/types.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/policyengine_api/services/v2/household_calculations/types.py b/policyengine_api/services/v2/household_calculations/types.py index 87b0d0dcc..7bf290dec 100644 --- a/policyengine_api/services/v2/household_calculations/types.py +++ b/policyengine_api/services/v2/household_calculations/types.py @@ -41,8 +41,9 @@ # household requests limit them. MAXIMUM_LISTED_VARIABLES = 10_000 -# A listed variable's name: at most as long as the variables table's names. -ListedVariableName = Annotated[str, Field(min_length=1, max_length=512)] +# A listed variable's name, as long as the simulation service's household +# contract takes variable names. +ListedVariableName = Annotated[str, Field(min_length=1, max_length=255)] # A household job's status, as household_jobs stores it: the simulation # service inserts the job pending, its household function sets it running, From cca563ad4ef4608d588bfe4dc88f84ba19e65468 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:33:02 +0400 Subject: [PATCH 5/9] Add tests for a NUL character in a listed name and an unreadable catalog A listed variable name holding a NUL character is to be refused as the caller's data, since PostgreSQL text can't hold NUL and the catalog query would otherwise fail as a storage outage (503). Also cover the variable check's 503 when the catalog can't be queried, and name the test of a list given with add_missing_variables true for what it asserts. Co-Authored-By: Claude Opus 5.5 --- .../test_household_calculation_variables.py | 36 +++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/tests/unit/v2/test_household_calculation_variables.py b/tests/unit/v2/test_household_calculation_variables.py index bc6428d5e..375f8c050 100644 --- a/tests/unit/v2/test_household_calculation_variables.py +++ b/tests/unit/v2/test_household_calculation_variables.py @@ -63,7 +63,7 @@ PolicyDatabaseSession, ) from policyengine_api.services.v2.policies.services import V2PolicyService -from tests.fixtures.database_sessions import sqlite_v2_sessions +from tests.fixtures.database_sessions import drop_tables, sqlite_v2_sessions from tests.unit.v2.household_calculation_support import HOUSEHOLD_ID, FakeSimulation if TYPE_CHECKING: @@ -233,6 +233,18 @@ def test_a_name_longer_than_the_simulation_service_takes_is_refused() -> None: ] +@pytest.mark.parametrize("form", list(FORMS)) +def test_a_name_holding_a_nul_character_is_refused(form: str) -> None: + # PostgreSQL text can't hold NUL, so no catalog variable is named with + # one, and the catalog query would fail on it as on a storage outage. + model, fields = FORMS[form] + + refusals = _refusals(model, fields(variables=["snap", "sn\x00ap"])) + + assert [refusal["loc"] for refusal in refusals] == [("variables",)] + assert "NUL" in refusals[0]["msg"] + + @pytest.mark.parametrize("form", list(FORMS)) def test_listed_variables_are_sent_to_the_simulation_service(form: str) -> None: model, fields = FORMS[form] @@ -410,7 +422,7 @@ def test_variables_are_sent_unchecked_when_the_running_version_has_no_catalog( @pytest.mark.parametrize("form", list(FORMS)) -def test_a_list_with_add_missing_variables_true_is_refused_before_anything_is_read( +def test_a_list_with_add_missing_variables_true_is_refused_and_not_sent( client, sessions, simulation, form: str ) -> None: _store(sessions) @@ -425,6 +437,26 @@ def test_a_list_with_add_missing_variables_true_is_refused_before_anything_is_re assert simulation.submissions == [] +@pytest.mark.parametrize("form", list(FORMS)) +def test_a_variable_check_whose_catalog_cannot_be_queried_answers_503( + client, sessions, simulation, form: str +) -> None: + _store(sessions) + # Only the variable check reads this table. + with sessions.begin() as session: + drop_tables(session, Variable) + _, fields = FORMS[form] + + response = client.post(CALCULATIONS, json=fields(variables=["snap"])) + + assert response.status_code == 503 + assert response.json() == { + "status": "error", + "message": "V2 household calculation storage is unavailable", + } + assert simulation.submissions == [] + + def test_openapi_documents_the_list_and_its_refusal(client) -> None: schema = client.get("/v2/openapi.json").json() components = schema["components"]["schemas"] From 2a2cd27438338f43bed4f678393591e89e470818 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:34:22 +0400 Subject: [PATCH 6/9] Refuse a listed variable name holding a NUL character PostgreSQL text can't hold NUL, so the catalog query failed on such a name and the calculation was answered 503, as for a storage outage. The request model now refuses it with a 422. Also: the migration doc lists the dynamic check and the variable check's 503 and says API v1, the household calculation session's docstring says API v1, and the changelog fragment says what the list does next to add_missing_variables and that names go unchecked when the running .py version has no published catalog. Co-Authored-By: Claude Opus 5.5 --- changelog.d/household-calculation-variables.added.md | 2 +- docs/migration/stage-11-v2-households.md | 12 ++++++++---- .../v2/household_calculations/database_session.py | 4 ++-- .../services/v2/household_calculations/types.py | 8 +++++++- 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/changelog.d/household-calculation-variables.added.md b/changelog.d/household-calculation-variables.added.md index 50d8f254e..66aea168c 100644 --- a/changelog.d/household-calculation-variables.added.md +++ b/changelog.d/household-calculation-variables.added.md @@ -1 +1 @@ -`POST /v2/household-calculations` accepts `variables`, a list of at most 10,000 distinct variable names to calculate instead of every variable, for a stored household and for one given in the request. API v1 refuses with a 422 (`code` `unknown_variables`, naming them) any name the running catalog version lacks, refuses a list given with `add_missing_variables` true, and sends the list to the simulation service only when it is given. +`POST /v2/household-calculations` accepts `variables`, a list of at most 10,000 distinct variable names, for a stored household and for one given in the request: the simulation service adds each listed variable where the household has no value for the year and calculates it, as `add_missing_variables: true` does for every variable. API v1 refuses with a 422 (`code` `unknown_variables`, naming them) any listed name the running catalog version lacks, checking none when that .py version has no published catalog for the country; it refuses a list given with `add_missing_variables` true, and sends the list to the simulation service only when it is given. diff --git a/docs/migration/stage-11-v2-households.md b/docs/migration/stage-11-v2-households.md index a03d4f914..14a6326f0 100644 --- a/docs/migration/stage-11-v2-households.md +++ b/docs/migration/stage-11-v2-households.md @@ -311,8 +311,8 @@ adds: the simulation service adds each, empty, wherever the household gives it no value for the year, keeps the household's own values, and calculates the values left empty. It holds at most 10,000 distinct names and is refused with 422 when given with `add_missing_variables` true. The year calculated -is the household's `default_year`. Before anything is sent, the Public API -checks, in order: +is the household's `default_year`. A name holding a NUL character is refused +with 422 too. Before anything is sent, API v1 checks, in order: 1. that the country's `countries` row has `household_enabled` (422 otherwise); 2. that the household, and the policy when one is named, exist in that @@ -322,7 +322,10 @@ checks, in order: with `code` `missing_parameters` and the parameters' names in `missing_parameters`). A policy no published catalog of the running PolicyEngine.py version can check passes. -5. that every variable `variables` lists is a variable of the running +5. that the dynamic, when one is named, is stored in that country (404 + otherwise) and sets no parameter the running catalog version lacks (422 + with `code` `missing_parameters`); +6. that every variable `variables` lists is a variable of the running catalog version (422 with `code` `unknown_variables` and the names in `unknown_variables`, sorted). When the running .py version has no published catalog for the country, API v1 checks no names. @@ -380,7 +383,8 @@ rate limits, before its route runs), its own 503, which names its code (it isn't configured, its manifest or database can't be read, or Modal refused the call, after which it fails the job it had created), a refusal the Public API can't read, a connection never made, missing configuration and a gateway -token it can't fetch. A failed catalog query in the policy check is 503 too. +token it can't fetch. A failed catalog query in the policy check or the variable check is 503 +too. Answers that may come after it created the job are 502: a 202 whose body the Public API can't read, its 500 (`internal_error`), any status not named diff --git a/policyengine_api/services/v2/household_calculations/database_session.py b/policyengine_api/services/v2/household_calculations/database_session.py index 23a77840c..36217f42a 100644 --- a/policyengine_api/services/v2/household_calculations/database_session.py +++ b/policyengine_api/services/v2/household_calculations/database_session.py @@ -15,8 +15,8 @@ class HouseholdCalculationDatabaseSession: """Open the read sessions the household calculation service uses. - The Public API only reads household jobs, which the simulation service - writes, and the running catalog version's variables a calculation lists. + API v1 only reads household jobs, which the simulation service writes, + and the running catalog version's variables a calculation lists. """ def __init__(self, session_factory: sessionmaker[Session]) -> None: diff --git a/policyengine_api/services/v2/household_calculations/types.py b/policyengine_api/services/v2/household_calculations/types.py index 7bf290dec..3d3aa812e 100644 --- a/policyengine_api/services/v2/household_calculations/types.py +++ b/policyengine_api/services/v2/household_calculations/types.py @@ -156,7 +156,10 @@ def refuse_repeated_or_redundant_variables( """Refuse a list given with ``add_missing_variables`` true, or naming one twice. ``add_missing_variables`` calculates every variable, which a list - would contradict, as the simulation service refuses it. + would contradict, as the simulation service refuses it. A name + holding a NUL character is refused too: PostgreSQL text can't hold + one, so no catalog variable has such a name, and the catalog query + would fail on it. """ if variables is None: return None @@ -166,6 +169,9 @@ def refuse_repeated_or_redundant_variables( "which calculates every variable" ) raise ValueError(msg) + if any("\x00" in name for name in variables): + msg = "variables can't name a variable with a NUL character" + raise ValueError(msg) repeated = sorted( name for name, count in Counter(variables).items() if count > 1 ) From 1ad1b3cb84863b80e405704e905ee8aa53a1acee Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:49:22 +0400 Subject: [PATCH 7/9] Cover the variable check's order and an empty list, and document both limits Tests: an unknown household is answered 404 before its listed variables are checked, and an empty list is accepted and sent as given, for both request forms. The request and options docstrings (which the OpenAPI document shows) and the migration doc now give the per-name limit, the NUL refusal, the unpublished-catalog exception and what an empty list does, and the doc names the optional dynamic_id. Co-Authored-By: Claude Opus 5.5 --- docs/migration/stage-11-v2-households.md | 7 +++-- .../household_calculations/request_models.py | 6 ++-- .../v2/household_calculations/types.py | 8 +++-- .../test_household_calculation_variables.py | 29 +++++++++++++++++++ 4 files changed, 42 insertions(+), 8 deletions(-) diff --git a/docs/migration/stage-11-v2-households.md b/docs/migration/stage-11-v2-households.md index 14a6326f0..d133ee2fd 100644 --- a/docs/migration/stage-11-v2-households.md +++ b/docs/migration/stage-11-v2-households.md @@ -303,14 +303,15 @@ are kept. `/v2/households`, under a policy stored through `/v2/policies` or under current law, on the simulation service's v2 household functions. It needs no account. The body names `country_id`, `household_id`, an optional -`policy_id`, optional `axes` (at most 8 groups of at most 32 axes, one point +`policy_id`, an optional `dynamic_id`, optional `axes` (at most 8 groups of at most 32 axes, one point count per group, at most 10,000 points in all), `add_missing_variables`, optional `variables` and optional `spm` settings. `variables` lists the variables to calculate instead of every variable `add_missing_variables` adds: the simulation service adds each, empty, wherever the household gives it no value for the year, keeps the household's own values, and calculates -the values left empty. It holds at most 10,000 distinct names and is refused -with 422 when given with `add_missing_variables` true. The year calculated +the values left empty. It holds at most 10,000 distinct names of 1 to 255 +characters and is refused with 422 when given with `add_missing_variables` +true. The year calculated is the household's `default_year`. A name holding a NUL character is refused with 422 too. Before anything is sent, API v1 checks, in order: 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 58fd4f847..681c49957 100644 --- a/policyengine_api/fastapi_routes/v2/household_calculations/request_models.py +++ b/policyengine_api/fastapi_routes/v2/household_calculations/request_models.py @@ -40,8 +40,10 @@ class HouseholdCalculationRequest(HouseholdCalculationInput): ``variables`` instead names the variables to calculate: each is added, empty, wherever the household gives it no value for that year, and calculated, and the household's own values are kept. It holds at most - 10,000 distinct names, each a variable of the running catalog version, - and is not given with ``add_missing_variables`` true. ``spm`` selects + 10,000 distinct names of 1 to 255 characters with no NUL character, each + a variable of the running catalog version (unchecked when that version + has no published catalog for the country), and is not given with + ``add_missing_variables`` true; an empty list adds none. ``spm`` selects the SPM forecast scenario and geography for a US household. Each submission starts a new calculation. """ diff --git a/policyengine_api/services/v2/household_calculations/types.py b/policyengine_api/services/v2/household_calculations/types.py index 3d3aa812e..e57d12fe4 100644 --- a/policyengine_api/services/v2/household_calculations/types.py +++ b/policyengine_api/services/v2/household_calculations/types.py @@ -111,9 +111,11 @@ class HouseholdCalculationInputOptions(StrictCalculationModel): service adds each, empty, wherever the household gives it no value for the calculation's year, keeps every value the household gives, and calculates the values left empty, as without the list. It holds at most - 10,000 distinct names, each checked against the running catalog version - before the calculation is sent, and is not given with - ``add_missing_variables`` true; null or none lists no variables. + 10,000 distinct names of 1 to 255 characters with no NUL character, each + checked against the running catalog version before the calculation is + sent unless that version has no published catalog for the country, and + is not given with ``add_missing_variables`` true. Null or an omitted + field lists no variables; an empty list adds none. ``spm`` selects the SPM forecast scenario and geography for this calculation; omit it, rather than sending null, to send no settings. """ diff --git a/tests/unit/v2/test_household_calculation_variables.py b/tests/unit/v2/test_household_calculation_variables.py index 375f8c050..678b223f6 100644 --- a/tests/unit/v2/test_household_calculation_variables.py +++ b/tests/unit/v2/test_household_calculation_variables.py @@ -13,6 +13,7 @@ from __future__ import annotations from typing import TYPE_CHECKING, Any, TypeVar +from uuid import uuid4 import pytest from fastapi.testclient import TestClient @@ -407,6 +408,34 @@ def test_variables_the_running_catalog_lacks_are_refused_by_name( assert simulation.submissions == [] +def test_an_unknown_household_is_not_found_before_variables_are_checked( + client, sessions, simulation +) -> None: + _store(sessions) + + response = client.post( + CALCULATIONS, + json=_stored_fields(household_id=str(uuid4()), variables=["not_a_variable"]), + ) + + assert response.status_code == 404 + assert simulation.submissions == [] + + +@pytest.mark.parametrize("form", list(FORMS)) +def test_an_empty_list_is_sent_as_given( + client, sessions, simulation, form: str +) -> None: + _store(sessions) + _, fields = FORMS[form] + + response = client.post(CALCULATIONS, json=fields(variables=[])) + + assert response.status_code == 202, response.json() + (sent,) = simulation.submissions + assert sent.model_dump().get("variables") == [] + + @pytest.mark.parametrize("form", list(FORMS)) def test_variables_are_sent_unchecked_when_the_running_version_has_no_catalog( client, sessions, simulation, form: str From ca98ba2fbca7a5c10a065749a92a1efe64a4e9dc Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:10:24 +0400 Subject: [PATCH 8/9] Add generated-client cases that list variables, which fail on the current pin A stored and an inline household calculation listing variables, and each with an empty list, are sent through the simulation service's generated client. On policyengine-api-simulation-client 0.20261201.454, whose request models have no variables field, send_request_with_body refuses before sending (ValueError naming variables); they pass once the pin is raised to the release with the field. Co-Authored-By: Claude Opus 5.5 --- tests/unit/libs/test_simulation_generated_client.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/unit/libs/test_simulation_generated_client.py b/tests/unit/libs/test_simulation_generated_client.py index 822f6cda8..05f4fb8b2 100644 --- a/tests/unit/libs/test_simulation_generated_client.py +++ b/tests/unit/libs/test_simulation_generated_client.py @@ -292,6 +292,8 @@ def assert_sent_through_generated_operation( ], "spm": NULL_SPM_OPTIONS, }, + "a list of variables": {"variables": ["household_net_income", "snap"]}, + "an empty list of variables": {"variables": []}, } @@ -441,6 +443,8 @@ def inline_calculation_input(**changes: object) -> InlineHouseholdCalculationInp ], "spm": NULL_SPM_OPTIONS, }, + "a list of variables": {"variables": ["household_net_income", "snap"]}, + "an empty list of variables": {"variables": []}, } From 3f3c326df1732a67a710aceb9af0b02dea278818 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:03:30 +0400 Subject: [PATCH 9/9] Pin the simulation service's client release that takes a list of variables policyengine-api-simulation-client 0.20261202.458, published by PolicyEngine/policyengine-sim-api#1177's release, has `variables` on its HouseholdCalculationRequest and InlineHouseholdCalculationRequest, so a household calculation that lists variables is sent through the generated client instead of being refused before sending. Co-Authored-By: Claude Opus 5.5 --- pyproject.toml | 10 ++++++---- uv.lock | 8 ++++---- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 8980066ea..bf2be89e1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -57,11 +57,13 @@ dependencies = [ # (policyengine_api.libs.simulation_service_operations). The pin is a # release whose request models hold every field those requests send, # including the inline household calculation's - # (InlineHouseholdCalculationRequest, from 0.20261201.450), and that has - # create_report_without_run (from 0.20261201.454); moving it is its own - # change, tested by tests/unit/libs/test_simulation_generated_client.py and + # (InlineHouseholdCalculationRequest, from 0.20261201.450) and the list + # of variables either household calculation names (variables, from + # 0.20261202.458), and that has create_report_without_run (from + # 0.20261201.454); moving it is its own change, tested by + # tests/unit/libs/test_simulation_generated_client.py and # tests/unit/libs/test_simulation_reports_without_runs.py. - "policyengine-api-simulation-client==0.20261201.454", + "policyengine-api-simulation-client==0.20261202.458", "pydantic", "pymysql", "python-dotenv", diff --git a/uv.lock b/uv.lock index 348362a9f..bbcce5735 100644 --- a/uv.lock +++ b/uv.lock @@ -3074,7 +3074,7 @@ requires-dist = [ { name = "openai" }, { name = "packaging", specifier = ">=24,<27" }, { name = "policyengine", extras = ["models"], specifier = "==6.20.4" }, - { name = "policyengine-api-simulation-client", specifier = "==0.20261201.454" }, + { name = "policyengine-api-simulation-client", specifier = "==0.20261202.458" }, { name = "policyengine-observability", extras = ["flask", "google", "httpx", "otlp-grpc"], specifier = ">=3.0.3,<4" }, { name = "psycopg", extras = ["binary"], specifier = ">=3.3,<4" }, { name = "pydantic" }, @@ -3103,15 +3103,15 @@ telemetry-error-issues = [{ name = "google-cloud-bigquery", specifier = ">=3.30, [[package]] name = "policyengine-api-simulation-client" -version = "0.20261201.454" +version = "0.20261202.458" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "attrs" }, { name = "httpx" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/44/e1/240821339fdca27a7db09f4e11467107ab5c4b77caa2a3f0cd96a68c6578/policyengine_api_simulation_client-0.20261201.454.tar.gz", hash = "sha256:9663c209fb2a1af41c4d7c0168a161a84ee71cf5484232c1f6d1edf8b374c266", size = 77171, upload-time = "2026-12-01T16:42:38.631Z" } +sdist = { url = "https://files.pythonhosted.org/packages/8e/dc/544fc39ce5a5fba38e6d047b5502709e7eaa6381608cd3aad16f91da01eb/policyengine_api_simulation_client-0.20261202.458.tar.gz", hash = "sha256:aa0140c8759469c28f04ddba3f160e7550babdd0f05d5bab4bd4493810613c71", size = 77732, upload-time = "2026-12-02T15:32:33.729Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/74/7f/1920dc8272813d8d4001666e3c7185818a4e0cd29407c81e24c27dc9ae83/policyengine_api_simulation_client-0.20261201.454-py3-none-any.whl", hash = "sha256:7b201b7df45e1967bcec4e8eddd26409b4e83b5e8bde22f443b8c2cae2576f98", size = 173233, upload-time = "2026-12-01T16:42:37.101Z" }, + { url = "https://files.pythonhosted.org/packages/7e/97/0f8a474397cbf2ce4cef06d1f67faa5d6b3b2cfdc9b025c0f6c9f81cb551/policyengine_api_simulation_client-0.20261202.458-py3-none-any.whl", hash = "sha256:22e102b03184138c01a7552bd7f58d5105cf4a75c59ae3d54961fce179a26a15", size = 173829, upload-time = "2026-12-02T15:32:32.363Z" }, ] [[package]]