diff --git a/changelog.d/household-calculation-variables.added.md b/changelog.d/household-calculation-variables.added.md new file mode 100644 index 000000000..5943ac176 --- /dev/null +++ b/changelog.d/household-calculation-variables.added.md @@ -0,0 +1 @@ +`POST /household-calculations` takes `variables`, a list of the variables to calculate, for a stored household or one given in the request. The household function adds each listed variable for the calculation year wherever the household has no value for it in that year, and keeps every value the household gives. This is an alternative to `add_missing_variables`, which calculates every variable and can't be sent together with `variables`. diff --git a/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/household_execution.py b/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/household_execution.py index 343e0f355..c32380ab3 100644 --- a/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/household_execution.py +++ b/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/household_execution.py @@ -38,6 +38,8 @@ JsonValue, PrivateAttr, TypeAdapter, + ValidationInfo, + field_validator, model_serializer, model_validator, ) @@ -74,6 +76,9 @@ MAXIMUM_AXIS_POINTS = 10_000 MAXIMUM_POLICY_PARAMETERS = 10_000 MAXIMUM_WARNINGS = 10_000 +# The most variables a request may list to calculate: as many as one entity +# may carry. +MAXIMUM_LISTED_VARIABLES = MAXIMUM_VARIABLES_PER_ENTITY EntityKey = Annotated[str, Field(min_length=1, max_length=255)] EntityPlural = Annotated[str, Field(min_length=1, max_length=255)] @@ -215,6 +220,35 @@ def _require_unique_members(members: tuple[str, ...]) -> tuple[str, ...]: ] +def _require_distinct_variables(names: tuple[str, ...]) -> tuple[str, ...]: + if len(set(names)) != len(names): + msg = "listed variables must be distinct" + raise ValueError(msg) + return names + + +# The variables a request lists to calculate, each named once. +ListedVariables = Annotated[ + tuple[VariableName, ...], + Field(max_length=MAXIMUM_LISTED_VARIABLES), + AfterValidator(_require_distinct_variables), +] + + +def refuse_listed_variables_with_every_variable( + listed: tuple[str, ...] | None, *, add_missing_variables: object +) -> tuple[str, ...] | None: + """Refuse a list of variables beside ``add_missing_variables``. + + ``add_missing_variables`` adds every variable, so a list beside it would + limit nothing. Raise ValueError when both are given. + """ + if listed is not None and add_missing_variables is True: + msg = "list the variables to calculate or set add_missing_variables, not both" + raise ValueError(msg) + return listed + + class HouseholdGroup(CallerOrderedModel): """One group entity instance, such as a household or a tax unit. @@ -458,7 +492,14 @@ class HouseholdExecutionRequest(StrictHouseholdModel): the household's entities lack, for ``year``, before calculating, as the Public API's ``/calculate-full`` route does (that route takes its year from the first age period of a person named ``you``, or else the current year, - and v2 households name people by record ID). ``spm`` carries the caller's + and v2 households name people by record ID). ``variables`` instead lists + the variables to calculate, each once: each is added as null for ``year`` + to every member of its entity with no value for it in ``year``, inputs + included, so it is calculated; every value the household gives is kept. + A name the country model lacks is reported as an unrecognized input. A + request gives at most one of the two; one without ``variables`` leaves + the field out, so household functions deployed before it still take the + request. ``spm`` carries the caller's SPM settings exactly as sent, as any JSON value, and the household function checks them with the Public API's SPM error codes: settings for a country other than the US are unsupported, and for the US an explicit null @@ -498,18 +539,36 @@ class HouseholdExecutionRequest(StrictHouseholdModel): household: HouseholdDocument policy: HouseholdPolicy add_missing_variables: bool = False + # Declared after add_missing_variables: its validator reads that value. + variables: ListedVariables | None = None spm: JsonValue = None spm_selection_source: Literal["request", "saved_household"] = "request" bundle: HouseholdBundleProvenance + @field_validator("variables") + @classmethod + def refuse_variables_with_every_variable( + cls, listed: tuple[str, ...] | None, info: ValidationInfo + ) -> tuple[str, ...] | None: + """Refuse ``variables`` beside ``add_missing_variables``.""" + return refuse_listed_variables_with_every_variable( + listed, add_missing_variables=info.data.get("add_missing_variables") + ) + @model_serializer(mode="wrap") def serialize_request( self, handler: SerializerFunctionWrapHandler ) -> dict[str, Any]: - """Leave out ``spm`` when the caller sent none, so omission is kept.""" + """Leave out ``spm`` and ``variables`` when the caller sent none. + + Omitted SPM settings inherit the defaults, and household functions + deployed before ``variables`` refuse the field. + """ dumped: dict[str, Any] = handler(self) if not self.spm_requested: dumped.pop("spm", None) + if self.variables is None: + dumped.pop("variables", None) return dumped @property @@ -544,7 +603,8 @@ class HouseholdInputError(StrictHouseholdModel): Field names and messages match the entries of the Public API's ``errors`` list, which name entity plurals only for a variable placed on the wrong - entity. + entity. A listed variable the model lacks is a ``household_variable`` at + ``variables[]``; API v1's own routes take no such list. """ type: InputErrorType @@ -570,8 +630,9 @@ class HouseholdCalculationError(StrictHouseholdModel): """Why a household calculation failed. ``message`` is worded as the Public API words the matching error response. - ``input_errors`` lists unrecognized names for ``invalid_inputs``, the - household's then the policy's; ``spm_error`` holds the SPM error code for + ``input_errors`` lists unrecognized names for ``invalid_inputs``: the + household's, then the listed variables', then the policy's; ``spm_error`` + holds the SPM error code for ``invalid_spm_selection``. """ diff --git a/libs/policyengine-simulation-contract/tests/test_household_execution.py b/libs/policyengine-simulation-contract/tests/test_household_execution.py index 7efdf7f24..bfb737d1e 100644 --- a/libs/policyengine-simulation-contract/tests/test_household_execution.py +++ b/libs/policyengine-simulation-contract/tests/test_household_execution.py @@ -305,6 +305,53 @@ def test_add_missing_variables_asks_for_a_full_calculation() -> None: assert _request(add_missing_variables=True).add_missing_variables is True +def test_a_request_may_list_the_variables_to_calculate() -> None: + listed = ["household_net_income", "employment_income"] + + request = _request(variables=listed) + + assert request.variables == tuple(listed) + dumped = request.model_dump(mode="json") + assert dumped["variables"] == listed + assert HouseholdExecutionRequest.model_validate(dumped) == request + # An empty list adds no variable, and is still sent. + assert _request(variables=[]).model_dump(mode="json")["variables"] == [] + + +def test_a_request_without_listed_variables_leaves_the_field_out() -> None: + # Household functions deployed before the field refuse it, so a request + # that lists none still reaches them. + unlisted = _request(variables=None) + + assert unlisted.variables is None + assert "variables" not in unlisted.model_dump(mode="json") + assert "variables" not in _request().model_dump(mode="json") + + +def test_listed_variables_are_distinct_and_at_most_ten_thousand() -> None: + most_names = [f"variable_{index}" for index in range(10_000)] + + with pytest.raises(ValidationError, match="distinct"): + _request(variables=["employment_income", "employment_income"]) + with pytest.raises(ValidationError, match="at most 10000 items"): + _request(variables=[*most_names, "one_too_many"]) + with pytest.raises(ValidationError, match="at least 1 character"): + _request(variables=[""]) + assert len(_request(variables=most_names).variables or ()) == 10_000 + + +def test_listed_variables_are_refused_with_add_missing_variables() -> None: + # add_missing_variables adds every variable, so a list beside it would + # limit nothing. + with pytest.raises(ValidationError) as refused: + _request(variables=["household_net_income"], add_missing_variables=True) + + (error,) = refused.value.errors() + assert error["loc"] == ("variables",) + assert "add_missing_variables" in error["msg"] + assert _request(variables=None, add_missing_variables=True).add_missing_variables + + def test_a_request_names_exactly_one_policy() -> None: # A baseline and its reform are two requests; a policy has no name. values = _request().model_dump(mode="json") diff --git a/projects/policyengine-simulation-entry/README.md b/projects/policyengine-simulation-entry/README.md index bbb29b7a8..7d134d6c9 100644 --- a/projects/policyengine-simulation-entry/README.md +++ b/projects/policyengine-simulation-entry/README.md @@ -80,9 +80,10 @@ setup required before enforcement is described in `DEPLOYMENT.md`. `POST /household-calculations` names a stored household, and optionally a stored policy and a stored dynamic, of API v1: `country`, `household_id`, -`policy_id`, `dynamic_id`, `add_missing_variables`, `axes` (within the -household contract's limits) and `spm` (SPM settings as an object; omit it -to use the household's saved selection, since null is refused). The service +`policy_id`, `dynamic_id`, `add_missing_variables`, `variables`, `axes` +(within the household contract's limits) and `spm` (SPM settings as an +object; omit it to use the household's saved selection, since null is +refused). The service reads the rows itself, applies the dynamic's values with the policy's, as an economy simulation does, stores the dynamic in `household_jobs.dynamic_id`, calculates the household's `default_year` on the v2 version manifest's @@ -97,8 +98,8 @@ The same route also takes a household given in the request instead of a stored one, as API v1's `/{country}/calculate` takes it: `country`, `household` (the situation), `policy` (parameter values by period; omit it or send null for current law), `year` (required), `add_missing_variables`, -`axes` (here or inside `household`, not both) and `spm` (omit it to use the -bundle's defaults). The body's kind is told by which of `household_id` and +`variables`, `axes` (here or inside `household`, not both) and `spm` (omit +it to use the bundle's defaults). The body's kind is told by which of `household_id` and `household` it has; a body with both is refused (`household_given_twice`), and one with neither as missing `household_id`, as before. The service reads only the catalog version, checks the request against the household @@ -112,6 +113,21 @@ situation as sent, with axes given beside it added. Each deployment from more than ten minutes earlier and whose versions are not those of the household function the v2 default now runs. +Both kinds of body may list the variables to calculate in `variables`, +instead of asking for every variable with `add_missing_variables`. A body +with both is refused with 422 at `variables`, as is a list naming a variable +twice or more than 10,000 names. The household function adds each listed +variable as null for the calculation year to every member of its entity +that has no value for it in that year, input variables included, so it is +calculated; every value the household gives is kept. A listed variable whose +entity collection the household lacks gets no value. With axes every +variable in the household is calculated at every point, as before. A listed +name the country model lacks fails the job as an unrecognized input at +`variables[]`. The job keeps the list in `request_data`. A body +without `variables` calculates as before, and the household function's +request then leaves the field out, so a household function deployed before +it still takes the request. + A submission is refused before anything is written: with 400 and a `code` when the household, policy, dynamic or catalog version for the default worker's .py version is missing (a dynamic of another country is diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_api_models.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_api_models.py index ec6cd7aa2..3707b74c1 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_api_models.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_api_models.py @@ -17,7 +17,11 @@ from typing import Annotated, Any, Literal from uuid import UUID -from policyengine_simulation_contract.household_execution import Axes +from policyengine_simulation_contract.household_execution import ( + Axes, + ListedVariables, + refuse_listed_variables_with_every_variable, +) from policyengine_simulation_contract.stage12_bundle import CountryId from policyengine_simulation_persistence import LATEST_YEAR, HouseholdJobStatus from pydantic import ( @@ -27,6 +31,7 @@ Field, JsonValue, Tag, + ValidationInfo, field_validator, ) from pydantic.json_schema import SkipJsonSchema @@ -88,6 +93,25 @@ def _refuse_null_spm(value: object) -> object: return value +_LISTED_VARIABLES_DESCRIPTION = ( + "The variables to calculate, each named once: each is added for the " + "calculation year wherever the household has no value for it in that " + "year, and calculated; every value the household gives is kept. Without " + "it, the household's own null values are calculated, or every variable " + "with add_missing_variables, which can't be sent with it. With axes, " + "every variable in the household is calculated at every point." +) + + +def _refuse_variables_with_every_variable( + listed: tuple[str, ...] | None, info: ValidationInfo +) -> tuple[str, ...] | None: + """Refuse ``variables`` beside ``add_missing_variables``, located at the list.""" + return refuse_listed_variables_with_every_variable( + listed, add_missing_variables=info.data.get("add_missing_variables") + ) + + class HouseholdCalculationRequest(BaseModel): """A stored household to calculate under one stored policy, or current law. @@ -99,9 +123,11 @@ class HouseholdCalculationRequest(BaseModel): neither may set a parameter the other sets. The calculation is for the household's ``default_year``, on the v2 version manifest's default worker. ``add_missing_variables`` adds every yearly, monthly and eternal variable - the household lacks, as the Public API's ``/calculate-full`` does. - ``axes`` vary the stored household's inputs across points, within the - household contract's limits. + the household lacks, as the Public API's ``/calculate-full`` does; + ``variables`` instead lists the variables to calculate, each wherever the + household has no value for it in that year. A request gives at most one + of the two. ``axes`` vary the stored household's inputs across points, + within the household contract's limits. ``spm`` holds SPM settings as an object, which the household function checks with the Public API's SPM error codes. Omit it to use the @@ -116,6 +142,10 @@ class HouseholdCalculationRequest(BaseModel): policy_id: UUID | None = None dynamic_id: UUID | None = None add_missing_variables: bool = False + # Declared after add_missing_variables: its validator reads that value. + variables: ListedVariables | None = Field( + default=None, description=_LISTED_VARIABLES_DESCRIPTION + ) axes: Axes = None spm: dict[str, JsonValue] | SkipJsonSchema[None] = Field( default=None, @@ -127,6 +157,14 @@ class HouseholdCalculationRequest(BaseModel): json_schema_extra=_omit_spm_default, ) + @field_validator("variables") + @classmethod + def refuse_variables_with_every_variable( + cls, listed: tuple[str, ...] | None, info: ValidationInfo + ) -> tuple[str, ...] | None: + """Refuse ``variables`` beside ``add_missing_variables``.""" + return _refuse_variables_with_every_variable(listed, info) + @field_validator("spm", mode="before") @classmethod def refuse_null_spm(cls, value: object) -> object: @@ -154,9 +192,10 @@ class InlineHouseholdCalculationRequest(BaseModel): job names no household, policy or dynamic. ``year`` is the calculation year: the period of the variables - ``add_missing_variables`` adds, and of any value or axis the household - gives without a period. ``axes`` may be given here or inside - ``household``, not in both. ``spm`` holds SPM settings as an object; + ``add_missing_variables`` adds, or ``variables`` lists, and of any value + or axis the household gives without a period. A request gives at most one + of ``add_missing_variables`` and ``variables``. ``axes`` may be given here + or inside ``household``, not in both. ``spm`` holds SPM settings as an object; omit it to use the bundle's certified defaults; an explicit null is refused. """ @@ -186,6 +225,10 @@ class InlineHouseholdCalculationRequest(BaseModel): ), ) add_missing_variables: bool = False + # Declared after add_missing_variables: its validator reads that value. + variables: ListedVariables | None = Field( + default=None, description=_LISTED_VARIABLES_DESCRIPTION + ) axes: Axes = None spm: dict[str, JsonValue] | SkipJsonSchema[None] = Field( default=None, @@ -196,6 +239,14 @@ class InlineHouseholdCalculationRequest(BaseModel): json_schema_extra=_omit_spm_default, ) + @field_validator("variables") + @classmethod + def refuse_variables_with_every_variable( + cls, listed: tuple[str, ...] | None, info: ValidationInfo + ) -> tuple[str, ...] | None: + """Refuse ``variables`` beside ``add_missing_variables``.""" + return _refuse_variables_with_every_variable(listed, info) + @field_validator("spm", mode="before") @classmethod def refuse_null_spm(cls, value: object) -> object: diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_contract_fields.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_contract_fields.py index a558afda6..160cbb2e2 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_contract_fields.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_contract_fields.py @@ -29,6 +29,7 @@ "year": "household_id", "country": "country", "add_missing_variables": "add_missing_variables", + "variables": "variables", **dict.fromkeys(POLICY_FIELDS, "policy_id"), } # The field of a request giving its household that each of the contract @@ -39,6 +40,7 @@ "year": "year", "country": "country", "add_missing_variables": "add_missing_variables", + "variables": "variables", "spm": "spm", } diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_job_preparation.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_job_preparation.py index b9c65e5cc..37a46b904 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_job_preparation.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/household_job_preparation.py @@ -197,6 +197,7 @@ def prepare_household_job( ), **job_policy_fields(reform=inputs.reform.values), "add_missing_variables": request.add_missing_variables, + "variables": request.variables, "bundle": worker.bundle, **_spm_fields(request, household.document), } @@ -302,6 +303,7 @@ def prepare_inline_household_job( "household": household_sent, **job_policy_fields(reform=request.policy or {}), "add_missing_variables": request.add_missing_variables, + "variables": request.variables, "bundle": worker.bundle, # No household is stored, so no saved selection applies. **( diff --git a/projects/policyengine-simulation-entry/tests/test_household_calculations.py b/projects/policyengine-simulation-entry/tests/test_household_calculations.py index 30c661ef2..dd5128587 100644 --- a/projects/policyengine-simulation-entry/tests/test_household_calculations.py +++ b/projects/policyengine-simulation-entry/tests/test_household_calculations.py @@ -445,6 +445,24 @@ async def test_without_axes_the_household_has_none(): assert "axes" not in store.created[0].request_data +LISTED_VARIABLES = ["household_net_income", "employment_income"] + + +@pytest.mark.asyncio +async def test_a_stored_households_listed_variables_reach_its_function_and_job(): + """The household function calculates them; the job keeps them as sent.""" + service, store, _, caller = _service() + + await service.submit( + _request(variables=LISTED_VARIABLES), observability_context=None + ) + + payload = caller.calls[0]["payload"] + assert payload["variables"] == LISTED_VARIABLES + assert payload["add_missing_variables"] is False + assert store.created[0].request_data["variables"] == LISTED_VARIABLES + + @pytest.mark.parametrize( "axes", [ @@ -1073,6 +1091,32 @@ async def test_axes_given_on_the_request_join_the_inline_situation(): assert job.request_data["axes"] == axes +@pytest.mark.asyncio +async def test_an_inline_households_listed_variables_reach_its_function_and_job(): + """The job keeps the list with the options, apart from the situation.""" + service, store, _, caller = _service() + + await service.submit( + _inline_request(variables=LISTED_VARIABLES), observability_context=None + ) + + payload = caller.calls[0]["payload"] + assert payload["variables"] == LISTED_VARIABLES + assert payload["household"] == SITUATION + (job,) = store.created + assert job.request_data == { + "country": "us", + "year": 2026, + "variables": LISTED_VARIABLES, + } + + +@pytest.mark.parametrize("build_request", [_request, _inline_request]) +def test_listed_variables_with_add_missing_variables_are_refused(build_request): + with pytest.raises(ValidationError, match="add_missing_variables"): + build_request(variables=LISTED_VARIABLES, add_missing_variables=True) + + @pytest.mark.asyncio async def test_axes_given_both_in_the_situation_and_on_the_request_are_refused(): axes = [[{"name": "employment_income", "count": 5, "min": 0, "max": 80_000}]] diff --git a/projects/policyengine-simulation-entry/tests/test_household_contract_fields.py b/projects/policyengine-simulation-entry/tests/test_household_contract_fields.py index 743129ea3..fc3054d0b 100644 --- a/projects/policyengine-simulation-entry/tests/test_household_contract_fields.py +++ b/projects/policyengine-simulation-entry/tests/test_household_contract_fields.py @@ -3,7 +3,10 @@ from __future__ import annotations import pytest -from policyengine_simulation_entry.household_contract_fields import request_field_of +from policyengine_simulation_entry.household_contract_fields import ( + inline_request_location, + request_field_of, +) DYNAMIC_PARAMETER = "gov.simulation.labor_supply_responses.elasticities.income" @@ -27,6 +30,8 @@ (("spm",), False, "household_id"), (("country",), False, "country"), (("add_missing_variables",), False, "add_missing_variables"), + (("variables",), False, "variables"), + (("variables", 2), False, "variables"), # The service builds these itself; no request field is to blame. (("bundle", "core_package_version"), False, None), (("calculation_id",), False, None), @@ -71,3 +76,18 @@ def test_a_refused_value_of_the_dynamics_parameter_traces_to_the_dynamic( ) == request_field ) + + +@pytest.mark.parametrize( + ("location", "request_location"), + [ + (("variables",), ("body", "variables")), + (("variables", 2), ("body", "variables", 2)), + ], +) +def test_a_refused_variable_list_is_located_at_the_inline_bodys_variables( + location, request_location +): + assert ( + inline_request_location(location, axes_from_request=False) == request_location + ) diff --git a/projects/policyengine-simulation-entry/tests/test_household_routes.py b/projects/policyengine-simulation-entry/tests/test_household_routes.py index 53fbeefae..6e876a817 100644 --- a/projects/policyengine-simulation-entry/tests/test_household_routes.py +++ b/projects/policyengine-simulation-entry/tests/test_household_routes.py @@ -261,6 +261,22 @@ def test_an_inline_household_is_submitted_on_the_same_route(client_for): assert request.model_dump(mode="json")["axes"] == axes +@pytest.mark.parametrize("body", [SUBMISSION, INLINE_SUBMISSION]) +def test_either_body_may_list_the_variables_to_calculate(client_for, body): + calculations = FakeHouseholdCalculations() + listed = ["household_net_income", "employment_income"] + + with client_for(calculations) as client: + result = client.post( + "/household-calculations", json={**body, "variables": listed} + ) + + assert result.status_code == 202 + ((request, _),) = calculations.submissions + assert request.variables == tuple(listed) + assert request.add_missing_variables is False + + def test_a_body_naming_a_stored_household_is_read_as_before(client_for): calculations = FakeHouseholdCalculations() @@ -321,6 +337,26 @@ def test_a_body_naming_a_stored_household_is_read_as_before(client_for): {**SUBMISSION, "household_id": "not-a-uuid"}, {"type": "uuid_parsing", "loc": ["body", "household_id"]}, ), + # A list of variables names each variable once, and never comes with + # add_missing_variables, which adds every variable. + *( + ( + {**body, "variables": ["employment_income", "employment_income"]}, + {"type": "value_error", "loc": ["body", "variables"]}, + ) + for body in (SUBMISSION, INLINE_SUBMISSION) + ), + *( + ( + { + **body, + "variables": ["household_net_income"], + "add_missing_variables": True, + }, + {"type": "value_error", "loc": ["body", "variables"]}, + ) + for body in (SUBMISSION, INLINE_SUBMISSION) + ), # A body that is not an object is refused at the body, as before. *( ( diff --git a/projects/policyengine-simulation-entry/tests/test_openapi.py b/projects/policyengine-simulation-entry/tests/test_openapi.py index 2881d1320..679b9ab6c 100644 --- a/projects/policyengine-simulation-entry/tests/test_openapi.py +++ b/projects/policyengine-simulation-entry/tests/test_openapi.py @@ -373,6 +373,7 @@ def test_a_household_calculation_request_names_its_fields_only(): "policy_id", "dynamic_id", "add_missing_variables", + "variables", "axes", "spm", } @@ -411,10 +412,17 @@ def test_a_household_calculation_takes_a_stored_or_an_inline_household(): "policy", "year", "add_missing_variables", + "variables", "axes", "spm", } assert set(inline["required"]) == {"country", "household", "year"} + # Both bodies may list the variables to calculate. + for name in ("HouseholdCalculationRequest", "InlineHouseholdCalculationRequest"): + (listed, *_) = schemas[name]["properties"]["variables"]["anyOf"] + assert listed["type"] == "array" + assert listed["items"]["type"] == "string" + assert listed["maxItems"] == 10_000 assert inline["additionalProperties"] is False assert inline["properties"]["household"]["type"] == "object" year = inline["properties"]["year"] diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/household_calculation.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/household_calculation.py index 4540a6601..2dd053184 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/household_calculation.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/household_calculation.py @@ -22,6 +22,11 @@ adds them for the first period of the age of a person named ``you``, or else its host's current year (and fails with an internal error when that age is one value, not by period); v2 households name people by record ID. +- A request may list the variables to calculate (``variables``), which + API v1's routes cannot: each is added as null for ``year`` to every + member of its entity without a value for that year, and a name the country + model lacks is an unrecognized input at its place in the list, after the + household's own and before the policy's. - A variable given as one value, not by period, is that value for ``year``, and an axis without a period varies ``year``; the calculated household shows both with that period. The Public API leaves them to the country @@ -75,10 +80,12 @@ from policyengine_simulation_executor.household_inputs import ( HouseholdModelMetadata, RequestedValue, + add_listed_variables, add_missing_variables, assign_request_year, drop_deprecated_inputs, find_unrecognized_household_inputs, + find_unrecognized_listed_variables, find_unrecognized_policy_inputs, requested_computations, unrecognized_inputs_message, @@ -565,21 +572,27 @@ def _prepared_household( ) -> _PreparedHousehold: """Prepare the household as the Public API does; raise for unknown names. - Unknown household names are listed first, then the policy's unknown - parameters, as the Public API lists them. + Missing variables are added for the request's year: every variable with + ``add_missing_variables``, or only those ``variables`` lists. Unknown + household names are listed first, then listed variables the model lacks, + then the policy's unknown parameters, as API v1 lists the first and + last. """ situation = request.household.to_situation() assign_request_year(situation, year=request.year) + listed = request.variables or () if request.add_missing_variables: add_missing_variables(situation, model.metadata, year=request.year) + add_listed_variables(situation, model.metadata, listed, year=request.year) deprecated = drop_deprecated_inputs(situation) household_errors = find_unrecognized_household_inputs( deprecated.household, model.metadata ) + listed_errors = find_unrecognized_listed_variables(listed, model.metadata) policy_errors = find_unrecognized_policy_inputs( request.policy.parameters, model.metadata ) - input_errors = (*household_errors, *policy_errors) + input_errors = (*household_errors, *listed_errors, *policy_errors) if input_errors: raise _CalculationFailedError( HouseholdCalculationError( diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/household_inputs.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/household_inputs.py index 67de12a67..550edf903 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/household_inputs.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/household_inputs.py @@ -11,7 +11,9 @@ added for that year, where the Public API infers one, and ``assign_request_year`` puts values and axes the household gives without a period in that year, where the Public API leaves them to the country model's -own default year. +own default year. A v2 request may also list the variables to calculate, +which API v1's routes cannot: ``add_listed_variables`` adds only those, and +``find_unrecognized_listed_variables`` reports the names the model lacks. """ from __future__ import annotations @@ -194,6 +196,43 @@ def add_missing_variables( } +def add_listed_variables( + situation: dict[str, Any], + metadata: HouseholdModelMetadata, + names: Iterable[str], + *, + year: str, +) -> None: + """Add each listed variable, as None for ``year`` where it has no value, in place. + + Every member of the variable's entity without a value for it in ``year`` + gets None for that year, which requests it, input variables included; any + value the household gives, for ``year`` or another period, is kept. Names + the country model lacks are left out here and reported by + ``find_unrecognized_listed_variables``. + """ + for name in names: + variable = metadata.variables.get(name) + if variable is None: + continue + entity_plural = metadata.entities[variable.entity].plural + for entity in situation.get(entity_plural, {}).values(): + periods = entity.setdefault(name, {}) + if isinstance(periods, dict): + periods.setdefault(year, None) + + +def find_unrecognized_listed_variables( + names: Iterable[str], metadata: HouseholdModelMetadata +) -> list[HouseholdInputError]: + """Find the listed variables the country model lacks, at their list positions.""" + return [ + _input_error("household_variable", name, f"variables[{index}]") + for index, name in enumerate(names) + if name not in metadata.variables + ] + + @dataclass(frozen=True) class DeprecatedVariableWarning: """A removed or renamed variable was supplied and dropped before calculation.""" diff --git a/projects/policyengine-simulation-executor/tests/test_household_calculation.py b/projects/policyengine-simulation-executor/tests/test_household_calculation.py index a1eac8bb9..98ba3011f 100644 --- a/projects/policyengine-simulation-executor/tests/test_household_calculation.py +++ b/projects/policyengine-simulation-executor/tests/test_household_calculation.py @@ -596,6 +596,96 @@ def test_unrecognized_inputs_are_listed_in_the_order_the_household_was_sent() -> ) +def test_listed_variables_are_added_where_their_entity_lacks_the_years_value() -> None: + # Each listed variable is added as null for the request's year to every + # member of its entity without a value for that year, input variables + # (age) included; values the household gives, for any year, are kept. + # Variables not listed are not added. + created: list[dict] = [] + + class RecordingSimulation( + _stand_in_simulation({"age": np.array([30, 41]), "net_income": np.array([1.5])}) + ): + def __init__(self, **options: object) -> None: + super().__init__(**options) + created.append(self.situation) + + household = { + "people": {"you": {"age": {"2026": 30}}, "partner": {"age": {"2025": 40}}}, + "households": {"home": {"members": ["you", "partner"]}}, + } + + outcome = _calculate_with_stand_in( + RecordingSimulation, household, variables=["age", "net_income"] + ) + + assert isinstance(outcome, HouseholdExecutionResult), outcome + assert created[0]["people"] == { + "you": {"age": {"2026": 30}}, + "partner": {"age": {"2025": 40, "2026": None}}, + } + assert created[0]["households"]["home"] == { + "members": ["you", "partner"], + "net_income": {"2026": None}, + } + situation = outcome.output.household.to_situation() + assert situation["people"]["you"]["age"] == {"2026": 30} + assert situation["people"]["partner"]["age"] == {"2025": 40, "2026": 41} + assert situation["households"]["home"]["net_income"] == {"2026": 1.5} + + +def test_with_axes_listed_variables_are_calculated_at_every_point() -> None: + household = { + "people": {"you": {"age": {"2026": 30}}}, + "households": {"home": {"members": ["you"]}}, + "axes": [[{"name": "age", "count": 3, "min": 0, "max": 2}]], + } + + outcome = _calculate_with_stand_in( + _stand_in_simulation( + {"age": np.array([0, 1, 2]), "net_income": np.array([1.0, 2.0, 3.0])}, + axis_points=3, + ), + household, + variables=["net_income"], + ) + + assert isinstance(outcome, HouseholdExecutionResult), outcome + situation = outcome.output.household.to_situation() + assert situation["people"]["you"]["age"] == {"2026": [0, 1, 2]} + assert situation["households"]["home"] == { + "members": ["you"], + "net_income": {"2026": [1.0, 2.0, 3.0]}, + } + + +def test_listed_variables_the_model_lacks_fail_with_the_households_inputs() -> None: + # Listed after the household's own unrecognized inputs and before the + # policy's, each at its place in the list. + household = { + "people": {"you": {"age": {"2026": 30}, "not_a_variable": {"2026": 1}}}, + "households": {"home": {"members": ["you"]}}, + } + + outcome = _calculate_with_stand_in( + _stand_in_simulation({}), + household, + variables=["net_income", "not_listed_anywhere", "age"], + policy={"parameters": {"gov.not_a_parameter": {"2026-01-01.2100-12-31": 1}}}, + ) + + assert isinstance(outcome, HouseholdExecutionFailure) + assert outcome.error.code == "invalid_inputs" + assert [(error.type, error.path) for error in outcome.error.input_errors] == [ + ("household_variable", "household.people.you.not_a_variable"), + ("household_variable", "variables[1]"), + ("policy_parameter", "policy.gov.not_a_parameter"), + ] + assert outcome.error.input_errors[1].message == ( + "Unrecognized household variable `not_listed_anywhere` at `variables[1]`." + ) + + def test_a_request_for_another_bundle_is_refused() -> None: bundle = installed_household_bundle("uk").model_copy( update={"policyengine_version": "0.0.1"} @@ -775,6 +865,34 @@ def test_us_calculate_full_adds_and_calculates_every_missing_variable() -> None: ) +def test_us_listed_variables_are_the_only_ones_added_and_calculated() -> None: + outcome = calculate_household( + _request( + "us", + US_FAMILY, + variables=["household_net_income", "employment_income", "eitc"], + ), + worker=_worker("us"), + dependencies=HouseholdCalculationDependencies(), + ) + + assert isinstance(outcome, HouseholdExecutionResult), outcome + situation = outcome.output.household.to_situation() + you = situation["people"]["you"] + dependent = situation["people"]["your first dependent"] + tax_unit = situation["tax_units"]["your tax unit"] + # The earnings the household gives are kept; the dependent's are calculated. + assert you == {"age": {"2026": 35}, "employment_income": {"2026": 30_000}} + assert dependent == {"age": {"2026": 5}, "employment_income": {"2026": 0.0}} + assert set(tax_unit) == {"members", "ctc", "eitc"} + assert isinstance(tax_unit["eitc"]["2026"], float) + assert isinstance(tax_unit["ctc"]["2026"], float) + assert isinstance( + situation["households"]["your household"]["household_net_income"]["2026"], + float, + ) + + US_SINGLE_WITHOUT_COUNTY = { "people": {"you": {"age": {"2026": 35}, "employment_income": {"2026": 30_000}}}, "spm_units": {