Skip to content
Draft
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
4 changes: 3 additions & 1 deletion .github/scripts/test_alembic_v2_lifecycle.sh
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ uv run --frozen --extra dev pytest -q \
tests/unit/v2/test_alembic_v2_dynamic_revisions.py \
tests/unit/v2/test_alembic_v2_household_job_revisions.py \
tests/unit/v2/test_alembic_v2_report_revisions.py \
tests/unit/v2/test_alembic_v2_household_run_revisions.py \
tests/integration/test_alembic_v2_lifecycle.py \
tests/integration/test_alembic_v2_catalog_tables.py \
tests/integration/test_alembic_v2_simulation_runs.py \
Expand All @@ -25,4 +26,5 @@ uv run --frozen --extra dev pytest -q \
tests/integration/test_alembic_v2_inline_household_jobs.py \
tests/integration/test_alembic_v2_published_report_images.py \
tests/integration/test_alembic_v2_saved_report_current_runs.py \
tests/integration/test_alembic_v2_report_types.py
tests/integration/test_alembic_v2_report_types.py \
tests/integration/test_alembic_v2_household_run_tables.py
1 change: 1 addition & 0 deletions changelog.d/v2-household-run-tables.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
API v2's database stores the variables each household simulation run calculated, household runs' stored extra calculations, and links from an economy report's saved row to household reports' saved rows of the same owner and country.
119 changes: 119 additions & 0 deletions docs/engineering/skills/alembic-migrations.md
Original file line number Diff line number Diff line change
Expand Up @@ -2053,3 +2053,122 @@ which the Alembic v2 check runs, stores reports at the parent as the
simulation service stored them, checks the types the upgrade sets, compares
the revision and its downgrade with the parent schema, and checks each
refusal as the database's owner.

### API v2 household runs' tables and household report links

Revision `6ec3d17299b6` (parent `24b571d7d079`, ID chosen with `--rev-id`)
was autogenerated after `HouseholdRunVariables` and `HouseholdRunCalculation`
(`policyengine_api/data/v2/models/simulations.py`) and
`UserReportHouseholdReport` (`policyengine_api/data/v2/models/associations.py`)
were added (D2 · 3a). It was generated on `7dcd2cd14330`; when `master`
gained the report types revision `24b571d7d079` on the same parent, its
`down_revision` moved to `24b571d7d079`, and generating it again from there
gives the same operations. App v3 calculates a household report's default
view with the report's run, its other views with stored extra calculations of
each side's run, and keeps a saved economy report's households as saved
household reports linked to it. It adds three tables:

- `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 the revision did.
- `household_run_calculations`: one extra calculation of a household
simulation run, such as an earnings variation, and its result, modelled on
`cliff_impacts`. `variables` and `axes` (null for the household as entered)
are the request, `calculation_key` the SHA-256 of the two in the format
`key_version` names. `uq_household_run_calculations_unfailed`, a partial
unique index on `(simulation_run_id, key_version, calculation_key)` where
`status <> 'failed'` (also declared for SQLite), lets identical requests
join one calculation; a failed one never counts. It has the run tables'
completion check, a check that exactly a succeeded calculation has a
`result`, and an index on `(status, started_at)` for finding unfinished
calculations by age. The model writes an absent `axes` or `result` as SQL
NULL, not JSON `null`, which that check needs.
- `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`), with the owner (`user_id`) and country
(`country_id`) of both, at most once per pair (`uq_user_report_household_reports_link`),
never a row to itself (`ck_user_report_household_reports_two_rows`), and
indexed on `household_user_report_id`.

Both household tables carry `simulation_id` and `simulation_type`, with two
composite 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`. So the database accepts their rows only for a
household simulation's run, and deleting the run or its simulation deletes
them. PostgreSQL-only checks hold `variables` to a non-empty JSON array, and
`axes`, when set, to a JSON array. The link table's two keys,
`(user_report_id, user_id, country_id)` and `(household_user_report_id,
user_id, country_id)`, go to `user_report_associations (id, user_id,
country_id)`, both `ON DELETE CASCADE ON UPDATE CASCADE`: the database
refuses a link between two owners' or two countries' rows, and deleting
either row, or the owner, deletes the link. 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 (`reassign_user_associations`), and the update cascade
gives each link the new owner; without it, that update would fail on the
link's key. Deleting an economy report's saved row deletes only its links;
the household rows listed only under it are API v2's to delete. The
three keys' targets are new unique constraints: `uq_simulations_id_type`,
`uq_simulation_runs_id_simulation` and
`uq_user_report_associations_id_user_country`.

It has two post-generation corrections, commented in the revision:
`simulation_type` and `status` reuse the existing `v2_simulation_type` and
`v2_simulation_status` types (`postgresql.ENUM(..., create_type=False)`), as
`bc334f9877b7` does for `cliff_impacts.status`; and the three unique
constraints are created before the tables whose keys refer to them, and
dropped after those tables, where Alembic generated them after the tables in
the upgrade and before them in the downgrade, which PostgreSQL refuses. The
downgrade leaves the two types to the tables that still use them.

Privileges: the simulation service may read and insert
`household_run_variables`, and the Modal worker and API v1's runtime role may
read them; nobody may change or delete one. `household_run_calculations` is
granted as `cliff_impacts` is: the simulation service inserts a calculation
and records or fails its Modal call, the Modal worker claims it and writes its
state and `result`, API v1 reads it, and neither simulation role may change
the run or request a calculation names, or delete one. API v1's runtime role
alone reads, inserts, updates and deletes `user_report_household_reports`.

The revision writes no data and changes no column, and API v1's previous
release, which doesn't map the new tables, keeps working. The downgrade drops
the three tables, with every recorded variable list, calculation and link, and
the three constraints.

Deploying it:

- **The simulation service's models.** PolicyEngine/policyengine-sim-api
models `simulations` and `simulation_runs` and compares their constraints by
name with the tables this repository's `master` builds (its weekly
`public-api-schema-drift.yml`, and its pull requests' job at its pinned
commit). That weekly comparison fails once this revision is on `master`,
until its `Simulation` and `SimulationRun` gain `uq_simulations_id_type` and
`uq_simulation_runs_id_simulation`, which D2 · 3b adds together with its
models of the two household tables.
- **Locks while it runs.** The revision runs in one transaction, and each new
unique constraint takes an `ACCESS EXCLUSIVE` lock on its table to build its
index: `simulation_runs`, then `simulations`, then
`user_report_associations`. Each lock is held until the migration commits,
so every read and write of a locked table waits in a queue for that long:
the three index builds, plus however long the migration waits for each
next table's lock, which nothing bounds (it sets no `lock_timeout`).
Statements with a statement timeout fail once they reach it (API v1's is
set in `policyengine_api/data/v2/database.py`); statements without one,
such as some of the simulation service's and the Modal workers' updates of
`simulation_runs`, wait until the commit. A transaction that has already
used `simulations` and then needs `simulation_runs` can deadlock with the
migration: for example the simulation service inserting a simulation and
then its run, or an API v1 request that reads a simulation and then its
runs in one transaction. PostgreSQL then aborts one of the two
transactions; when it aborts the migration, the upgrade rolls back whole
and the deploy's migration step fails, and it can be run again. Deploy it
when few reports are running.

`tests/unit/v2/test_alembic_v2_household_run_revisions.py` checks the
revision file. `tests/integration/test_alembic_v2_household_run_tables.py`,
which the Alembic v2 check runs, compares the revision and its downgrade with
the parent schema and checks each refusal and cascade as the database's
owner, and that moving a browser's saved rows at sign-in moves their links. `tests/integration/test_v2_simulation_role_privileges.py` runs the
simulation service's and Modal workers' writes of the two household tables as
their roles.
8 changes: 6 additions & 2 deletions docs/migration/stage-12a-user-login.md
Original file line number Diff line number Diff line change
Expand Up @@ -465,10 +465,14 @@ unauthenticated: a signed-in user's row is never locked.
| No unauthenticated user with that ID | `none` | The identity's user is resolved, or provisioned, as on any request. |
| The ID names a signed-in user (already converted, or anyone else's) | `none` | That user is never touched; the identity's user is resolved as on any request. |

The association tables have no uniqueness involving the owner
Every uniqueness on the association tables includes the row's ID
(`client_ref` and its per-user constraints were removed), so a merge never
conflicts. Association IDs do not change, so a report's `user_policy_id` link
stays valid. `legacy_user_mappings` and `legacy_user_policy_mappings` belong
stays valid. All of the unauthenticated user's `user_report_associations`
rows move in one `UPDATE`, and a household report link
(`user_report_household_reports`) names its two saved reports together with
their owner through keys with `ON UPDATE CASCADE`, so the link takes the new
owner with them. `legacy_user_mappings` and `legacy_user_policy_mappings` belong
only to signed-in users and are untouched.

Concurrency on Postgres:
Expand Down
Loading
Loading