Skip to content
Merged
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 /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`.
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@
JsonValue,
PrivateAttr,
TypeAdapter,
ValidationInfo,
field_validator,
model_serializer,
model_validator,
)
Expand Down Expand Up @@ -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)]
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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[<index>]``; API v1's own routes take no such list.
"""

type: InputErrorType
Expand All @@ -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``.
"""

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
26 changes: 21 additions & 5 deletions projects/policyengine-simulation-entry/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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[<index>]`. 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -27,6 +31,7 @@
Field,
JsonValue,
Tag,
ValidationInfo,
field_validator,
)
from pydantic.json_schema import SkipJsonSchema
Expand Down Expand Up @@ -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.

Expand All @@ -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
Expand All @@ -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,
Expand All @@ -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:
Expand Down Expand Up @@ -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.
"""
Expand Down Expand Up @@ -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,
Expand All @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -39,6 +40,7 @@
"year": "year",
"country": "country",
"add_missing_variables": "add_missing_variables",
"variables": "variables",
"spm": "spm",
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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),
}
Expand Down Expand Up @@ -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.
**(
Expand Down
Loading