Skip to content

Add tables for household runs' variables and extra calculations, and household report links, to API v2 - #4396

Draft
anth-volk wants to merge 12 commits into
masterfrom
v2plan/d2-3a-household-run-tables
Draft

anth-volk wants to merge 12 commits into
masterfrom
v2plan/d2-3a-household-run-tables

Conversation

@anth-volk

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

Copy link
Copy Markdown
Collaborator

Fixes #4395

Summary

Tracker task D2 · 3a: tables for household runs' variables, their extra calculations, and household reports linked to economy reports. API v2's database gains three tables, in one autogenerated Alembic v2 revision, 6ec3d17299b6 on 24b571d7d079 (D1 · 8's report types revision), as the new v2 head:

  • household_run_variables: the variables a household simulation run calculated, one row per run (simulation_run_id is the primary key), as a JSON array of names. A household run with no row calculated every variable, as every run stored before this revision did.
  • household_run_calculations: one stored extra calculation of a household run (more variables, or an earnings variation given as axes) and its result, modelled on cliff_impacts. A partial unique index on (simulation_run_id, key_version, calculation_key) where status <> 'failed' allows one calculation of each request that hasn't failed, so identical requests can join it; a failed one doesn't count. It has the run tables' completion check, a check that exactly a succeeded calculation has a result, and an index on (status, started_at).
  • user_report_household_reports: links an economy report's or budget window's saved row (user_report_id) to a household report's saved row (household_user_report_id), at most once per pair, never a row to itself.

How the database holds these to household runs and to one owner and country:

  • Both household tables carry simulation_id and simulation_type, with two composite foreign keys, both ON DELETE CASCADE: (simulation_run_id, simulation_id) to simulation_runs (id, simulation_id), and (simulation_id, simulation_type) to simulations (id, simulation_type), with a check that the type is household. PostgreSQL-only checks hold variables to a non-empty JSON array and axes, when set, to a JSON array.
  • The link table's two foreign keys, (user_report_id, user_id, country_id) and (household_user_report_id, user_id, country_id), both refer to user_report_associations (id, user_id, country_id) with ON DELETE CASCADE ON UPDATE CASCADE. So the database refuses a link between two owners' or two countries' saved rows; deleting either row, or the owner, deletes the link; and signing in to an account that already has a user, which moves each of the browser's saved rows to that user with one UPDATE per table, gives the link that owner.
  • The keys refer to three new unique constraints: uq_simulations_id_type, uq_simulation_runs_id_simulation and uq_user_report_associations_id_user_country.

The revision has two documented post-generation corrections: the new enum columns reuse the existing v2_simulation_type and v2_simulation_status types, and the three unique constraints are created before the tables that refer to them and dropped after those tables. It writes no data and changes no column; the downgrade drops the three tables and the three constraints and leaves the enum types.

Privileges (policyengine_api/data/v2/privileges.py): the simulation service may read and insert household_run_variables, and the Modal worker and API v1's runtime role may read it; nobody may update or delete it. household_run_calculations is granted as cliff_impacts is. Only API v1's runtime role reads and writes user_report_household_reports.

Also: V2_ALEMBIC_HEAD_REVISION, the Alembic v2 check's list of test files, a section in docs/engineering/skills/alembic-migrations.md, and a changelog fragment.

Migration scope: no route or route contract changes, and nothing user-visible. Nothing reads or writes the new tables yet. The simulation service's models of them, and its writes, are D2 · 3b; the routes that link household reports are D2 · 3d. The link table joins two user-report associations (the saved rows /v2/user-reports serves), never base reports, so a report page's URL keeps using its user-report association's ID.

Testing

Tests that fail before the change come first, in three commits, then the change:

  • 3c2670f1: the revision, its downgrade and the new tables' refusals and cascades (tests/integration/test_alembic_v2_household_run_tables.py); the revision file's operations (tests/unit/v2/test_alembic_v2_household_run_revisions.py); the privilege manifest's entries; the simulation service's and Modal workers' writes as their own roles (tests/integration/test_v2_simulation_role_privileges.py); the v2 head and revision chain; and the Alembic v2 check running the new files.
  • 54db9677: a test that signing in moves a link with its saved rows.
  • c22574bb: existing tests the new tables change: the v2 table count (57 → 60), the third unique constraint on user_report_associations in the full-history round-trip test, and the two household tables in both lists of tables the simulation service writes.
  • 582ee410: the change. 9482f9a2, 7a74c74f and 7b7e5690 correct docstrings and documentation after review; they change no behaviour.
  • 17602fc6: CI's first run failed in one existing test, tests/unit/v2/test_models.py::test_associations_are_v1_anchored_without_client_refs, which still expected two unique column sets on user_report_associations. It now expects (id, user_id, country_id) too; it passes locally.
  • 26331cca merges master, which runs API v1 on .py 6.20.5, the simulation API's latest. The check that API v1's .py version is the simulation API's latest had failed on 6.20.4. policyengine-core stays at 3.34.10, the exact version every .py release pins, 6.21.0 included; API v1 installs it only through .py's models extra. The merge had no conflicts and touches none of this branch's files. The tests below pass on it too.
  • dd415364 merges master again, after D1 · 5a (Saved reports stop storing and returning a copy of the reform's changes #4402). Two docstrings conflicted, and the merge keeps both sides' text: UserReportAssociation's (this branch's unique key for household report links, and D1 · 5a's unmapped provisions column) and the module docstring of tests/integration/test_v2_simulation_role_privileges.py (this branch's household tables, and D1 · 5a's wording on columns a mapper leaves out). No code conflicted.
  • 4b2d6f47 merges master after D1 · 8 (Require every API v2 report's type in reports.type, and read it in API v1 #4400), which added Alembic v2 revision 24b571d7d079 on 7dcd2cd14330, this revision's parent until then. 6ec3d17299b6's down_revision moves to 24b571d7d079, so the chain has one head again, as the repository's Alembic skill does for a revision master gains on the same parent. Generated again on 24b571d7d079 with the same ID, the revision has the same operations apart from its two documented corrections; on disposable PostgreSQL 17, the upgrade, alembic check (no new operations), the downgrade to 24b571d7d079, the upgrade again and alembic current --check-heads pass. The head constant, the chain test, this branch's revision tests (their parent revision), the Alembic skill section, and the Alembic v2 check's file list and its test (both branches' files) change with it. Ruff, formatting and the commit hook's make quality pass; the tests weren't run again locally.
  • cb8200d2: CI on 4b2d6f47 failed in one test this branch doesn't otherwise touch, tests/unit/v2/test_me_routes.py::test_export_answers_the_current_run_of_each_saved_report, with a TypeError: it passed provisions=None to UserReportRead, whose provisions field D1 · 5a (Saved reports stop storing and returning a copy of the reform's changes #4402) removed, and the test came in with D1 · 8 (Require every API v2 report's type in reports.type, and read it in API v1 #4400). master has the same test and model, so it fails there too. The test no longer passes provisions; it passes locally.

Local results, running only the 13 unit and 11 integration tests this branch adds or changes, by node ID, on disposable PostgreSQL 17:

  • Before the change: every one fails except test_no_new_role_writes_the_public_api_tables, whose changed set holds before and after. All fail on assertions, except two existing manifest tests (test_no_role_can_change_what_a_run_is, test_public_api_reads_simulations_runs_and_results_without_writing_them), which fail with KeyError because the new tables have no manifest entry yet. The sign-in test fails with a foreign-key violation on the change without the update cascade.
  • After the change: all pass (12 integration results; one test is parametrized).
  • alembic -c alembic-v2.ini check reports no new operations at head; the upgrade, downgrade and upgrade again succeed; privilege reconciliation applies and verifies.
  • The commit hook's make quality, python -m scripts.rules validate, lint-imports and python scripts/run_quality_guards.py pass. Running mypy on the changed policyengine_api/data/v2/ files by name reports only sqlmodel's Field(sa_type=...) overload errors that the existing models already have (master has 10 in these files; the new fields add 8 of the same kind); the repository's mypy file list leaves these modules out.

Review

Three rounds of review, each by a fresh reviewer:

  • Round 1 (on 582ee410): no bugs. It re-ran the tests on both commits, regenerated the revision with the same ID under four hash seeds (identical apart from the two documented corrections), and confirmed each claim above. Its wording findings (the privilege manifest's role descriptions, three model docstrings describing later tasks' code as existing, a bare "v2" in test text) and its deploy note on locks are fixed in 9482f9a2.
  • Round 2 (on 9482f9a2): no bugs. Its documentation findings on the lock note and two present-tense descriptions are fixed in 7a74c74f.
  • Round 3 (on 17602fc6, the CI fix): no bugs. It found no other test that still expects the old unique constraints. Its documentation finding, that the Stage 12A user-login doc still said no uniqueness on the association tables involves the owner, is fixed in 7b7e5690.

Bugs left: none found.

Deploying it

  • Locks while it runs. Each new unique constraint takes an ACCESS EXCLUSIVE lock on its table to build its index (simulation_runs, then simulations, then user_report_associations), held until the migration commits. Reads and writes of those tables wait meanwhile; statements with a statement timeout (API v1's is 5 seconds) fail when they reach it. A transaction that uses a simulation and then its runs can deadlock with the migration; if PostgreSQL aborts the migration, the upgrade rolls back whole and can be run again. The Alembic skill section describes this in full.
  • The simulation service's weekly schema comparison. PolicyEngine/policyengine-sim-api compares its models of simulations and simulation_runs with this repository's master by constraint name. That weekly comparison fails once this is merged, until D2 · 3b adds uq_simulations_id_type and uq_simulation_runs_id_simulation to its models, as happened with uq_report_runs_id_report. Its pull-request job compares at its pinned commit and isn't affected.

What the merge waits for

This PR builds on master, not on an earlier task's branch.

Environment variables

The change edits .github/scripts/test_alembic_v2_lifecycle.sh (two more test files). The script reads no variable itself; the tests it runs read these, in the Alembic v2 schema checks workflow (alembic-v2-check.yml, called from pr.yml and push.yml):

Variable Read by Provider Wiring
UV_PYTHON uv A literal in the job's env: block Job-level env:, reaches every step
V2_MIGRATION_DATABASE_URL Alembic v2 environment, tests/integration/conftest.py A literal in the job's env: block, naming the job's own PostgreSQL 17 service container (not a secret) Job-level env:
V2_ALEMBIC_DISPOSABLE_TEST Alembic v2 environment, tests/integration/conftest.py A literal "1" in the job's env: block Job-level env:
DEPLOYMENT_ENVIRONMENT tests/integration/conftest.py (names of the managed roles) Not set in this job; the fixture defaults to test, as for the existing Alembic tests there None needed

No secrets are read, and no workflow file changes.

🤖 Generated with Claude Code

anth-volk and others added 6 commits December 3, 2026 21:17
…fail before the change

Task D2 · 3a adds three API v2 tables in one revision on 7dcd2cd14330:
household_run_variables (the variables a household simulation run
calculated), household_run_calculations (a household run's stored extra
calculations), and user_report_household_reports (links from an economy
report's saved row to household reports' saved rows of the same owner and
country), with the unique constraints their composite keys refer to.

The tests cover the revision's schema and its exact downgrade, the database
refusing rows for economy runs, mismatched simulations, other owners' or
countries' saved rows and malformed variable lists, one unfailed calculation
per request, the cascades from runs, simulations, saved rows and users, the
revision file's operations, the new v2 head, the declared privileges, and the
simulation service's and Modal workers' writes as their roles.

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

Signing in to an account that already has a user moves each of the
browser's saved rows to that user with one update per table. The test
checks that a link between two of those rows takes the new owner, and the
revision test now records each key's update action.

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

- The v2 metadata has 60 tables, not 57.
- At head, user_report_associations has a third unique constraint,
  (id, user_id, country_id), which the household report links' keys
  reference. Each of its unique constraints still includes the row's ID, so
  signing in can still move any row to another owner.
- household_run_variables and household_run_calculations are tables the
  simulation service writes; the integration test now checks that every
  table in that list exists at head.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…hold report links to API v2

Revision 6ec3d17299b6, autogenerated on 7dcd2cd14330, adds three tables:

- household_run_variables: the variables a household simulation run
  calculated, one row per run. A run with no row calculated every variable.
- household_run_calculations: a household run's stored extra calculations
  (such as an earnings variation) and their results, modelled on
  cliff_impacts. A partial unique index lets identical requests join one
  calculation that hasn't failed.
- user_report_household_reports: links an economy report's saved row to a
  household report's saved row of the same owner in the same country.

Both household tables name their run together with its simulation, and the
simulation together with its type, checked to be 'household', so PostgreSQL
accepts their rows only for household runs; deleting the run or simulation
deletes them. The link table's two keys name each saved row together with
the link's owner and country, cascading deletes and updates, so a link
between two owners' or countries' rows is refused, deleting either row or
the owner deletes the link, and moving the rows to another owner at sign-in
gives the link that owner. The keys refer to three new unique constraints:
simulations (id, simulation_type), simulation_runs (id, simulation_id) and
user_report_associations (id, user_id, country_id).

Two documented post-generation corrections: the new enum columns reuse the
existing types, and the unique constraints are created before the tables
that refer to them and dropped after them.

Privileges: the simulation service reads and inserts household run
variables, which the Modal worker and API v1's runtime role read; household
run calculations are granted as cliff_impacts are; API v1's runtime role
alone reads and writes the links. The v2 head is now 6ec3d17299b6, the
Alembic v2 check runs the new revision tests, and the Alembic skill doc
describes the revision.

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

Review round 1 found no bugs; this commit fixes its wording findings.

- The privilege manifest's role descriptions now include the household
  runs' variable lists and extra calculations.
- The three new models' docstrings say what a writer must do and what the
  database doesn't check, instead of describing later tasks' code as if it
  existed.
- Test text says "API v2" instead of a bare "v2".
- The Alembic skill doc's deploy notes describe the three tables the
  revision locks while it runs, and the deadlock it can cause with the
  simulation service.

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

Review round 2 found no bugs; this commit fixes its documentation findings.

- The deploy note on locks now says that blocked statements wait until the
  migration commits unless a statement timeout ends them first, that the
  wait also includes the migration's own waits for each lock, which no
  lock_timeout bounds, that any transaction reading or writing a simulation
  and then its runs can deadlock with it, and that PostgreSQL may abort the
  migration, which rolls back and can be run again. It drops a misleading
  comparison with revision 7dcd2cd14330.
- HouseholdRunCalculation's docstring and the privilege manifest describe
  joining a calculation and the household tables' writes as what the
  index and privileges allow, not as code that exists.

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

codecov Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.94%. Comparing base (57202c0) to head (cb8200d).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #4396      +/-   ##
==========================================
- Coverage   93.99%   93.94%   -0.05%     
==========================================
  Files         459      459              
  Lines       26259    26296      +37     
  Branches     4088     4090       +2     
==========================================
+ Hits        24682    24705      +23     
- Misses        901      907       +6     
- Partials      676      684       +8     
Flag Coverage Δ
integration 60.95% <100.00%> (+0.05%) ⬆️
unit 90.41% <100.00%> (-0.04%) ⬇️

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.

anth-volk and others added 2 commits December 3, 2026 22:38
tests/unit/v2/test_models.py's test_associations_are_v1_anchored_without_client_refs
still expected user_report_associations to have only (id, country_id) and
(id, report_id) unique, so it failed in CI once the change added
(id, user_id, country_id), which the household report links' keys
reference. It now expects all three; each includes the row's ID, so a merge
at sign-in can still move any row to another user.

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

Review round 3 found no bugs. Its documentation finding: the Stage 12A
user-login doc's "Conversion and merge" section still said no uniqueness on
the association tables involves the owner. Every uniqueness includes the
row's ID, which is why a merge never conflicts, and a household report link
takes the new owner through its keys' update cascade.

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

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

# Conflicts:
#	policyengine_api/data/v2/models/associations.py
#	tests/integration/test_v2_simulation_role_privileges.py
…tables branch

Master gained revision 24b571d7d079 (D1 · 8) on 7dcd2cd14330, the parent of
this branch's 6ec3d17299b6. The household run tables revision's down_revision
moves to 24b571d7d079, which makes it the one v2 head again; generating it
again from there gives the same operations apart from its two documented
corrections. The Alembic skill records the move, and the revision tests name
the new parent. The Alembic v2 check's file list and its test keep both
branches' files.

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

D1 · 5a removed UserReportRead's provisions field, and D1 · 8 brought in
test_export_answers_the_current_run_of_each_saved_report, which still passed
provisions=None, so the test failed with a TypeError once both were on
master.

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.

Add tables for household runs' variables and extra calculations, and household report links, to API v2

1 participant