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-dynamics.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`/v2/household-calculations` and household reports on `/v2/reports` take an optional `dynamic_id` (each report side its own), checked as economy reports check one: 404 when the request's country does not store it, and 422 `missing_parameters` for parameters the running catalog version lacks. API v1 sends a named dynamic to the simulation service, which applies it, and household calculations answer the `dynamic_id` they apply.
4 changes: 2 additions & 2 deletions docs/engineering/migration-contracts.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,8 @@ Generated from `policyengine_api/migration_registry.py` and `tests/contract/regi

| Method | Path | Status | Route group | Required headers | Stable response fields |
| --- | --- | ---: | --- | --- | --- |
| `POST` | `/v2/household-calculations` | 202 | `household` | none | `status`, `message`, `result.item.calculation_id`, `result.item.status`, `result.item.country_id`, `result.item.household_id`, `result.item.policy_id`, `result.item.year` |
| `GET` | `/v2/household-calculations/{calculation_id}` | 200 | `household` | none | `status`, `message`, `result.item.calculation_id`, `result.item.country_id`, `result.item.household_id`, `result.item.policy_id`, `result.item.year`, `result.item.catalog_version_id`, `result.item.country_package_version`, `result.item.policyengine_version`, `result.item.status`, `result.item.created_at`, `result.item.started_at`, `result.item.completed_at`, `result.item.result`, `result.item.error` |
| `POST` | `/v2/household-calculations` | 202 | `household` | none | `status`, `message`, `result.item.calculation_id`, `result.item.status`, `result.item.country_id`, `result.item.household_id`, `result.item.policy_id`, `result.item.dynamic_id`, `result.item.year` |
| `GET` | `/v2/household-calculations/{calculation_id}` | 200 | `household` | none | `status`, `message`, `result.item.calculation_id`, `result.item.country_id`, `result.item.household_id`, `result.item.policy_id`, `result.item.dynamic_id`, `result.item.year`, `result.item.catalog_version_id`, `result.item.country_package_version`, `result.item.policyengine_version`, `result.item.status`, `result.item.created_at`, `result.item.started_at`, `result.item.completed_at`, `result.item.result`, `result.item.error` |

### `user_household_associations_v2`

Expand Down
2 changes: 2 additions & 0 deletions docs/generated/migration_contracts.json
Original file line number Diff line number Diff line change
Expand Up @@ -732,6 +732,7 @@
"result.item.country_id",
"result.item.household_id",
"result.item.policy_id",
"result.item.dynamic_id",
"result.item.year"
]
},
Expand All @@ -748,6 +749,7 @@
"result.item.country_id",
"result.item.household_id",
"result.item.policy_id",
"result.item.dynamic_id",
"result.item.year",
"result.item.catalog_version_id",
"result.item.country_package_version",
Expand Down
12 changes: 9 additions & 3 deletions policyengine_api/fastapi_routes/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@
)
from policyengine_api.readiness import is_ready
from policyengine_api.request_caller import current_request_caller
from policyengine_api.services.v2.household_calculations.types import (
HouseholdCalculationSources,
)
from policyengine_api.services.v2.metadata.process_state import (
SelectedCatalogStore,
)
Expand Down Expand Up @@ -224,9 +227,12 @@ def _default_v2_household_calculation_service_factory() -> (
)

return V2HouseholdCalculationService(
countries=_default_v2_country_service_factory(),
households=_default_v2_household_service_factory(),
policies=_default_v2_policy_service_factory(),
sources=HouseholdCalculationSources(
countries=_default_v2_country_service_factory(),
households=_default_v2_household_service_factory(),
policies=_default_v2_policy_service_factory(),
dynamics=_default_v2_dynamic_service_factory(),
),
database_session=HouseholdCalculationDatabaseSession(get_v2_session_factory()),
simulation_factory=process_simulation_household_calculation_client,
)
Expand Down
13 changes: 7 additions & 6 deletions policyengine_api/fastapi_routes/resource_service_protocols.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,12 +196,13 @@ def submit_calculation(
"""Send a stored household's calculation to the simulation service.

Raise ``HouseholdCalculationCountryError`` for a country without
household calculations, ``HouseholdNotFoundError`` or
``PolicyNotFoundError`` for a record not stored in that country,
``HouseholdCalculationYearError`` for a household without a default
year, ``PolicyParametersMissingError`` for a policy setting parameters
the running catalog version lacks, and the simulation service errors
when it refuses the calculation.
household calculations, ``HouseholdNotFoundError``,
``PolicyNotFoundError`` or ``DynamicNotFoundError`` for a record not
stored in that country, ``HouseholdCalculationYearError`` for a
household without a default year, ``PolicyParametersMissingError``
(``DynamicParametersMissingError`` for a dynamic) for one setting
parameters the running catalog version lacks, and the simulation
service errors when it refuses the calculation.
"""
...

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,16 @@
class HouseholdCalculationRequest(HouseholdCalculationInput):
"""A stored household to calculate under a stored policy, or current law.

``household_id`` and ``policy_id`` name records of ``country_id`` stored
through ``/v2/households`` and ``/v2/policies``; without ``policy_id`` the
household is calculated under current law, 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 submission starts a new calculation.
``household_id``, ``policy_id`` and ``dynamic_id`` name records of
``country_id`` stored through ``/v2/households``, ``/v2/policies`` and
``/v2/dynamics``; without ``policy_id`` the household is calculated under
current law, and without ``dynamic_id`` with no model assumptions beyond
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
submission starts a new calculation.
"""

def to_service_input(self) -> HouseholdCalculationInput:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,17 @@ class HouseholdCalculationSubmittedItem(StrictHouseholdCalculationAPIModel):
"""A calculation the simulation service accepted.

Poll ``GET /v2/household-calculations/{calculation_id}`` until ``status``
is ``succeeded`` or ``failed``. ``year`` is the household's default year,
which is calculated.
is ``succeeded`` or ``failed``. ``dynamic_id`` is the dynamic whose model
assumptions apply, null for none. ``year`` is the household's default
year, which is calculated.
"""

calculation_id: UUID
status: CalculationStatus
country_id: str
household_id: UUID
policy_id: UUID | None
dynamic_id: UUID | None
year: int

@classmethod
Expand Down Expand Up @@ -90,15 +92,17 @@ class HouseholdCalculationItem(StrictHouseholdCalculationAPIModel):
"""A household calculation and its outcome.

``status`` moves from ``pending`` through ``running`` to ``succeeded``,
with ``result``, or ``failed``, with ``error``. ``catalog_version_id``,
``country_package_version`` and ``policyengine_version`` are those the
calculation runs with.
with ``result``, or ``failed``, with ``error``. ``dynamic_id`` is the
dynamic whose model assumptions apply, null for none or once the dynamic
is deleted. ``catalog_version_id``, ``country_package_version`` and
``policyengine_version`` are those the calculation runs with.
"""

calculation_id: UUID
country_id: str
household_id: UUID
policy_id: UUID | None
dynamic_id: UUID | None
year: int
catalog_version_id: UUID
country_package_version: str
Expand Down Expand Up @@ -158,7 +162,10 @@ class HouseholdCalculationResponse(
HOUSEHOLD_CALCULATION_ERROR_RESPONSES: dict[int | str, dict[str, Any]] = {
404: {
"model": V2ErrorResponse,
"description": "The household, policy or calculation does not exist.",
"description": (
"The household, policy or dynamic a submission names is not stored "
"in its country, or the calculation does not exist."
),
},
422: {
"model": V2ErrorResponse,
Expand Down Expand Up @@ -199,9 +206,12 @@ class HouseholdCalculationResponse(
"description": (
"The request does not match the schema; the country does not offer "
"household calculations; the household has no default year; the "
"policy sets parameters the running catalog version does not have "
"(code missing_parameters, which names them); or the simulation "
"service refuses the caller's data, with its reason in the message."
"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 "
"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."
),
},
503: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

The calculation runs on the simulation service, which records it as a job in
``household_jobs``; the routes need no account. Submitting sends the
simulation service the stored household's and policy's IDs once the Public
API's own checks pass; reading reads the job from the database and never
simulation service the stored household's, policy's and dynamic's IDs once
API v1's own checks pass; reading reads the job from the database and never
calls the simulation service.
"""

Expand Down Expand Up @@ -39,6 +39,7 @@
)
from policyengine_api.observability.identifiers import OBSERVABILITY_ID_HEADER
from policyengine_api.request_context import current_observability_id
from policyengine_api.services.v2.dynamics.validators import DynamicNotFoundError
from policyengine_api.services.v2.household_calculations.validators import (
HouseholdCalculationCountryError,
HouseholdCalculationNotFoundError,
Expand Down Expand Up @@ -82,6 +83,7 @@
(
HouseholdNotFoundError,
PolicyNotFoundError,
DynamicNotFoundError,
HouseholdCalculationNotFoundError,
),
404,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -543,7 +543,7 @@ class ReportRunNotRecordedResponse(V2ErrorResponse):
"have (code missing_parameters, which names them; the policies are "
"checked before the dynamics, the baseline's first); or the "
"simulation service cannot run the report: its "
"422, or its 400 for a region or dataset it does not have. The "
"422, or its 400 for a region, dynamic or dataset it does not have. The "
"message says which; for the simulation service's refusal, it gives "
"the service's code, when it gave one, and its reason, but not its "
"status. A simulation service that doesn't calculate cliffs per "
Expand Down
59 changes: 41 additions & 18 deletions policyengine_api/libs/simulation_household_calculations.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@
ID headers, transport and instrumentation as every other simulation call.

The request names the country, the stored household and the stored policy
(null for current law), ``add_missing_variables``, and the axes and SPM
settings only when the caller gave them. The simulation service's answers
are read as follows.
(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. The simulation service's answers are read as follows.

The job was created:

Expand All @@ -21,7 +23,8 @@
(SimulationServiceUnavailableError, which the route answers 503):

- 400 when a household, policy or catalog version it names does not exist
(the Public API checks the first two first), with the service's reason;
(the Public API checks the first two first), with the service's reason,
unless its code names a row the caller chose (below);
- 401, 403, 404, 405, 413 and 429, which its authentication, routing,
body-size and rate limits answer before its route runs;
- its own 503, which names its code, when it is not configured, cannot read
Expand All @@ -33,10 +36,17 @@

The caller's data was refused:

- 422 with its reasons (a malformed request, or one its household contract
refuses), one per field as FastAPI writes them, which reach the caller as
SimulationServiceInvalidRequestError. A 422 of another shape is
unavailable.
- 422 with its reasons (a malformed request, one its household contract
refuses, a dynamic setting parameters its catalog version lacks, or a
parameter both the policy and the dynamic set, each located at
``dynamic_id``), one per field as FastAPI writes them, which reach the
caller as SimulationServiceInvalidRequestError. A 422 of another shape is
unavailable;
- 400 with a code in ``CALLER_ROW_REFUSAL_CODES`` and a readable reason,
as the report route's: ``unknown_dynamic`` for a dynamic the country does
not store (API v1 checks it first), which reaches the caller as
SimulationServiceInvalidRequestError with its code and reason, as on the
economy routes. One whose reason cannot be read is unavailable.

The job may exist, and no route finds a household job without its ID, so the
message asks the caller to submit the calculation again and says that this
Expand Down Expand Up @@ -95,6 +105,7 @@
from pydantic import ValidationError

from policyengine_api.libs.simulation_service_answers import (
CALLER_ROW_REFUSAL_CODES,
PROXY_STAND_IN_STATUSES,
AnswerModel,
Refusal,
Expand Down Expand Up @@ -184,17 +195,20 @@ def household_calculation_request(
) -> dict[str, Any]:
"""Return the simulation service's request body for the calculation.

``axes`` and ``spm`` are sent only when the caller gave them; each axis
and the SPM settings keep only the fields the caller gave.
``dynamic_id``, ``axes`` and ``spm`` are sent 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,
"household_id": str(calculation.household_id),
"policy_id": (
None if calculation.policy_id is None else str(calculation.policy_id)
),
"add_missing_variables": calculation.add_missing_variables,
}
if calculation.dynamic_id is not None:
body["dynamic_id"] = str(calculation.dynamic_id)
body["add_missing_variables"] = calculation.add_missing_variables
if calculation.axes is not None:
body["axes"] = [
[axis.model_dump(mode="json", exclude_unset=True) for axis in group]
Expand Down Expand Up @@ -229,10 +243,14 @@ def post_household_calculation(
return SimulationAnswer(status_code=response.status_code, content=response.content)


def _invalid_request_reason(refusal: Refusal) -> str:
"""Return the service's reason, or each refused field and why."""
def _invalid_request_reason(refusal: Refusal, code: str | None = None) -> str:
"""Return the service's reason, or each refused field and why.

``code`` is the service's code, named when given.
"""
named_code = "" if code is None else f" ({code})"
return (
"The simulation service cannot calculate this household: "
f"The simulation service cannot calculate this household{named_code}: "
f"{refusal_reason(refusal)}"
)

Expand Down Expand Up @@ -336,11 +354,12 @@ def submit(
"""Submit the calculation and return the job the service created.

Raise SimulationServiceInvalidRequestError with the service's reasons
when it refuses the caller's data (422);
when it refuses the caller's data (422, or 400 naming a row the
caller chose, such as ``unknown_dynamic``);
SimulationServiceUnavailableError when no job of the submission will
run (its 400, the statuses it answers before its route runs, its own
503, a connection never made or a gateway token that cannot be
fetched); SimulationServiceInternalError when it failed (500); and
run (any other 400, the statuses it answers before its route runs,
its own 503, a connection never made or a gateway token that cannot
be fetched); SimulationServiceInternalError when it failed (500); and
SimulationServiceAnswerUnreadableError when it accepted the
calculation but its answer cannot be read, it answered any other
status, its answer was lost after the submission may have reached it,
Expand Down Expand Up @@ -384,6 +403,10 @@ def _accepted_job(answer: SimulationAnswer) -> HouseholdCalculationAccepted:
_invalid_request_reason(read.refusal)
)
if read.status_code == HTTPStatus.BAD_REQUEST:
if read.refusal is not None and read.code in CALLER_ROW_REFUSAL_CODES:
raise SimulationServiceInvalidRequestError(
_invalid_request_reason(read.refusal, read.code)
)
raise SimulationServiceUnavailableError(_refused(read))
if read.status_code in STATUSES_AFTER_WHICH_NO_JOB_RUNS:
raise SimulationServiceUnavailableError(_unavailable(read))
Expand Down
30 changes: 21 additions & 9 deletions policyengine_api/libs/simulation_reports.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@
``POST /reports`` as ``report_type`` ``budget_window``, naming its first
year and ``budget_window_size`` in place of the year, and no
``include_cliffs``. A household report goes there too, as ``report_type``
``household``, naming the stored household, each simulation's policy (the
reform null for a report of the baseline alone), but no year: the
simulation service calculates the household's default year, adding every
variable the household lacks. None names a PolicyEngine.py version: the
simulation service runs its default worker's. None names a label or a
description, which belong to users' saved reports. The simulation service
answers:
``household``, naming the stored household, each simulation's policy, and
its dynamic only when it names one (the reform null for a report of the
baseline alone), but no year: the simulation service calculates the
household's default year, adding every variable the household lacks. None
names a PolicyEngine.py version: the simulation service runs its default
worker's. None names a label or a description, which belong to users'
saved reports. The simulation service answers:

- 201 or 202 with the created record's ID and its first run's ID: for a
budget window, its budget-window run's ID (``budget_window_run_id``). One
Expand Down Expand Up @@ -276,13 +276,25 @@ def budget_window_request(report: BudgetWindowReportCreationInput) -> dict[str,


def _household_policy_choice(choice: HouseholdPolicyChoice) -> dict[str, str | None]:
return {"policy_id": None if choice.policy_id is None else str(choice.policy_id)}
"""Return a household side's policy, and its dynamic only when it names one.

The simulation service's release before it took a household side's
dynamic refuses any side naming the field, so a side without one sends
none and is accepted by either release.
"""
side: dict[str, str | None] = {
"policy_id": None if choice.policy_id is None else str(choice.policy_id)
}
if choice.dynamic_id is not None:
side["dynamic_id"] = str(choice.dynamic_id)
return side


def household_report_request(report: HouseholdReportCreationInput) -> dict[str, Any]:
"""Return the simulation service's request body for the household report.

``reform`` is null for a report of the baseline alone.
``reform`` is null for a report of the baseline alone. Each side names
its dynamic only when it has one.
"""
return {
"country": report.country_id,
Expand Down
Loading
Loading