Skip to content

Take household report variables and serve extra calculations of household report runs at /v2/reports - #4404

Draft
anth-volk wants to merge 13 commits into
v2plan/d2-3a-household-run-tablesfrom
v2plan/d2-3c-household-report-variables
Draft

anth-volk wants to merge 13 commits into
v2plan/d2-3a-household-run-tablesfrom
v2plan/d2-3c-household-report-variables

Conversation

@anth-volk

Copy link
Copy Markdown
Collaborator

Fixes #4403
Do not merge: raise the policyengine-api-simulation-client pin to the release D2 · 3b's merge publishes (PolicyEngine/policyengine-sim-api#1202). The pinned 0.20261202.458 lacks the create_household_run_calculations operation and the variables fields, so CI fails until then.

Summary

API v1's API v2 report routes take the variables a household report calculates, show them in reads, and request and read stored extra calculations of a household report's run. This is task D2 · 3c of "5. Detailed-save API"; app v3's household-report feature (D2 · 4) builds on these routes.

  • variables on household report create and re-run. POST /v2/reports (household reports) and POST /v2/reports/{report_id}/runs take an optional variables list: the variables each side's simulation runs calculate. Null or omitted means every variable, as before. The list follows /v2/household-calculations' name checks (1 to 255 characters, no NUL, at most 10,000 names), and an empty list or a repeated name is refused with 422. Each name is checked against the running catalog version after the household and policies (422 unknown_variables), and the list is sent to the simulation service only when given. A re-run of an economy report or budget window that lists variables answers 422 before anything is asked. Both routes now refuse bodies over 1 MiB (was 16 KiB) so a full list fits.
  • calculated_variables in reads. A household report's item names the variables each side's simulation run calculates (from household_run_variables), whatever the run's status; null without a run, and null for a side with no row.
  • POST /v2/reports/{report_id}/runs/{run_id}/household-calculations?country_id= with {variables, axes}. It reads the report in the country (404), refuses a report that isn't a household report (422), a run of another report (404) and a failed run (409, "run the report again") before asking; checks the country and each variable; then asks the simulation service, through the generated client's create_household_run_calculations operation, to find or create each side's calculation. It answers 201 with {baseline, reform}, each {id, status, variables, axes, result, error_message, created_at, completed_at}, whether the calculations were found or created. No user credential is needed and nothing is recorded per user. Bodies over 1 MiB answer 413.
    • The simulation service's answers map as the other API v2 simulation clients map them: a 409 with a code (report_run_failed, report_run_not_current, rerun_not_supported) is 409; 422 and caller-row 400 codes are 422; its own 503 and statuses sent before any write are 503; a 500, a proxy's 502 or 504, an unreadable 503 and any other status are 502 with "request the same calculations again", since an identical request finds the calculations already created.
    • When the calculations it named cannot be read back, the route answers 502 naming each distinct calculation's GET /v2/household-run-calculations/{id} read and both IDs.
  • GET /v2/household-run-calculations/{id}?country_id= reads one stored extra calculation: its status, variables, axes, the household function's result once it succeeded, and its error once it failed. Another country's calculation is 404.
  • Migration contract files (docs/generated/migration_contracts.json, docs/engineering/migration-contracts.md) regenerated with the two new routes in the report route group; the migration request log records the new read like the other API v2 simulation resources.

Migration notes

  • Route groups: report (/v2/reports create, re-run and reads; the two new routes).
  • What stays on the Flask/API v1 path: nothing here changes it.
  • What is newly prepared: FastAPI routes that read the Supabase tables D2 · 3a adds (household_run_variables, household_run_calculations) through SQLAlchemy, and ask the Cloud Run simulation service for extra calculations.
  • User-visible contract changes, intended: the optional variables request field, the calculated_variables response field, the two new routes, and the 1 MiB request limit on report create and re-run.

Builds on

D2 · 3a's branch v2plan/d2-3a-household-run-tables (#4396), which adds the tables and ORM models these reads use. This PR is stacked on it, so it runs only the CI complete and PR description jobs until #4396 merges.

Testing

Tests come first in each pair of commits, as separate commits; each was run individually by node ID, once on the commit with the tests (to see them fail) and once after the change (to see them pass). No full suite was run.

  • Variables on create and re-run (fc318fa3, 123cce33; change 34475d3f): 46 tests. Before the change 40 fail (route and model tests on assertions; body and submission tests with TypeError or ValidationError; the economy re-run tests with ImportError) and 6 pass (the two over-1-MiB tests, which 16 KiB already refused; three exact-call re-run route tests; "no list sends none"). After, all 46 pass.
  • Reads (575bea73; change 6cae7965): 24 tests, all fail before and pass after, plus test_migration_flags.py::test_infer_route_group[/v2/household-run-calculations/…-report], which fails without the registry entry and passes with it.
  • Extra-calculation POST (f0d3e6a8; change 65a9632d): 71 tests, all fail before and pass after; the earlier 46 and 24 still pass.
  • Review fixes: 3d0f5831 (log record of the new read; fails before, passes after ee6dee13), f090ec82 (one calculation on both sides: the 502 message test fails before and passes after b11db3fa; the service test covers a branch that already worked).
  • The tests that use the new client operation ran against a client generated locally from D2 · 3b's branch, installed only in the local environment. Checks run locally: the commit hook's ruff, import contracts, mypy and quality guards; alembic -c alembic-v2.ini check on a disposable PostgreSQL 17 (no new operations); python -m scripts.rules validate.

Review

Two rounds of adversarial review, each by a fresh reviewer on its own clone, before this PR was opened.

  • Round 1 (head 48cda19c): two low-priority bugs, both fixed with a test first. The migration request log recorded GET /v2/household-run-calculations/{id} with the report route group's database and compute settings (fixed in ee6dee13: it now gets the fixed record of the other API v2 simulation resources); two function-level import blocks in the generated-client tests were unsorted, which the required ruff check refuses (fixed in ee6dee13). Two cheap quality items were also fixed: the 502 message named one calculation's read twice when both sides share it (b11db3fa), and the re-run description now says a run the re-run joins keeps the variables it was created with.
  • Round 2 (head b11db3fa): no bugs.

Bugs left: none.

Quality items left (no behaviour is wrong):

  • The re-run text still says a household report's sides "are always calculated again, so force changes nothing for it" (route description, ReportRerunRequest, V2StoredReportService.rerun_report, ReportRerunInput). That sentence predates this PR; the simulation service now joins an unforced household re-run to a current run found by key, so it no longer holds.
  • Report creation's OpenAPI text doesn't say that a run the request joins keeps its own variables (the re-run description does).
  • The extra-calculation POST can answer 500 through its fallback handler, but its OpenAPI responses don't list 500.
  • No test fails if production wiring stops passing the variable source to the submission service, and no route test covers an unreadable simulation service answer (502, "request again").
  • GET /v2/household-run-calculations/{id} builds the submission service, which it never uses, and every request that submits builds a whole household calculation service only for its variable check.
  • The extra-calculation reads repeat the stored-report service's "report of this country" and "run of this report" queries rather than sharing them.
  • The unknown-variables 422 message begins "The calculation lists variables…", which now also answers a report's or re-run's list.
  • SimulationSubmissionService takes its variable source as optional; production always passes one.

Ruff suppressions added

  • E501 on imports whose module path alone is longer than the line limit (routes, services, dependencies, tests): a module path can't be split across lines.
  • PLR0913 on rerun_report (the service, its protocol and the tests' stand-in) and on SimulationSubmissionService.__init__: each keyword argument is an option the request body gives or a source a check reads; grouping them into one object would only move the list. Also on the test helper _store_calculation, whose arguments are the columns a test varies.
  • F401 and F811 in test modules that import pytest fixtures from another test module: pytest finds fixtures by parameter name, so the import looks unused (F401) and the parameter looks like it redefines it (F811).

What the merge waits for

  • D2 · 3b deployed (task done), with its client release published: this PR pins that release and calls the route it deploys. Raising the pin is this PR's own step (the "Do not merge" line).
  • D2 · 3a merged: same repository, and this branch contains its commits.
  • D2 · 1a, 2b and 3 merged (earlier in tracker order only); D2 · 1, 2, 2a and 2c done.

No deployment code changed, so there is no environment variable table.

🤖 Generated with Claude Code

anth-volk and others added 12 commits December 4, 2026 01:57
The tests cover the variables list on POST /v2/reports for a household
report and on POST /v2/reports/{id}/runs: the list's limits, the check
against the running catalog version, the request bodies sent to the
simulation service, the refusal of a list for an economy report or a
budget window, and the 1 MiB request size limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
POST /v2/reports (kind household) and POST /v2/reports/{id}/runs take an
optional variables list: 1 to 10,000 distinct names of 1 to 255 characters
with no NUL character. Null or omitted calculates every variable, as
before; an empty list is refused, because a run stores the list it
calculated and stores none for every variable. Each name is checked
against the running catalog version after the household, policies and
dynamics, through the household calculation service's check, and unknown
names answer 422 with code unknown_variables. A re-run listing variables
for an economy report or budget window answers 422. The list is sent to
the simulation service only when given. Both routes now take bodies of up
to 1 MiB, so a list of 10,000 typical names fits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s, which fail before the change

The household report read gives calculated_variables: each side's listed
variables from household_run_variables, null for a side that calculated
every variable, and null with no run. GET
/v2/household-run-calculations/{calculation_id} reads one extra
calculation of a household report's run: its status, variables, axes,
calculated household or error message; another country's is not found.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The household report read gives calculated_variables: each side's list
from household_run_variables, null for a side whose run calculated every
variable, and null for a report with no run. The household outcome read
moves to stored_reports/household_results/services.py, which keeps the
report service under the file length limit.

GET /v2/household-run-calculations/{calculation_id}?country_id= reads one
extra calculation of a household report's run from
household_run_calculations: its status, variables, axes, calculated
household once it has succeeded and error message once it has failed. A
calculation of another country's run is not found; the read never calls
the simulation service. The route is in the report route group and the
detailed-save reports workflow contract, and the contract files are
regenerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… fail before the change

POST /v2/reports/{report_id}/runs/{run_id}/household-calculations reads the
household report in its country, refuses a failed run with 409, checks the
listed variables, asks the simulation service for each side's calculation
and answers 201 with both, read back from household_run_calculations. The
generated-client tests also send a household report's and a re-run's list
of variables through the generated request models.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
POST /v2/reports/{report_id}/runs/{run_id}/household-calculations?country_id=
reads the report and run in the country, refuses another kind of report
(422), an unknown report or run (404) and a failed run (409), checks the
country and each listed variable, then asks the simulation service's new
route through the generated client. The service finds each side's
calculation of the same variables and axes that hasn't failed, or creates
and starts one; API v1 reads both back and answers 201. Calculations that
cannot be read back answer 502 naming each, and the simulation service's
answers are read as for a re-run.

The generated client's create_household_run_calculations operation comes
with the simulation service release that adds the route, so this change
needs the client pin raised to that release before it can merge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…he changelog

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ch fails before the fix

GET /v2/household-run-calculations/{id} reads only Supabase and calls
nothing, like the report reads, so its log record should not read the
report route group's database or compute flags.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rces, and sort two test imports

GET /v2/household-run-calculations/{id} reads only Supabase, so its log
record no longer reads the report route group's database or compute flags.
Also sort the function-level imports of two generated-client tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…age test fails before the fix

A report comparing a policy with itself has one calculation on both sides.
The service already reads it once for both; the 502 message, when it cannot
be read back, should name its read path once rather than twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…n keeps its variables

When the extra calculations cannot be read back, the 502 message names
each distinct calculation's read once. The re-run description now says a
run the re-run joins keeps the variables it was created with, and how to
request others.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk added a commit to PolicyEngine/policyengine-app-v2 that referenced this pull request Dec 3, 2026
…ocument

Replaces the parts added by hand before D2 · 3c had a PR with API v1's
exported /v2/openapi.json at PolicyEngine/policyengine-api#4404's head
(b11db3fa): the /v2/reports routes, the household report run's extra
calculations and their reads, and every schema they reach. Those schemas
take D2 · 3c's names, calculated_variables becomes required, both lists
of variables need at least one name, and the extra calculations gain a
502 answer and a 422 unknown_variables answer. Other routes are
unchanged. The report fixture gains calculated_variables as API v2
answers it; the extra-calculation client's notes say a failed run also
answers 409.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 38.34746% with 291 lines in your changes missing coverage. Please review.
✅ Project coverage is 92.99%. Comparing base (4b2d6f4) to head (bccd26b).

Files with missing lines Patch % Lines
..._api/libs/simulation_household_run_calculations.py 0.00% 91 Missing ⚠️
...services/v2/household_run_calculations/services.py 0.00% 48 Missing ⚠️
...rvices/v2/household_run_calculations/validators.py 34.69% 32 Missing ⚠️
...ne_api/services/v2/household_calculations/types.py 18.18% 18 Missing ⚠️
...pi/services/v2/household_run_calculations/types.py 0.00% 18 Missing ⚠️
...api_routes/v2/household_run_calculations/routes.py 67.30% 16 Missing and 1 partial ⚠️
...hold_run_calculations/database_connectors/reads.py 0.00% 13 Missing ⚠️
.../v2/household_run_calculations/database_session.py 0.00% 10 Missing ⚠️
policyengine_api/libs/simulation_reports.py 0.00% 8 Missing ⚠️
...ine_api/services/v2/simulation_service/services.py 50.00% 6 Missing and 1 partial ⚠️
... and 10 more

❌ Your patch check has failed because the patch coverage (38.34%) is below the target coverage (80.00%). You can increase the patch coverage or adjust the target coverage.

Additional details and impacted files
@@                          Coverage Diff                          @@
##           v2plan/d2-3a-household-run-tables    #4404      +/-   ##
=====================================================================
- Coverage                              93.98%   92.99%   -0.99%     
=====================================================================
  Files                                    459      470      +11     
  Lines                                  26296    26727     +431     
  Branches                                4090     4138      +48     
=====================================================================
+ Hits                                   24714    24856     +142     
- Misses                                   907     1194     +287     
- Partials                                 675      677       +2     
Flag Coverage Δ
integration 60.57% <38.34%> (-0.39%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

…vision, into the household report variables branch

GitHub reported a conflict with the base branch. Its new commits make
each report store its type in reports.type and read it in place of the
type derived from its simulations, which removed ReportKind and
report_kind().

- stored_reports validators: keep the variables refusal, now naming the
  report's stored type (ReportType), and take the base branch's
  require_budget_window_year, which no longer takes the type.
- stored_reports services: the re-run checks cliffs and variables
  against the stored type.
- household_run_calculations validators: the household-report check
  reads report.type in place of the removed report_kind().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant