Skip to content

Record household report runs' variables and run extra calculations of a run - #1202

Draft
anth-volk wants to merge 17 commits into
mainfrom
v2plan/d2-3b-household-run-calculations
Draft

anth-volk wants to merge 17 commits into
mainfrom
v2plan/d2-3b-household-run-calculations

Conversation

@anth-volk

@anth-volk anth-volk commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1200
Do not merge: raise libs/policyengine-simulation-persistence/public-api-commit to the merge commit of PolicyEngine/policyengine-api#4396 (D2 · 3a). It is pinned to that PR's head until it merges, so the pinned-commit check fails until then.
Do not merge: a core developer other than the author approves the change to the proof fixtures under rules/, as rule sim.process.rule-machinery-code-owned requires.

What this changes

The simulation service now records which variables each household report run calculates, and runs extra calculations of a run. It uses the two tables API v1 adds in PolicyEngine/policyengine-api#4396.

Variables on household reports

  • A household report's create (POST /reports, report_type: household) and re-run (POST /reports/{report_id}/runs) take an optional variables list. Absent or null means every variable, as before.
  • For each simulation run the request inserts, the list is recorded, sorted, in household_run_variables. This covers create, forced re-run and unforced re-run. A request that joins an existing run records nothing, and that run keeps its own list.
  • The household function calculates each side with its run's recorded list, or every variable when there is no row. It ignores its payload's list, because identical requests share simulation runs and whichever call claims a shared run calculates it.
  • The service refuses variables with 422 variables_not_available in two places: an economy or budget-window report's re-run, and POST /reports/without-run, which creates no run to record the list.
  • A list must name at least one variable and at most 10,000. Each name must be 1–255 characters, appear once and contain no NUL character. Anything else is refused with 422 at variables.

Extra calculations: POST /reports/{report_id}/runs/{report_run_id}/household-calculations

  • The body is {"variables": [...], "axes": ... | null}. The route calculates those variables of each side's simulation run, or of its household across the axes, under the run's household, policy, dynamic, year and versions.
  • Before writing anything, it refuses:
    • an unknown report (404 unknown_report), or a run that isn't the report's (404 unknown_report_run);
    • a report that isn't a household report (422 household_calculations_not_available);
    • a failed run (409 report_run_failed);
    • a run on other versions than the default worker's (409 report_run_not_current);
    • what the household contract refuses (422, located at the stored report).
  • In one transaction, for each distinct simulation run, it finds the household_run_calculations row of the same variables (in any order) and axes that hasn't failed, or inserts one pending.
  • For each row it inserted, it starts one household function call (household_run_calculation_id) and records the call's ID. When Modal refuses the call or doesn't confirm it in time, the row is failed at once and answered failed, so the next identical request starts another.
  • It answers 201 with report_id, report_run_id, and for baseline and reform (null for a baseline-only report) the calculation's ID, its simulation run and its status. A database write that can't be confirmed answers a 500 saying the calculations may have been written.
  • The household function claims the row under its own call, then records the HouseholdExecutionResult as result, or the failure's one-line summary as error_message. A row another call holds, or one already finished, isn't calculated again.
  • The stuck-run sweep also fails calculations whose call ended or never started. It measures age from the first claim or, while a row is pending, from its creation.
  • API v1 reads the rows; the service has no GET.

Persistence and documentation

  • The persistence library has ORM models of both tables, plus the two unique constraints the new tables' foreign keys use.
  • The service role may insert into both tables and record a calculation's call. The Modal worker role may read both and update a calculation's state and result.
  • The entry README, the persistence README, the Stage 12 migration document and the database-access and observability skills describe the change.
  • The missing-privileges rule's proof fixtures now name only the privileges they leave out, so a new service table no longer means editing them. See "Fixed after the PR opened" below.
  • policyengine-api-simulation-client gains the route and the variables fields when this merges.

Decisions, quoting Anthony

  • The route shape: "A, as recommended". One route over a report run covering both sides, with no GET.
  • From D2 · 3c's questions:
    • "Yes, A": empty lists and repeated names are refused with 422.
    • "A: refuse with 409": an extra calculation of a failed run is refused until the report is re-run.
    • "A: 1 MiB": a request size limit on API v1's routes. Here, variables keeps the bounds above.

Deployment order. API v1's revision from PolicyEngine/policyengine-api#4396 must be applied in an environment before this release deploys there, for three reasons:

  • the service's /ready privilege check names both tables;
  • every household report side reads household_run_variables;
  • the stuck-run sweep lists household_run_calculations on every pass.

Between the entry's promotion and the move of the v2 default, the entry could start the previous default's household function with the new keyword, which that function doesn't take. The call would fail before claiming the row, and the sweep would fail the row once it is ten minutes old. Nothing calls the route until API v1 does (D2 · 3c).

Tests

Tests that fail before the change were committed first, each failing on its assertion:

  • 01357a30, a0467e39, 93a3bdfa and c0358f61: the change itself;
  • 223449da: failed runs and NUL characters;
  • 4ff3de8d: review round 1's two fixes.

The change then made them pass. Run locally by node ID, one file at a time, against a disposable PostgreSQL 17 with API v1's v2 schema at D2 · 3a's head:

Package Tests added or changed After the change
libs/policyengine-simulation-persistence 30 pass
libs/policyengine-stage12-persistence 7 pass
projects/policyengine-simulation-executor 17 pass
projects/policyengine-simulation-entry 40 pass
projects/policyengine-apis-integ (generated client) 4 pass

Five of these cover code already written, so they passed on their first run:

  • a database test of an unforced re-run that joins the report's run, inserts both sides' runs, or joins one side's run and inserts the other's;
  • the four generated-client tests.

The repository checks passed on the changed packages: format, lint, rules registry, quality guards (file length included), lock files, and Pyright on persistence, Stage 12 persistence, observability, executor, entry and apis-integ.

Fixed after the PR opened. CI failed four existing persistence tests that list the service's tables or privileges by hand. The other test jobs were cancelled when the persistence job failed, so none of their tests failed.

  • 93ec16e7: test_each_base_maps_exactly_the_tables_of_its_metadata[service] and test_each_refused_key_is_known_by_its_table_and_column now name the two new tables' classes. That adds both classes to the per-class tests. API v1 keys household_run_variables by simulation_run_id, one row per run, so the primary-key test reads that class's key from a small PRIMARY_KEYS map and requires id for every other class. 9bc1e537 renames that test to test_each_class_is_identified_by_id_or_its_listed_primary_key.
  • 47e69d1d: the two cases of test_rule_proof_missing_privileges_reported failed because the proof fixtures listed every privilege the service needs, a hand-made copy of SERVICE_TABLE_PRIVILEGES and SERVICE_UPDATABLE_COLUMNS. Each new service table meant editing both files under rules/. The proof now grants every privilege the service needs except those its fixture names. The bad fixture names the same two privileges as before, and the good one names none. A fixture entry that names no required privilege fails the test. Anthony chose to make this change here: "In this PR".

These tests pass locally, each run by node ID. The repository checks pass on the persistence package.

Review

Three rounds of review, each by a fresh reviewer against a fresh clone.

Round 1 (a43f1232): all eight claims met. It found one low-priority bug: POST /reports/without-run accepted and dropped a household report's variables. That is fixed, test first. Of its six code-quality findings:

  • Fixed:
    • an unconfirmed write now answers the "may have been written" 500;
    • stale documentation is updated;
    • the request description now says a joined run keeps its own list;
    • the unforced re-run test and the generated-client tests are added.
  • Left:
    • the duplication described below;
    • axes keys, described below.

Round 2 (183525e4): no bugs. It found documentation of the stuck-run sweep and the Stage 12 migration document still out of date, and the deployment order unstated. Both are fixed in e92f9005.

Round 3 (47e69d1d, the fixes after the PR opened): no bugs, and all four aims met. The reviewer ran the proof test with altered fixtures. Entries naming no required privilege were refused, and a good fixture leaving out SELECT policies failed the proof. The reviewer also judged that deriving the grants from the service's own privilege lists doesn't weaken the proof in a way that matters:

  • the expected missing privileges are written by hand;
  • the check reads PostgreSQL's catalog, not the lists;
  • three tests in test_access pin both lists by hand;
  • the "Public API schema" job checks the lists against API v1's privilege manifest.

The reviewer had two code-quality findings:

  • Fixed in 9bc1e537: the primary-key test's name no longer matched what it checks.
  • Left: two tests in the "Public API schema" job that write a row to each table still name only the older tables. Their tables are written as the service role in test_household_run_records, and as the Modal worker role in the Stage 12 extra-calculation store tests.

Left as they are (no bugs):

  • Duplication. The code that starts a Modal call and then records its ID or fails the row now has a fourth copy, alongside cliff calculations and the economy and household creates. Merging them touches those routes.
  • Axes keys. The calculation key hashes axes as written, so equivalent axes written differently get separate calculations: 0 and 0.0, an omitted and an explicit index, 2026 and "2026". axes: [] is keyed apart from no axes.
  • Rule scope. The scope of rule sim.persistence.models-match-public-api in rules/registry.toml lists tables.py but not household_run_tables.py or table_values.py. Its tests still compare both modules' tables with API v1's, because they read service_metadata. Adding the files is a change under rules/.
  • No concurrent-transaction tests. Each race outcome is covered by sequential tests. The lookup is the one cliff calculations already use.

What the merge waits for

This PR is built on main, not on another task's branch.

Merged main once (90f4b744), because the PR conflicted with it. main's household functions now keep their container's observability runtime open. The conflict in v2_app keeps that, and adds the extra calculation's keyword, check and record attributes.

The merge took v2_app to 810 lines and test_stage12_modal_app to 1,576, over the file-length limits. ca7d3913 fixes both:

  • it shortens the household function's choice of the row a call names;
  • it moves the two tests of calls naming an extra calculation into test_stage12_modal_household_run_calculations, expecting the runtime to stay open;
  • it has the refusal tests import the household calculation module first, so they pass when run alone.

Those three tests pass, each run alone.

Merged main again (8cbf65b7), because the PR conflicted with it. main now pins API v1 on D1 · 8's merge commit, where reports.type is required and checked. The only conflict was public-api-commit. It now names D2 · 3a's current head, cb8200d2, which already includes D1 · 8's merge, so the pinned API v1 has both the required report type and the household run tables.

That merge took tables.py to 804 lines, so 75b651fb moves the column limits and the four status and type enums, unchanged, into a new table_values.py. tables.py re-exports them, so every import from it keeps working. Pyright passes on every package that imports the persistence library.

Environment variables

No variable is added. The changed code reads these existing ones, wired as before:

Variable Read by Provider Wiring (unchanged)
SIMULATION_SERVICE_DATABASE_URL The Simulation Entrypoint: the new route's store, like household reports' Google Secret Manager, the secret named by the GitHub Actions variable SIMULATION_SERVICE_DATABASE_URL_SECRET_NAME simulation-deploy.reusable.yml passes the name to deploy-cloud-run-simulation-entry.sh, which adds it as a Cloud Run runtime secret
SIMULATION_V2_MODAL_ENVIRONMENT, SIMULATION_V2_MANIFEST_NAME The Simulation Entrypoint: the default worker and its household function The deploy workflow's Modal environment, and a fixed manifest name Set by deploy-cloud-run-simulation-entry.sh as Cloud Run environment variables
MODAL_WORKER_DATABASE_URL The household functions (recorded variables, extra calculations) and the stuck-run sweep A Modal secret Already attached to both household functions in v2_app.py and to the sweep in run_sweep_app.py

🤖 Generated with Claude Code

anth-volk and others added 12 commits December 4, 2026 01:32
…run extra calculations

These tests describe D2 · 3b and fail before the change:

- sim's models of API v1's household_run_variables and
  household_run_calculations tables, and the role privileges on them;
- a household report's create or re-run recording its listed variables,
  sorted, for each simulation run it inserts, and each side's household
  function request listing those variables;
- the household function calculating each side's run with the variables
  that run records;
- finding or inserting a household run's extra calculation by a key of its
  variables and axes, recording its Modal call, and failing an unstarted one;
- the household function claiming, calculating and recording an extra
  calculation, and the stuck-run sweep failing one no call finished;
- POST /reports/{report_id}/runs/{report_run_id}/household-calculations and
  its OpenAPI answers.

The table definitions are pinned to the head of API v1's household run
tables branch until it merges.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The extra-calculation store test inserted JSON null for absent axes, which
the table's check refuses; it now leaves the column out. The variable-list
refusal test now checks the list itself is refused, not an unknown field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The extra-calculation test that deletes a run after its read built its
EconomyRecordReferenceError with one argument; the error takes the table
and the column. The new tests are formatted, and their long lines wrapped,
as the repository's lint requires.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The route reads the stored report's household, policies and dynamics as a
household report's re-run does, so it answers 400 when one of them, or the
default worker's household function or catalog version, is missing. The
OpenAPI test now expects that answer with the error schema.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Anthony's answers in D2 · 3c: an extra calculation of a report run that
has failed is refused with 409 (report_run_failed), while pending,
running and succeeded runs get one; and a household report's or extra
calculation's variable name containing a NUL character is refused with
422, as /v2/household-calculations refuses it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A household report's create and re-run take an optional `variables` list,
recorded, sorted, in `household_run_variables` for each side's simulation
run the request inserted; the household function calculates each side
with its run's recorded list, or every variable without one.

`POST /reports/{report_id}/runs/{report_run_id}/household-calculations`
finds, for each distinct simulation run of the report run, the
`household_run_calculations` row of the same variables and axes that
hasn't failed, or inserts one pending and starts one household function
call for it. The function claims the row under its call and records the
calculated household or the failure's summary; the stuck-run sweep fails
a row no call finishes. A run that failed, or one on other versions than
the default worker's, is refused with 409 until the report is re-run.
An empty list, a repeated name or a name with a NUL character is refused
with 422. The sim ORM models match the tables API v1 creates (pinned to
D2 · 3a's branch until it merges).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A household report created without a run that lists variables is
refused with 422 variables_not_available, as one asking for cliffs is,
since no run records the list. An extra calculation whose commit can't
be confirmed is answered as other creates answer it: a 500 saying the
rows may have been written, logged as its own event.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A household report created without a run that lists variables is
refused with 422 variables_not_available, as one asking for cliffs is:
no run records the list, and the report's first run lists its own. An
extra calculation whose commit can't be confirmed answers the 500 saying
the calculations may have been written, logged as
household_run_calculations_outcome_unknown, as other creates answer it.
The household report request's description says a run it joins keeps
its own list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t the tables

A database test follows an unforced household re-run that joins the
report's run, one that inserts both sides' runs, and one that joins one
side's run and inserts the other's: each records the list only on the
runs it inserted. Generated-client tests send an extra calculation and a
household report's variables, and read the answers. The persistence
README and the database-access and observability skills name the two
household run tables.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The stuck-run sweep's application, its summary and the executor README
name household runs' extra calculations among what the sweep fails. The
Stage 12 migration document describes the household function's
`household_run_calculation_id` call, that each side calculates its run's
recorded variables, and that API v1's revision adding the two household
run tables must be applied before this release deploys. The persistence
README names the test that writes those two tables as the service.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…e extra calculations branch

The household function now uses its container's observability runtime
and leaves it open; the conflict in v2_app keeps that and adds the extra
calculation's keyword, check and record attributes.

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

The merge took the Modal app to 810 lines and its tests to 1,576. The
household function now picks the row its call names in one branch,
and the tests of calls naming an extra calculation move to their own
module, expecting the container's runtime to stay open as main's
household functions now leave it. The refusal tests import the household
calculation module first, so its imports' own exit handlers are not
recorded as the runtime's when a test runs alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk and others added 5 commits December 4, 2026 20:47
…y service table

`test_each_base_maps_exactly_the_tables_of_its_metadata[service]` and
`test_each_refused_key_is_known_by_its_table_and_column` list the service's
mapped classes by hand, so they failed once this branch mapped
`household_run_variables` and `household_run_calculations`. Both lists now
name the two classes.

Listing them adds both to the per-class tests. API v1 keys
`household_run_variables` by `simulation_run_id`, one row per run, so the
primary-key test now reads each class's expected key from `PRIMARY_KEYS`,
defaulting to `id`.

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

The proof fixtures listed every privilege the simulation service needs, a
hand-made copy of `SERVICE_TABLE_PRIVILEGES` and `SERVICE_UPDATABLE_COLUMNS`.
Every table the service started using meant editing both files under
`rules/`, as this branch's two household run tables did.

`test_rule_proof_missing_privileges_reported` now grants every privilege the
service needs except the ones its fixture names, and refuses a fixture line
that names no required grant. The bad fixture names the two privileges it
leaves out, as before; the good one names none. The proof still shows that
the check reports exactly what the role lacks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review round 3: the test accepts a class keyed by the key `PRIMARY_KEYS`
lists, `household_run_variables` by `simulation_run_id`, so its name no
longer says only `id`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…extra calculations branch

The one conflict is `public-api-commit`. `main` pins API v1 on D1 · 8's
merge commit, where `reports.type` is required and checked; this branch
pinned D2 · 3a's earlier head, for the household run tables. The pin now
names D2 · 3a's current head, `cb8200d2`, which merged D1 · 8 and so holds
both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Merging `main` took `tables.py` to 804 lines, over the 800-line limit:
`main` added the `reports.type` check, and this branch added the two unique
constraints the household run tables' foreign keys use. The column limits
and the four status and type enums move, unchanged, into `table_values.py`.
`tables.py` imports them and lists them in `__all__`, so every import from it
keeps working. It is now 789 lines.

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

This branch has not been deployed

No deployments
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.

Record household report runs' variables and run extra calculations of a run

1 participant