Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/household-calculation-variables.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`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.
36 changes: 27 additions & 9 deletions docs/migration/stage-11-v2-households.md
Original file line number Diff line number Diff line change
Expand Up @@ -303,10 +303,17 @@ 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
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:
`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 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:

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
Expand All @@ -316,9 +323,16 @@ 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 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.

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.
Expand All @@ -327,7 +341,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
Expand All @@ -349,11 +363,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
Expand All @@ -367,7 +384,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
Expand Down
1 change: 1 addition & 0 deletions policyengine_api/fastapi_routes/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
)


Expand Down
21 changes: 21 additions & 0 deletions policyengine_api/fastapi_routes/v2/errors_support.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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")


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,15 @@ 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 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.
"""

Expand All @@ -60,8 +67,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.
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from policyengine_api.fastapi_routes.v2.errors_support import (
V2ErrorResponse,
V2MissingParametersErrorResponse,
V2UnknownVariablesErrorResponse,
)

if TYPE_CHECKING:
Expand Down Expand Up @@ -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 "
Expand All @@ -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."
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -48,6 +49,7 @@
HouseholdCalculationNotFoundError,
HouseholdCalculationResultUnreadableError,
HouseholdCalculationStorageError,
HouseholdCalculationVariablesUnknownError,
HouseholdCalculationYearError,
InlinePolicyParametersMissingError,
)
Expand Down Expand Up @@ -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)
Expand Down
27 changes: 15 additions & 12 deletions policyengine_api/libs/simulation_household_calculations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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):
Expand All @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
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:
Expand Down
Loading
Loading