diff --git a/.github/scripts/test_alembic_v2_lifecycle.sh b/.github/scripts/test_alembic_v2_lifecycle.sh index 1085ad988..396622ab9 100755 --- a/.github/scripts/test_alembic_v2_lifecycle.sh +++ b/.github/scripts/test_alembic_v2_lifecycle.sh @@ -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 \ @@ -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 diff --git a/changelog.d/v2-household-run-tables.added.md b/changelog.d/v2-household-run-tables.added.md new file mode 100644 index 000000000..516e294a5 --- /dev/null +++ b/changelog.d/v2-household-run-tables.added.md @@ -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. diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 34c28b24c..216d6b0f7 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -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. diff --git a/docs/migration/stage-12a-user-login.md b/docs/migration/stage-12a-user-login.md index b3ab626ea..c8ce885bc 100644 --- a/docs/migration/stage-12a-user-login.md +++ b/docs/migration/stage-12a-user-login.md @@ -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: diff --git a/migrations/v2/versions/6ec3d17299b6_add_household_run_tables_and_household_.py b/migrations/v2/versions/6ec3d17299b6_add_household_run_tables_and_household_.py new file mode 100644 index 000000000..a5028a28c --- /dev/null +++ b/migrations/v2/versions/6ec3d17299b6_add_household_run_tables_and_household_.py @@ -0,0 +1,179 @@ +"""add household run tables and household report links + +Revision ID: 6ec3d17299b6 +Revises: 24b571d7d079 +Create Date: 2026-12-03 21:27:35.977414 +Generation: uv run alembic -c alembic-v2.ini revision --autogenerate --rev-id 6ec3d17299b6 + +Two post-generation corrections, commented where they are made: +- simulation_type and status reuse the existing v2_simulation_type and + v2_simulation_status types instead of creating them again, which would + fail; +- the three unique constraints are created before the tables whose keys + refer to them, and dropped after those tables, since PostgreSQL refuses a + key with no unique constraint to refer to, and refuses to drop one a key + needs. Generated, they came after the tables in the upgrade and before them + in the downgrade. + +Adds three tables (D2 · 3a): +- household_run_variables: the variables a household simulation run + calculated, one row per run; a household run with no row calculated every + variable; +- household_run_calculations: a household simulation run's stored extra + calculations and their results, with the state of each calculation's Modal + call. A partial unique index allows one calculation of each request that + hasn't failed, so identical requests join it; +- 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, which a check holds to 'household', so +they accept only household runs; deleting the run or the simulation deletes +their rows. Both link keys name a saved row together with the link's owner +and country, and cascade deletes and updates: deleting either row deletes the +link, and moving the rows to another owner, as signing in to an account that +already has a user does, 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). + +It 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 tables with +their rows, and the constraints; it leaves the two types, which simulations, +simulation_runs and cliff_impacts still use. +""" + +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +import sqlmodel +from sqlalchemy.dialects import postgresql + + +revision: str = '6ec3d17299b6' +down_revision: Union[str, None] = '24b571d7d079' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + # Order correction: the new tables' keys refer to these constraints, so + # they are created first. + op.create_unique_constraint('uq_simulation_runs_id_simulation', 'simulation_runs', ['id', 'simulation_id']) + op.create_unique_constraint('uq_simulations_id_type', 'simulations', ['id', 'simulation_type']) + op.create_unique_constraint('uq_user_report_associations_id_user_country', 'user_report_associations', ['id', 'user_id', 'country_id']) + op.create_table('household_run_calculations', + sa.Column('id', sa.Uuid(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False), + sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False), + sa.Column('simulation_run_id', sa.Uuid(), nullable=False), + sa.Column('simulation_id', sa.Uuid(), nullable=False), + sa.Column( + 'simulation_type', + # Dialect correction: the column reuses the existing + # v2_simulation_type type, which simulations uses, instead of + # creating it again, which would fail. + postgresql.ENUM( + 'household', + 'economy', + name='v2_simulation_type', + create_type=False, + ), + nullable=False, + ), + sa.Column('variables', sa.JSON(), nullable=False), + sa.Column('axes', sa.JSON(none_as_null=True), nullable=True), + sa.Column('key_version', sa.Integer(), nullable=False), + sa.Column('calculation_key', sqlmodel.sql.sqltypes.AutoString(length=64), nullable=False), + sa.Column( + 'status', + # Dialect correction: a calculation has a simulation run's states, so + # the column reuses the existing v2_simulation_status type instead of + # creating it again, which would fail. + postgresql.ENUM( + 'pending', + 'running', + 'succeeded', + 'failed', + name='v2_simulation_status', + create_type=False, + ), + nullable=False, + ), + sa.Column('modal_call_id', sqlmodel.sql.sqltypes.AutoString(length=255), nullable=True), + sa.Column('error_message', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('result', sa.JSON(none_as_null=True), nullable=True), + sa.Column('started_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('completed_at', sa.DateTime(timezone=True), nullable=True), + sa.CheckConstraint("(status = 'succeeded') = (result IS NOT NULL)", name=op.f('ck_household_run_calculations_result_when_succeeded')), + sa.CheckConstraint("CASE WHEN json_typeof(variables) = 'array' THEN json_array_length(variables) > 0 ELSE false END", name=op.f('ck_household_run_calculations_variables')), + sa.CheckConstraint("axes IS NULL OR json_typeof(axes) = 'array'", name=op.f('ck_household_run_calculations_axes')), + sa.CheckConstraint("length(calculation_key) = 64 AND ltrim(calculation_key, '0123456789abcdef') = ''", name=op.f('ck_household_run_calculations_calculation_key')), + sa.CheckConstraint("simulation_type = 'household'", name=op.f('ck_household_run_calculations_household')), + sa.CheckConstraint("status NOT IN ('succeeded', 'failed') OR completed_at IS NOT NULL", name=op.f('ck_household_run_calculations_finished_completion')), + sa.CheckConstraint('key_version > 0', name=op.f('ck_household_run_calculations_key_version')), + sa.ForeignKeyConstraint(['simulation_id', 'simulation_type'], ['simulations.id', 'simulations.simulation_type'], name='fk_household_run_calculations_simulation', ondelete='CASCADE'), + sa.ForeignKeyConstraint(['simulation_run_id', 'simulation_id'], ['simulation_runs.id', 'simulation_runs.simulation_id'], name='fk_household_run_calculations_run', ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id', name=op.f('pk_household_run_calculations')) + ) + op.create_index(op.f('ix_household_run_calculations_simulation_run_id'), 'household_run_calculations', ['simulation_run_id'], unique=False) + op.create_index('ix_household_run_calculations_status_started_at', 'household_run_calculations', ['status', 'started_at'], unique=False) + op.create_index('uq_household_run_calculations_unfailed', 'household_run_calculations', ['simulation_run_id', 'key_version', 'calculation_key'], unique=True, postgresql_where=sa.text("status <> 'failed'"), sqlite_where=sa.text("status <> 'failed'")) + op.create_table('household_run_variables', + sa.Column('simulation_run_id', sa.Uuid(), nullable=False), + sa.Column('simulation_id', sa.Uuid(), nullable=False), + sa.Column( + 'simulation_type', + # Dialect correction: the column reuses the existing + # v2_simulation_type type, which simulations uses, instead of + # creating it again, which would fail. + postgresql.ENUM( + 'household', + 'economy', + name='v2_simulation_type', + create_type=False, + ), + nullable=False, + ), + sa.Column('variables', sa.JSON(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False), + sa.CheckConstraint("CASE WHEN json_typeof(variables) = 'array' THEN json_array_length(variables) > 0 ELSE false END", name=op.f('ck_household_run_variables_variables')), + sa.CheckConstraint("simulation_type = 'household'", name=op.f('ck_household_run_variables_household')), + sa.ForeignKeyConstraint(['simulation_id', 'simulation_type'], ['simulations.id', 'simulations.simulation_type'], name='fk_household_run_variables_simulation', ondelete='CASCADE'), + sa.ForeignKeyConstraint(['simulation_run_id', 'simulation_id'], ['simulation_runs.id', 'simulation_runs.simulation_id'], name='fk_household_run_variables_run', ondelete='CASCADE'), + sa.PrimaryKeyConstraint('simulation_run_id', name=op.f('pk_household_run_variables')) + ) + op.create_table('user_report_household_reports', + sa.Column('id', sa.Uuid(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False), + sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False), + sa.Column('user_report_id', sa.Uuid(), nullable=False), + sa.Column('household_user_report_id', sa.Uuid(), nullable=False), + sa.Column('user_id', sa.Uuid(), nullable=False), + sa.Column('country_id', sqlmodel.sql.sqltypes.AutoString(length=2), nullable=False), + sa.CheckConstraint('user_report_id <> household_user_report_id', name=op.f('ck_user_report_household_reports_two_rows')), + sa.ForeignKeyConstraint(['household_user_report_id', 'user_id', 'country_id'], ['user_report_associations.id', 'user_report_associations.user_id', 'user_report_associations.country_id'], name='fk_user_report_household_reports_household_user_report', onupdate='CASCADE', ondelete='CASCADE'), + sa.ForeignKeyConstraint(['user_report_id', 'user_id', 'country_id'], ['user_report_associations.id', 'user_report_associations.user_id', 'user_report_associations.country_id'], name='fk_user_report_household_reports_user_report', onupdate='CASCADE', ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id', name=op.f('pk_user_report_household_reports')), + sa.UniqueConstraint('user_report_id', 'household_user_report_id', name='uq_user_report_household_reports_link') + ) + op.create_index(op.f('ix_user_report_household_reports_household_user_report_id'), 'user_report_household_reports', ['household_user_report_id'], unique=False) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_index(op.f('ix_user_report_household_reports_household_user_report_id'), table_name='user_report_household_reports') + op.drop_table('user_report_household_reports') + op.drop_table('household_run_variables') + op.drop_index('uq_household_run_calculations_unfailed', table_name='household_run_calculations', postgresql_where=sa.text("status <> 'failed'"), sqlite_where=sa.text("status <> 'failed'")) + op.drop_index('ix_household_run_calculations_status_started_at', table_name='household_run_calculations') + op.drop_index(op.f('ix_household_run_calculations_simulation_run_id'), table_name='household_run_calculations') + op.drop_table('household_run_calculations') + # Order correction: the dropped tables' keys needed these constraints, so + # they are dropped last. + op.drop_constraint('uq_user_report_associations_id_user_country', 'user_report_associations', type_='unique') + op.drop_constraint('uq_simulations_id_type', 'simulations', type_='unique') + op.drop_constraint('uq_simulation_runs_id_simulation', 'simulation_runs', type_='unique') + # ### end Alembic commands ### diff --git a/policyengine_api/data/v2/migration_target.py b/policyengine_api/data/v2/migration_target.py index d3fff7a6b..53842ce17 100644 --- a/policyengine_api/data/v2/migration_target.py +++ b/policyengine_api/data/v2/migration_target.py @@ -27,7 +27,7 @@ from sqlmodel import Session V2_ALEMBIC_DISPOSABLE_TEST = "V2_ALEMBIC_DISPOSABLE_TEST" -V2_ALEMBIC_HEAD_REVISION = "24b571d7d079" +V2_ALEMBIC_HEAD_REVISION = "6ec3d17299b6" DISPOSABLE_DATABASE_NAME = "policyengine_v2_alembic_test" DISPOSABLE_HOSTS = frozenset({"localhost", "127.0.0.1", "::1", "postgres"}) MIGRATION_ROLE = "policyengine_v2_migrator" diff --git a/policyengine_api/data/v2/models/__init__.py b/policyengine_api/data/v2/models/__init__.py index 313e3d265..f85b2f8d1 100644 --- a/policyengine_api/data/v2/models/__init__.py +++ b/policyengine_api/data/v2/models/__init__.py @@ -23,6 +23,7 @@ UserHouseholdAssociation, UserPolicy, UserReportAssociation, + UserReportHouseholdReport, UserReportRunAssociation, UserSimulationAssociation, ) @@ -104,6 +105,8 @@ WithheldAreaCode, ) from policyengine_api.data.v2.models.simulations import ( # noqa: E402 + HouseholdRunCalculation, + HouseholdRunVariables, Simulation, SimulationRun, SimulationStatus, @@ -157,6 +160,8 @@ "Household", "HouseholdJob", "HouseholdJobStatus", + "HouseholdRunCalculation", + "HouseholdRunVariables", "Inequality", "IntraDecileImpact", "LaborSupplyDecileResponse", @@ -204,6 +209,7 @@ "UserInvitation", "UserPolicy", "UserReportAssociation", + "UserReportHouseholdReport", "UserReportRunAssociation", "UserSimulationAssociation", "UserType", diff --git a/policyengine_api/data/v2/models/associations.py b/policyengine_api/data/v2/models/associations.py index eb91c9bc8..6ab239756 100644 --- a/policyengine_api/data/v2/models/associations.py +++ b/policyengine_api/data/v2/models/associations.py @@ -315,6 +315,10 @@ class UserReportAssociation(TimestampedModel, table=True): window, so only API v2's write check refuses one as its current run. Both are null for a saved report with no current run yet. + The unique ``(id, user_id, country_id)`` is what a household report link's + two keys refer to (``UserReportHouseholdReport``), so both saved reports a + link joins have one owner and one country. + A saved report keeps no copy of its reform's changes: its pages read the report's policy and dynamic records. The table's ``provisions`` column, where saved reports used to keep that copy, stays a SQLModel field, as rule @@ -370,6 +374,12 @@ class UserReportAssociation(TimestampedModel, table=True): " OR report_id IS NOT NULL", name="ck_user_report_associations_current_run_report", ), + sa.UniqueConstraint( + "id", + "user_id", + "country_id", + name="uq_user_report_associations_id_user_country", + ), sa.Index( "ix_user_reports_country_user_created_id", "country_id", @@ -439,6 +449,68 @@ class UserReportAssociation(TimestampedModel, table=True): user: User = Relationship(back_populates="report_associations") +# The saved report a link names, by its ID, owner and country. +_SAVED_REPORT_KEY_COLUMNS = ( + "user_report_associations.id", + "user_report_associations.user_id", + "user_report_associations.country_id", +) + + +class UserReportHouseholdReport(TimestampedModel, table=True): + """A household report's saved row, linked to an economy report's saved row. + + ``user_report_id`` is the saved row of an economy report or a budget + window, and ``household_user_report_id`` the saved row of a household + report shown with it, such as on its Household tab. A link joins saved + rows, never bare reports or households. Each is a foreign key together + with the link's ``user_id`` and ``country_id``, so both rows have that + owner and country. Both keys cascade deletes and updates: deleting either + row, or the owner, deletes the link, and moving the rows to another owner, + as signing in to an account that already has a user does, gives the link + that owner. The database can't check the rows' kinds, policies, dynamics + and years, since kinds live on ``reports``, so whatever writes a link must + check them. A link joins two different rows, at most once; a household + row may be linked under several economy rows. + """ + + __tablename__ = "user_report_household_reports" + __table_args__ = ( + # Named here: the naming convention's names are longer than + # PostgreSQL's 63-character limit. + sa.ForeignKeyConstraint( + ["user_report_id", "user_id", "country_id"], + list(_SAVED_REPORT_KEY_COLUMNS), + name="fk_user_report_household_reports_user_report", + ondelete="CASCADE", + onupdate="CASCADE", + ), + sa.ForeignKeyConstraint( + ["household_user_report_id", "user_id", "country_id"], + list(_SAVED_REPORT_KEY_COLUMNS), + name="fk_user_report_household_reports_household_user_report", + ondelete="CASCADE", + onupdate="CASCADE", + ), + sa.UniqueConstraint( + "user_report_id", + "household_user_report_id", + name="uq_user_report_household_reports_link", + ), + sa.CheckConstraint( + "user_report_id <> household_user_report_id", + name="ck_user_report_household_reports_two_rows", + ), + ) + + user_report_id: UUID + # Indexed for deleting a household report's saved row, which deletes its + # links, and for finding the rows linked under another. + household_user_report_id: UUID = Field(index=True) + user_id: UUID + country_id: str = Field(max_length=2) + + # A user asks for a report run by creating the report or by running it again; # a system re-run is nobody's request. _USER_REQUEST_TRIGGERS_SQL = ", ".join( diff --git a/policyengine_api/data/v2/models/simulations.py b/policyengine_api/data/v2/models/simulations.py index 28ba6b052..2a5f3d1b0 100644 --- a/policyengine_api/data/v2/models/simulations.py +++ b/policyengine_api/data/v2/models/simulations.py @@ -6,13 +6,14 @@ from uuid import UUID import sqlalchemy as sa -from sqlmodel import Field, Relationship +from sqlmodel import Field, Relationship, SQLModel from policyengine_api.data.v2.models.base import ( UNFAILED_UNFORCED_RUNS, TimestampedModel, enum_type, sha256_digest_check, + utc_now, ) from policyengine_api.data.v2.models.households import Household from policyengine_api.data.v2.models.metadata import ( @@ -63,6 +64,9 @@ class Simulation(TimestampedModel, table=True): selection, or its household), in the format ``key_version`` names; identical requests share the row. Simulations created before the keys have none and are never found by key. + + The unique ``(id, simulation_type)`` is what a household-only table's key + refers to, so that table accepts only household simulations' runs. """ __tablename__ = "simulations" @@ -89,6 +93,7 @@ class Simulation(TimestampedModel, table=True): "(key_version IS NULL) = (definition_key IS NULL)", name="ck_simulations_keys_complete", ), + sa.UniqueConstraint("id", "simulation_type", name="uq_simulations_id_type"), ) simulation_type: SimulationType = Field( @@ -180,6 +185,11 @@ class SimulationRun(TimestampedModel, table=True): version and pair of package versions, which identical requests join; a failed run never counts. ``forced`` marks a run a forced re-run created: an extra run, outside that rule, that nothing joins. + + The unique ``(id, simulation_id)`` is what a household-only table's key + refers to, together with its simulation's ``(id, simulation_type)``: a + household run's recorded variables (``HouseholdRunVariables``) and its + extra calculations (``HouseholdRunCalculation``). """ __tablename__ = "simulation_runs" @@ -211,6 +221,9 @@ class SimulationRun(TimestampedModel, table=True): "id", ), sa.Index("ix_simulation_runs_status_started_at", "status", "started_at"), + sa.UniqueConstraint( + "id", "simulation_id", name="uq_simulation_runs_id_simulation" + ), sa.Index( "uq_simulation_runs_unfailed_unforced_versions", "simulation_id", @@ -278,3 +291,174 @@ class SimulationRun(TimestampedModel, table=True): back_populates="simulation_run", cascade_delete=True, ) + + +# The calculations a new request may join: a failed one never counts. +UNFAILED_HOUSEHOLD_CALCULATIONS = "status <> 'failed'" + + +def _household_only_keys( + table_name: str, +) -> tuple[sa.ForeignKeyConstraint | sa.CheckConstraint, ...]: + """Keys and a check that hold a household-only table's row to a household run. + + The row names its run together with the run's simulation, and that + simulation together with its type, which must be ``household``. Deleting + the run or the simulation deletes the row. Named here: the naming + convention's names are longer than PostgreSQL's 63-character limit. + """ + return ( + sa.ForeignKeyConstraint( + ["simulation_run_id", "simulation_id"], + ["simulation_runs.id", "simulation_runs.simulation_id"], + name=f"fk_{table_name}_run", + ondelete="CASCADE", + ), + sa.ForeignKeyConstraint( + ["simulation_id", "simulation_type"], + ["simulations.id", "simulations.simulation_type"], + name=f"fk_{table_name}_simulation", + ondelete="CASCADE", + ), + sa.CheckConstraint( + "simulation_type = 'household'", name=f"ck_{table_name}_household" + ), + ) + + +def _variable_list_check(table_name: str) -> sa.CheckConstraint: + """Require ``variables`` to be a JSON array of at least one name. + + json_typeof and json_array_length are PostgreSQL's; SQLite, which only the + unit tests' copy of the schema uses, creates no such check. The CASE keeps + json_array_length from reading anything but an array. + """ + return sa.CheckConstraint( + "CASE WHEN json_typeof(variables) = 'array' " + "THEN json_array_length(variables) > 0 ELSE false END", + name=f"ck_{table_name}_variables", + ).ddl_if(dialect="postgresql") + + +class HouseholdRunVariables(SQLModel, table=True): + """The variables a household simulation run calculated, one row per run. + + A writer records the names a household report's request lists, sorted and + without repeats, when it creates the run; the database checks only that + they form a non-empty JSON array. A household run with no row calculated + every variable, as every run did before requests could list them. The + row is only for a household + simulation's run (``_household_only_keys``) and is deleted with it. + """ + + __tablename__ = "household_run_variables" + __table_args__ = ( + *_household_only_keys("household_run_variables"), + _variable_list_check("household_run_variables"), + ) + + simulation_run_id: UUID = Field(primary_key=True) + simulation_id: UUID + simulation_type: SimulationType = Field( + default=SimulationType.HOUSEHOLD, + sa_type=enum_type(SimulationType, "v2_simulation_type"), + ) + variables: list[str] = Field(sa_type=sa.JSON) + # Kept as the base models declare it, without the base's ``id``: the run's + # ID is this row's. + created_at: datetime = Field( + default_factory=utc_now, + sa_type=sa.DateTime(timezone=True), + sa_column_kwargs={"server_default": sa.func.now()}, + ) + + +class HouseholdRunCalculation(TimestampedModel, table=True): + """One extra calculation of a household simulation run, and its result. + + A household report's run calculates the variables its default view needs; + its other views ask for more, such as ``marginal_tax_rate`` or an earnings + variation, as extra calculations of each side's run. ``variables`` are + the sorted, distinct names to calculate, and ``axes`` the variation, or + null for the household as entered. ``calculation_key`` is the SHA-256 of + the two, in the format ``key_version`` names. The household, policy, + dynamic, year, catalog version and package versions are the run's, so a + writer should start a calculation only for a run on the current versions; + the database doesn't check that. + + As for a cliff calculation (``CliffImpact``), the simulation service may + insert a pending calculation and record its Modal call, or fail it when + Modal refuses the call; the Modal worker may claim it under its call, + then write the calculated household (``result``) with ``succeeded``, or + ``failed`` with its ``code: message`` error. The partial unique index + allows a run at most one calculation of each request that hasn't failed, + so a writer can have identical requests join it; a failed one doesn't + count, so a later request can start another. The + row is only for a household simulation's run (``_household_only_keys``) + and is deleted with it. This model writes an absent ``axes`` or + ``result`` as SQL NULL, not JSON ``null``. + """ + + __tablename__ = "household_run_calculations" + __table_args__ = ( + *_household_only_keys("household_run_calculations"), + _variable_list_check("household_run_calculations"), + sa.CheckConstraint( + "axes IS NULL OR json_typeof(axes) = 'array'", + name="ck_household_run_calculations_axes", + ).ddl_if(dialect="postgresql"), + sa.CheckConstraint( + "key_version > 0", name="ck_household_run_calculations_key_version" + ), + sha256_digest_check( + "calculation_key", "ck_household_run_calculations_calculation_key" + ), + sa.CheckConstraint( + "status NOT IN ('succeeded', 'failed') OR completed_at IS NOT NULL", + name="ck_household_run_calculations_finished_completion", + ), + sa.CheckConstraint( + "(status = 'succeeded') = (result IS NOT NULL)", + name="ck_household_run_calculations_result_when_succeeded", + ), + sa.Index( + "ix_household_run_calculations_status_started_at", "status", "started_at" + ), + sa.Index( + "uq_household_run_calculations_unfailed", + "simulation_run_id", + "key_version", + "calculation_key", + unique=True, + postgresql_where=sa.text(UNFAILED_HOUSEHOLD_CALCULATIONS), + sqlite_where=sa.text(UNFAILED_HOUSEHOLD_CALCULATIONS), + ), + ) + + simulation_run_id: UUID = Field(index=True) + simulation_id: UUID + simulation_type: SimulationType = Field( + default=SimulationType.HOUSEHOLD, + sa_type=enum_type(SimulationType, "v2_simulation_type"), + ) + variables: list[str] = Field(sa_type=sa.JSON) + axes: list[Any] | None = Field(default=None, sa_type=sa.JSON(none_as_null=True)) + key_version: int + calculation_key: str = Field(max_length=64) + status: SimulationStatus = Field( + default=SimulationStatus.PENDING, + sa_type=enum_type(SimulationStatus, "v2_simulation_status"), + ) + modal_call_id: str | None = Field(default=None, max_length=255) + error_message: str | None = None + result: dict[str, Any] | None = Field( + default=None, sa_type=sa.JSON(none_as_null=True) + ) + started_at: datetime | None = Field( + default=None, + sa_type=sa.DateTime(timezone=True), + ) + completed_at: datetime | None = Field( + default=None, + sa_type=sa.DateTime(timezone=True), + ) diff --git a/policyengine_api/data/v2/privileges.py b/policyengine_api/data/v2/privileges.py index cbe92bb4c..b26db4ab8 100644 --- a/policyengine_api/data/v2/privileges.py +++ b/policyengine_api/data/v2/privileges.py @@ -31,17 +31,20 @@ - ``policyengine_v2_simulation_service``: the simulation API on Cloud Run. It creates simulations, reports, their runs, budget-window runs, household jobs and simulation runs' cliff calculations, and reads the policy, - dynamic, household and catalog rows a run needs. It starts the Modal calls - of runs, household jobs and cliff calculations, so it may update their - status, Modal call ID, error and completion columns: it records a call's ID - once Modal accepts the call, and fails the run when Modal refuses it. It + dynamic, household and catalog rows a run needs; it may also create + household runs' variable lists and extra calculations. It starts the Modal + calls of runs, household jobs and cliff calculations, and may start those + of household runs' extra calculations, so it may update their status, + Modal call ID, error and completion columns: it records a call's ID once + Modal accepts the call, and fails the run when Modal refuses it. It starts a budget-window run's first years at submit, so it may update the window run's status, error and completion columns, to fail it at once when Modal refuses those years' calls. - ``policyengine_v2_modal_worker``: the simulation API's Modal workers. They write the status of the runs, household jobs and cliff calculations they - were given, and their results, and read the rows a run needs. They also - write a budget-window run's status, error and times: each year's + were given, and their results, and read the rows a run needs; they may + also write a household run's extra calculation's status and result. They + also write a budget-window run's status, error and times: each year's coordinator starts the window's next unstarted year when its own year finishes, the last year to finish marks the window succeeded, and a failed year fails it. They may also delete household jobs: a simulation API deploy @@ -289,6 +292,13 @@ def _run_table( # and the Modal worker claims it and writes its cliff gap and share. Neither # may change the run a calculation names. "cliff_impacts": _run_table("cliff_gap", "cliff_share"), + # The variables a household run calculated, which the simulation service + # records with the run and nobody changes; the Modal worker reads them. + "household_run_variables": _SIMULATION_DEFINITION, + # A household run's extra calculations, started and finished as cliff + # calculations are: the Modal worker claims one and writes its result. + # Neither may change the run or the request a calculation names. + "household_run_calculations": _run_table("result"), # Results of simulation runs and report runs. "labor_supply_decile_responses": _RESULT, "labor_supply_responses": _RESULT, @@ -376,6 +386,9 @@ def _run_table( "user_identities": _access(runtime=READ_WRITE), "user_policies": _access(runtime=READ_WRITE), "user_report_associations": _access(runtime=READ_WRITE), + # Household reports' saved rows linked to an economy report's saved row, + # which API v1 links, reads and unlinks. + "user_report_household_reports": _access(runtime=READ_WRITE), # Each user's request for a report run, which the Public API records when # the user creates or re-runs a report, reads, and deletes; nothing # changes one afterwards. diff --git a/tests/integration/privilege_statements.py b/tests/integration/privilege_statements.py index 3f80dc249..fb461adfb 100644 --- a/tests/integration/privilege_statements.py +++ b/tests/integration/privilege_statements.py @@ -21,7 +21,7 @@ from typing import Any from uuid import UUID -from sqlalchemy import ColumnElement, Update, bindparam, update +from sqlalchemy import JSON, ColumnElement, Update, bindparam, update from sqlalchemy.orm import Mapped, class_mapper, mapped_column, registry from sqlalchemy.types import TypeEngine from sqlmodel import SQLModel @@ -101,6 +101,29 @@ class CliffImpactColumns: cliff_gap: Mapped[float | None] +@named_column_tables.mapped +class HouseholdRunVariablesColumns: + """A household run's recorded variables, without its simulation's type.""" + + __tablename__ = "household_run_variables" + + simulation_run_id: Mapped[UUID] = mapped_column(primary_key=True) + simulation_id: Mapped[UUID] + variables: Mapped[list[str]] = mapped_column(JSON) + + +@named_column_tables.mapped +class HouseholdRunCalculationColumns: + """A new extra calculation of a household run, and its result.""" + + __tablename__ = "household_run_calculations" + + id: Mapped[UUID] = mapped_column(primary_key=True) + simulation_run_id: Mapped[UUID] + status: Mapped[str] = mapped_column(_type_of(CliffImpact, "status")) + result: Mapped[dict[str, Any] | None] = mapped_column(JSON) + + @named_column_tables.mapped class PovertyColumns: """A new poverty result's columns, without its values.""" diff --git a/tests/integration/simulation_rows.py b/tests/integration/simulation_rows.py index 5cd53148d..7bf1539cd 100644 --- a/tests/integration/simulation_rows.py +++ b/tests/integration/simulation_rows.py @@ -2,8 +2,9 @@ The statements run as whichever role the Session acts as, so a test can check what that role may do. Tests write inside a transaction they roll back. -``add_row`` writes one row of a mapped class, and ``refused`` expects the -statements inside it to fail. +``add_row`` writes one row of a mapped class, ``refused`` expects the +statements inside it to fail, and ``v2_model`` finds the mapped class of a +table by the table's name. """ from __future__ import annotations @@ -18,6 +19,7 @@ from sqlalchemy.exc import IntegrityError from sqlmodel import col +from policyengine_api.data.v2 import models as v2_models from policyengine_api.data.v2.models import ( Dataset, Household, @@ -52,6 +54,18 @@ def add_row(session: Session, model: type[Any], **values: object) -> None: session.execute(insert(model).values(**values)) +def v2_model(table_name: str) -> type[Any]: + """Return the API v2 model that maps ``table_name``; fail when none does.""" + mapped_classes = [ + value + for value in vars(v2_models).values() + if isinstance(value, type) + and getattr(value, "__tablename__", None) == table_name + ] + assert len(mapped_classes) == 1, f"one API v2 model should map {table_name}" + return mapped_classes[0] + + def insert_public_api_rows(session: Session) -> PublicApiRows: """Store a model, one of its versions, a dataset and a US household. diff --git a/tests/integration/test_alembic_v2_household_run_tables.py b/tests/integration/test_alembic_v2_household_run_tables.py new file mode 100644 index 000000000..070246118 --- /dev/null +++ b/tests/integration/test_alembic_v2_household_run_tables.py @@ -0,0 +1,756 @@ +"""Check the revision that adds household runs' tables and household report links. + +Revision 6ec3d17299b6, on 24b571d7d079, adds three tables, on disposable +Postgres here: + +- ``household_run_variables``: the variables a household simulation run + calculated, one row per run. A household run with no row calculated every + variable. +- ``household_run_calculations``: a household simulation run's stored extra + calculations and their results. Identical requests join one calculation + that hasn't failed; a failed one never counts. +- ``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 that +simulation together with its type, which must be ``household``, so the +database accepts them only for household runs; deleting the run or the +simulation deletes them. Deleting either saved row deletes its links, and +moving the saved rows to another owner, as signing in to an existing account +does, moves their links with them. The unique constraints ``simulations (id, +simulation_type)``, ``simulation_runs (id, simulation_id)`` and +``user_report_associations (id, user_id, country_id)`` are what those keys +refer to. Nothing else changes, and the downgrade removes exactly those. +""" + +from __future__ import annotations + +from datetime import UTC, datetime +from typing import TYPE_CHECKING, Any +from uuid import UUID, uuid4 + +import pytest +from alembic import command +from alembic.script import ScriptDirectory +from sqlalchemy import delete, func, select +from sqlalchemy.dialects import postgresql +from sqlmodel import col + +from policyengine_api.data.v2.models import ( + Simulation, + SimulationRun, + User, + UserReportAssociation, +) +from policyengine_api.data.v2.privileges import declared_privileges +from policyengine_api.services.v2.identity.database_connectors.updates import ( + reassign_user_associations, +) +from tests.fixtures.database_sessions import ( + grant_declared_v2_privileges, + schema_inspector, +) +from tests.fixtures.integration.alembic_v2 import alembic_v2_config +from tests.integration.simulation_rows import ( + RUN_VERSIONS, + PublicApiRows, + add_row, + insert_public_api_rows, + refused, + v2_model, +) + +if TYPE_CHECKING: + from collections.abc import Iterator + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + from tests.integration.conftest import ManagedV2Roles + +# The revision before it: saved reports' current runs. +PREVIOUS_REVISION = "24b571d7d079" +HOUSEHOLD_RUN_TABLES_REVISION = "6ec3d17299b6" +RUN_VARIABLES = "household_run_variables" +RUN_CALCULATIONS = "household_run_calculations" +HOUSEHOLD_REPORT_LINKS = "user_report_household_reports" +NEW_TABLES = frozenset({RUN_VARIABLES, RUN_CALCULATIONS, HOUSEHOLD_REPORT_LINKS}) +UNFAILED_CALCULATIONS = "(status <> 'failed'::v2_simulation_status)" +FINISHED_AT = datetime(2026, 12, 3, 9, tzinfo=UTC) +# A calculation's key: a SHA-256 digest, 64 lowercase hex digits. +CALCULATION_KEY = "ab" * 32 +OTHER_CALCULATION_KEY = "cd" * 32 +EARNINGS_VARIATION = [ + [{"name": "employment_income", "min": 0, "max": 200_000, "count": 401}] +] + + +def _revision_ids() -> set[str]: + """Return the ID of every revision in API v2's Alembic chain.""" + scripts = ScriptDirectory.from_config(alembic_v2_config()) + return {script.revision for script in scripts.walk_revisions()} + + +def _schema_shape(sessions: sessionmaker[Session]) -> dict[str, dict[str, Any]]: + """Reflect every table's columns, keys, unique constraints, indexes and checks.""" + with sessions() as session: + inspector = schema_inspector(session) + return { + table_name: { + "columns": { + column["name"]: ( + column["type"].compile(dialect=postgresql.dialect()), + column["nullable"], + column.get("default"), + ) + for column in inspector.get_columns(table_name) + }, + "primary_key": tuple( + inspector.get_pk_constraint(table_name)["constrained_columns"] + ), + "foreign_keys": { + key["name"]: ( + tuple(key["constrained_columns"]), + key["referred_table"], + tuple(key["referred_columns"]), + key["options"].get("ondelete"), + key["options"].get("onupdate"), + ) + for key in inspector.get_foreign_keys(table_name) + }, + "unique_constraints": { + unique["name"]: tuple(unique["column_names"]) + for unique in inspector.get_unique_constraints(table_name) + }, + "indexes": { + index["name"]: ( + tuple(index["column_names"]), + index["unique"], + index.get("dialect_options", {}).get("postgresql_where"), + ) + for index in inspector.get_indexes(table_name) + # A unique constraint's own index is listed with the constraints. + if "duplicates_constraint" not in index + }, + "checks": { + check["name"]: check["sqltext"] + for check in inspector.get_check_constraints(table_name) + }, + } + for table_name in inspector.get_table_names(schema="public") + if table_name != "alembic_version" + } + + +def _added(parent: dict[str, Any], revision: dict[str, Any]) -> dict[str, Any]: + """Return what the revision added to one part of a table; check it kept the rest.""" + assert {name: revision.get(name) for name in parent} == parent + return {name: value for name, value in revision.items() if name not in parent} + + +@pytest.fixture +def sessions( + v2_owner_sessions: sessionmaker[Session], + managed_v2_roles: ManagedV2Roles, + disposable_v2_database_url: str, +) -> Iterator[sessionmaker[Session]]: + """Yield the database owner's Session factories; leave the schema at head.""" + try: + yield v2_owner_sessions + finally: + command.upgrade(alembic_v2_config(), "head") + grant_declared_v2_privileges( + disposable_v2_database_url, + declared_privileges(managed_v2_roles.deployment_environment), + ) + + +@pytest.fixture +def session(sessions: sessionmaker[Session]) -> Iterator[Session]: + """Yield an owner's Session at head whose writes are rolled back afterwards.""" + command.upgrade(alembic_v2_config(), "head") + with sessions() as database_session: + try: + yield database_session + finally: + database_session.rollback() + + +def _check_new_tables(revision: dict[str, Any]) -> None: + """Check the three new tables' columns, keys, indexes and checks.""" + run_key = ("simulation_run_id", "simulation_id") + simulation_key = ("simulation_id", "simulation_type") + variables = revision[RUN_VARIABLES] + assert variables["columns"] == { + "simulation_run_id": ("UUID", False, None), + "simulation_id": ("UUID", False, None), + "simulation_type": ("v2_simulation_type", False, None), + "variables": ("JSON", False, None), + "created_at": ("TIMESTAMP WITH TIME ZONE", False, "now()"), + } + assert variables["primary_key"] == ("simulation_run_id",) + assert variables["foreign_keys"] == { + "fk_household_run_variables_run": ( + run_key, + "simulation_runs", + ("id", "simulation_id"), + "CASCADE", + None, + ), + "fk_household_run_variables_simulation": ( + simulation_key, + "simulations", + ("id", "simulation_type"), + "CASCADE", + None, + ), + } + assert set(variables["checks"]) == { + "ck_household_run_variables_household", + "ck_household_run_variables_variables", + } + assert variables["indexes"] == variables["unique_constraints"] == {} + + calculations = revision[RUN_CALCULATIONS] + assert calculations["columns"] == { + "id": ("UUID", False, None), + "created_at": ("TIMESTAMP WITH TIME ZONE", False, "now()"), + "updated_at": ("TIMESTAMP WITH TIME ZONE", False, "now()"), + "simulation_run_id": ("UUID", False, None), + "simulation_id": ("UUID", False, None), + "simulation_type": ("v2_simulation_type", False, None), + "variables": ("JSON", False, None), + "axes": ("JSON", True, None), + "key_version": ("INTEGER", False, None), + "calculation_key": ("VARCHAR(64)", False, None), + "status": ("v2_simulation_status", False, None), + "modal_call_id": ("VARCHAR(255)", True, None), + "error_message": ("VARCHAR", True, None), + "result": ("JSON", True, None), + "started_at": ("TIMESTAMP WITH TIME ZONE", True, None), + "completed_at": ("TIMESTAMP WITH TIME ZONE", True, None), + } + assert calculations["primary_key"] == ("id",) + assert calculations["foreign_keys"] == { + "fk_household_run_calculations_run": ( + run_key, + "simulation_runs", + ("id", "simulation_id"), + "CASCADE", + None, + ), + "fk_household_run_calculations_simulation": ( + simulation_key, + "simulations", + ("id", "simulation_type"), + "CASCADE", + None, + ), + } + assert calculations["indexes"] == { + "ix_household_run_calculations_simulation_run_id": ( + ("simulation_run_id",), + False, + None, + ), + "ix_household_run_calculations_status_started_at": ( + ("status", "started_at"), + False, + None, + ), + "uq_household_run_calculations_unfailed": ( + ("simulation_run_id", "key_version", "calculation_key"), + True, + UNFAILED_CALCULATIONS, + ), + } + assert calculations["unique_constraints"] == {} + assert set(calculations["checks"]) == { + "ck_household_run_calculations_household", + "ck_household_run_calculations_variables", + "ck_household_run_calculations_axes", + "ck_household_run_calculations_key_version", + "ck_household_run_calculations_calculation_key", + "ck_household_run_calculations_finished_completion", + "ck_household_run_calculations_result_when_succeeded", + } + + links = revision[HOUSEHOLD_REPORT_LINKS] + assert links["columns"] == { + "id": ("UUID", False, None), + "created_at": ("TIMESTAMP WITH TIME ZONE", False, "now()"), + "updated_at": ("TIMESTAMP WITH TIME ZONE", False, "now()"), + "user_report_id": ("UUID", False, None), + "household_user_report_id": ("UUID", False, None), + "user_id": ("UUID", False, None), + "country_id": ("VARCHAR(2)", False, None), + } + assert links["primary_key"] == ("id",) + assert links["foreign_keys"] == { + "fk_user_report_household_reports_user_report": ( + ("user_report_id", "user_id", "country_id"), + "user_report_associations", + ("id", "user_id", "country_id"), + "CASCADE", + "CASCADE", + ), + "fk_user_report_household_reports_household_user_report": ( + ("household_user_report_id", "user_id", "country_id"), + "user_report_associations", + ("id", "user_id", "country_id"), + "CASCADE", + "CASCADE", + ), + } + assert links["unique_constraints"] == { + "uq_user_report_household_reports_link": ( + "user_report_id", + "household_user_report_id", + ) + } + assert links["indexes"] == { + "ix_user_report_household_reports_household_user_report_id": ( + ("household_user_report_id",), + False, + None, + ) + } + assert set(links["checks"]) == {"ck_user_report_household_reports_two_rows"} + + +def test_the_revision_adds_the_household_run_tables_and_downgrades_exactly( + sessions: sessionmaker[Session], +) -> None: + assert HOUSEHOLD_RUN_TABLES_REVISION in _revision_ids() + config = alembic_v2_config() + command.upgrade(config, "head") + command.downgrade(config, PREVIOUS_REVISION) + parent = _schema_shape(sessions) + command.upgrade(config, HOUSEHOLD_RUN_TABLES_REVISION) + revision = _schema_shape(sessions) + command.downgrade(config, PREVIOUS_REVISION) + downgraded = _schema_shape(sessions) + + assert set(revision) == set(parent) | NEW_TABLES + assert sorted( + table_name + for table_name in parent + if revision[table_name] != parent[table_name] + ) == ["simulation_runs", "simulations", "user_report_associations"] + for table_name, constraint_name, columns in ( + ("simulations", "uq_simulations_id_type", ("id", "simulation_type")), + ( + "simulation_runs", + "uq_simulation_runs_id_simulation", + ("id", "simulation_id"), + ), + ( + "user_report_associations", + "uq_user_report_associations_id_user_country", + ("id", "user_id", "country_id"), + ), + ): + before, after = parent[table_name], revision[table_name] + assert _added(before["unique_constraints"], after["unique_constraints"]) == { + constraint_name: columns + } + for part in ("columns", "primary_key", "foreign_keys", "indexes", "checks"): + assert after[part] == before[part], (table_name, part) + _check_new_tables(revision) + assert downgraded == parent + + +def _store_simulation_with_run( + session: Session, public_api_rows: PublicApiRows, simulation_type: str +) -> dict[str, UUID]: + """Store a household or economy simulation of 2026 and one succeeded run of it.""" + ids = {"simulation": uuid4(), "run": uuid4()} + inputs = ( + {"household_id": public_api_rows.household_id} + if simulation_type == "household" + else {"dataset_id": public_api_rows.dataset_id} + ) + add_row( + session, + Simulation, + id=ids["simulation"], + simulation_type=simulation_type, + tax_benefit_model_version_id=public_api_rows.version_id, + year=2026, + **inputs, + ) + add_row( + session, + SimulationRun, + id=ids["run"], + simulation_id=ids["simulation"], + tax_benefit_model_version_id=public_api_rows.version_id, + year=2026, + status="succeeded", + completed_at=FINISHED_AT, + **RUN_VERSIONS, + ) + return ids + + +def _calculation(run: dict[str, UUID], **values: object) -> dict[str, object]: + """Build a pending earnings variation calculation of ``run``, with ``values``.""" + return { + "id": uuid4(), + "simulation_run_id": run["run"], + "simulation_id": run["simulation"], + "simulation_type": "household", + "variables": ["employment_income", "household_net_income"], + "axes": EARNINGS_VARIATION, + "key_version": 1, + "calculation_key": CALCULATION_KEY, + "status": "pending", + } | values + + +def _count(session: Session, model: type[Any], *conditions: Any) -> int: + """Count the model's rows that meet ``conditions``.""" + return session.execute( + select(func.count()).select_from(model).where(*conditions) + ).scalar_one() + + +def test_the_household_run_tables_accept_only_household_runs( + session: Session, +) -> None: + run_variables = v2_model(RUN_VARIABLES) + run_calculations = v2_model(RUN_CALCULATIONS) + public_api_rows = insert_public_api_rows(session) + household = _store_simulation_with_run(session, public_api_rows, "household") + other_household = _store_simulation_with_run(session, public_api_rows, "household") + economy = _store_simulation_with_run(session, public_api_rows, "economy") + household_row = { + "simulation_run_id": household["run"], + "simulation_id": household["simulation"], + "simulation_type": "household", + } + + # Each write, with the constraint that refuses it. + for model, constraint, refused_values in ( + # An economy run, named as a household simulation's. + ( + run_variables, + "fk_household_run_variables_simulation", + { + "simulation_run_id": economy["run"], + "simulation_id": economy["simulation"], + "simulation_type": "household", + "variables": ["household_net_income"], + }, + ), + # An economy run, named as what it is. + ( + run_variables, + "ck_household_run_variables_household", + { + "simulation_run_id": economy["run"], + "simulation_id": economy["simulation"], + "simulation_type": "economy", + "variables": ["household_net_income"], + }, + ), + # A household run, named with another simulation. + ( + run_variables, + "fk_household_run_variables_run", + household_row + | { + "simulation_id": other_household["simulation"], + "variables": ["household_net_income"], + }, + ), + ( + run_variables, + "ck_household_run_variables_variables", + household_row | {"variables": []}, + ), + ( + run_variables, + "ck_household_run_variables_variables", + household_row | {"variables": {"household_net_income": True}}, + ), + ( + run_calculations, + "fk_household_run_calculations_simulation", + _calculation(economy), + ), + ( + run_calculations, + "ck_household_run_calculations_household", + _calculation(economy, simulation_type="economy"), + ), + ( + run_calculations, + "fk_household_run_calculations_run", + _calculation(household, simulation_id=other_household["simulation"]), + ), + ( + run_calculations, + "ck_household_run_calculations_variables", + _calculation(household, variables=[]), + ), + ( + run_calculations, + "ck_household_run_calculations_axes", + _calculation(household, axes={"name": "employment_income"}), + ), + ( + run_calculations, + "ck_household_run_calculations_key_version", + _calculation(household, key_version=0), + ), + ( + run_calculations, + "ck_household_run_calculations_calculation_key", + _calculation(household, calculation_key="AB" * 32), + ), + ): + with refused(session, match=constraint): + add_row(session, model, **refused_values) + + add_row( + session, + run_variables, + **household_row, + variables=["household_net_income", "household_tax"], + ) + stored = session.execute( + select(col(run_variables.variables)).where( + col(run_variables.simulation_run_id) == household["run"] + ) + ).scalar_one() + assert stored == ["household_net_income", "household_tax"] + with refused(session, match="pk_household_run_variables"): + add_row(session, run_variables, **household_row, variables=["household_tax"]) + + +def test_a_household_run_has_one_unfailed_calculation_per_request( + session: Session, +) -> None: + """Identical requests join one calculation, and a failed one never counts. + + A succeeded or failed calculation has its completion time, and exactly a + succeeded one has a result. Deleting the run, or its simulation, deletes + its calculations and its variables. + """ + run_calculations = v2_model(RUN_CALCULATIONS) + run_variables = v2_model(RUN_VARIABLES) + public_api_rows = insert_public_api_rows(session) + household = _store_simulation_with_run(session, public_api_rows, "household") + other_household = _store_simulation_with_run(session, public_api_rows, "household") + + add_row(session, run_calculations, **_calculation(household)) + with refused(session, match="uq_household_run_calculations_unfailed"): + add_row(session, run_calculations, **_calculation(household)) + # Another request of the same run, and the same request of another run. + add_row( + session, + run_calculations, + **_calculation(household, calculation_key=OTHER_CALCULATION_KEY, axes=None), + ) + add_row(session, run_calculations, **_calculation(other_household)) + # A failed calculation never counts. + add_row( + session, + run_calculations, + **_calculation( + household, + status="failed", + error_message="household_failed: the calculation failed", + completed_at=FINISHED_AT, + ), + ) + for constraint, refused_values in ( + ( + "ck_household_run_calculations_finished_completion", + {"status": "failed", "error_message": "household_failed: failed"}, + ), + ( + "ck_household_run_calculations_result_when_succeeded", + {"status": "succeeded", "completed_at": FINISHED_AT}, + ), + ( + "ck_household_run_calculations_result_when_succeeded", + {"status": "running", "result": {"people": {}}}, + ), + ): + with refused(session, match=constraint): + add_row( + session, + run_calculations, + **_calculation(household, calculation_key="ef" * 32, **refused_values), + ) + add_row( + session, + run_calculations, + **_calculation( + household, + calculation_key="ef" * 32, + status="succeeded", + completed_at=FINISHED_AT, + result={"people": {"you": {"household_net_income": {"2026": [0.0]}}}}, + ), + ) + add_row( + session, + run_variables, + simulation_run_id=household["run"], + simulation_id=household["simulation"], + variables=["household_net_income"], + ) + add_row( + session, + run_variables, + simulation_run_id=other_household["run"], + simulation_id=other_household["simulation"], + variables=["household_net_income"], + ) + + run_rows = col(run_calculations.simulation_run_id) + assert _count(session, run_calculations, run_rows == household["run"]) == 4 + session.execute( + delete(SimulationRun).where(col(SimulationRun.id) == household["run"]) + ) + session.execute( + delete(Simulation).where(col(Simulation.id) == other_household["simulation"]) + ) + for model in (run_calculations, run_variables): + assert _count(session, model) == 0, model.__tablename__ + + +def _store_saved_report(session: Session, user_id: UUID, country_id: str) -> UUID: + """Store a user's saved row of an API v1 report output in ``country_id``.""" + saved_report_id = uuid4() + add_row( + session, + UserReportAssociation, + id=saved_report_id, + user_id=user_id, + country_id=country_id, + legacy_report_id=615, + ) + return saved_report_id + + +def _store_user(session: Session) -> UUID: + user_id = uuid4() + add_row(session, User, id=user_id, user_type="unauthenticated") + return user_id + + +def test_links_join_one_owners_saved_reports_in_one_country( + session: Session, +) -> None: + """A link joins two saved rows of one owner and country, at most once. + + Deleting either row deletes the link, and so does deleting the owner. + """ + links = v2_model(HOUSEHOLD_REPORT_LINKS) + owner = _store_user(session) + other_user = _store_user(session) + economy_row = _store_saved_report(session, owner, "us") + household_row = _store_saved_report(session, owner, "us") + second_household_row = _store_saved_report(session, owner, "us") + uk_row = _store_saved_report(session, owner, "uk") + other_users_row = _store_saved_report(session, other_user, "us") + + def link(parent: UUID, child: UUID, **values: object) -> dict[str, object]: + return { + "id": uuid4(), + "user_report_id": parent, + "household_user_report_id": child, + "user_id": owner, + "country_id": "us", + } | values + + for constraint, refused_values in ( + # Another user's row, under the owner's and under the other user's ID. + ( + "fk_user_report_household_reports_household_user_report", + link(economy_row, other_users_row), + ), + ( + "fk_user_report_household_reports_user_report", + link(economy_row, other_users_row, user_id=other_user), + ), + # A row of another country. + ( + "fk_user_report_household_reports_household_user_report", + link(economy_row, uk_row), + ), + ( + "fk_user_report_household_reports_user_report", + link(economy_row, uk_row, country_id="uk"), + ), + ("ck_user_report_household_reports_two_rows", link(economy_row, economy_row)), + ): + with refused(session, match=constraint): + add_row(session, links, **refused_values) + + add_row(session, links, **link(economy_row, household_row)) + add_row(session, links, **link(economy_row, second_household_row)) + with refused(session, match="uq_user_report_household_reports_link"): + add_row(session, links, **link(economy_row, household_row)) + assert _count(session, links) == 2 + + session.execute( + delete(UserReportAssociation).where( + col(UserReportAssociation.id) == household_row + ) + ) + assert session.execute( + select(col(links.household_user_report_id)) + ).scalars().all() == [second_household_row] + session.execute( + delete(UserReportAssociation).where( + col(UserReportAssociation.id) == economy_row + ) + ) + assert _count(session, links) == 0 + add_row( + session, + links, + **link(_store_saved_report(session, owner, "us"), second_household_row), + ) + session.execute(delete(User).where(col(User.id) == owner)) + assert _count(session, links) == 0 + + +def test_signing_in_moves_links_with_their_saved_reports(session: Session) -> None: + """Moving a browser's saved rows into an account moves their links too. + + Signing in to an account that already has a user moves each of the + browser's saved rows to that user, one update per table. Each link names + its rows together with their owner, so it takes the new owner with them. + """ + links = v2_model(HOUSEHOLD_REPORT_LINKS) + browser_user = _store_user(session) + account_user = _store_user(session) + economy_row = _store_saved_report(session, browser_user, "us") + household_row = _store_saved_report(session, browser_user, "us") + add_row( + session, + links, + id=uuid4(), + user_report_id=economy_row, + household_user_report_id=household_row, + user_id=browser_user, + country_id="us", + ) + + reassign_user_associations( + session, from_user_id=browser_user, to_user_id=account_user + ) + + assert session.execute( + select( + col(links.user_report_id), + col(links.household_user_report_id), + col(links.user_id), + ) + ).all() == [(economy_row, household_row, account_user)] diff --git a/tests/integration/test_alembic_v2_lifecycle.py b/tests/integration/test_alembic_v2_lifecycle.py index 892d8a4b9..cfef16494 100644 --- a/tests/integration/test_alembic_v2_lifecycle.py +++ b/tests/integration/test_alembic_v2_lifecycle.py @@ -370,16 +370,17 @@ def _assert_stage_12a_association_shape(sessions: sessionmaker[Session]) -> None assert columns[f"legacy_{reference}_id"]["nullable"] assert not columns["country_id"]["nullable"] assert "client_ref" not in columns - # No uniqueness involves the owner, so a merge can move any row. A - # saved report's (id, report_id) is what a published report's key - # references. + # Each uniqueness includes the row's ID, so a merge can move any row. + # A saved report's (id, report_id) is what a published report's key + # references, and its (id, user_id, country_id) what a household + # report link's keys reference. assert sorted( constraint["column_names"] for constraint in schema_inspector(sessions).get_unique_constraints( table_name ) ) == ( - [["id", "country_id"], ["id", "report_id"]] + [["id", "country_id"], ["id", "report_id"], ["id", "user_id", "country_id"]] if reference == "report" else [["id", "country_id"]] ) diff --git a/tests/integration/test_alembic_v2_simulation_runs.py b/tests/integration/test_alembic_v2_simulation_runs.py index 8c4b01d7b..0b8f497c9 100644 --- a/tests/integration/test_alembic_v2_simulation_runs.py +++ b/tests/integration/test_alembic_v2_simulation_runs.py @@ -88,12 +88,19 @@ } ) # The tables the simulation service and its Modal workers write; API v1 -# writes every other table. withheld_area_codes and cliff_impacts came in later -# revisions. +# writes every other table. withheld_area_codes, cliff_impacts and the two +# household run tables came in later revisions. SIMULATION_SIDE_TABLES = ( CHANGED_TABLES | NEW_TABLES - | {"aggregates", "change_aggregates", "withheld_area_codes", "cliff_impacts"} + | { + "aggregates", + "change_aggregates", + "withheld_area_codes", + "cliff_impacts", + "household_run_variables", + "household_run_calculations", + } ) # The foreign keys from the simulation service's tables to API v1's # rows, with their delete rules. @@ -262,6 +269,7 @@ def test_head_keeps_the_foreign_keys_to_the_public_api_tables( """Each service writes only its own tables; the keys between them stay.""" command.upgrade(config, "head") inspector = schema_inspector(sessions) + assert set(inspector.get_table_names(schema="public")) >= SIMULATION_SIDE_TABLES public_api_keys = { (table_name, column_name): (key["referred_table"], key["options"]["ondelete"]) diff --git a/tests/integration/test_v2_simulation_role_privileges.py b/tests/integration/test_v2_simulation_role_privileges.py index 0047e2c50..22b97b8a2 100644 --- a/tests/integration/test_v2_simulation_role_privileges.py +++ b/tests/integration/test_v2_simulation_role_privileges.py @@ -1,8 +1,9 @@ """Run the simulation tables' writes as the roles that do them in production. The simulation service creates simulations, reports, their runs, budget-window -runs, household jobs and simulation runs' cliff calculations; its Modal -workers write their runs' and cliff calculations' status and results and their +runs, household jobs, simulation runs' cliff calculations, the variables each +household run calculated and household runs' extra calculations; its Modal +workers write their runs' and calculations' status and results and their budget-window runs' status, and delete the finished jobs of households sent in the request when a deploy changes versions; API v1 reads them. Each role holds only its declared privileges (``policyengine_api/data/v2/privileges.py``), so @@ -17,8 +18,9 @@ ``updated_at``, go through ``tests.integration.privilege_statements``' classes, which map only the columns they name. The other refused updates use the models: both simulation roles may update ``updated_at`` on the run, budget-window -run and cliff calculation tables, and ``poverty`` and ``withheld_area_codes`` -have no ``updated_at``. A column a model's mapper leaves out +run, cliff calculation and household run calculation tables, and ``poverty``, +``withheld_area_codes`` and ``household_run_variables`` have no +``updated_at``. A column a model's mapper leaves out (``exclude_properties``) has no statement through the model, so its writes and refusals would go through a class that maps it; since revision ``4e30076d4b9f`` no model of the simulation tables leaves a column out. @@ -64,6 +66,8 @@ BudgetWindowRunColumns, CliffImpactColumns, HouseholdColumns, + HouseholdRunCalculationColumns, + HouseholdRunVariablesColumns, LaborSupplyDecileResponseColumns, PolicyColumns, PovertyColumns, @@ -79,6 +83,7 @@ add_row, insert_public_api_rows, refused, + v2_model, ) if TYPE_CHECKING: @@ -640,6 +645,8 @@ def test_each_simulation_role_updates_exactly_its_declared_columns( HouseholdJob, BudgetWindowRun, CliffImpact, + v2_model("household_run_calculations"), + v2_model("household_run_variables"), ): updatable = { column @@ -876,3 +883,248 @@ def test_only_the_modal_workers_delete_household_jobs( deleted = session.execute(deletion.returning(col(HouseholdJob.id))).scalars() assert list(deleted) == [job_id] + + +# The earnings variation a household run's extra calculation asks for. +EARNINGS_VARIATION = [ + [{"name": "employment_income", "min": 0, "max": 200_000, "count": 401}] +] +CALCULATION_KEY = "ab" * 32 + + +def _create_household_run( + session: Session, public_api_rows: PublicApiRows +) -> dict[str, UUID]: + """Create a household simulation and a pending run of it, as the service does.""" + ids = {"simulation": uuid4(), "run": uuid4()} + add_row( + session, + Simulation, + id=ids["simulation"], + simulation_type="household", + household_id=public_api_rows.household_id, + tax_benefit_model_version_id=public_api_rows.version_id, + year=2026, + ) + add_row( + session, + SimulationRun, + id=ids["run"], + simulation_id=ids["simulation"], + tax_benefit_model_version_id=public_api_rows.version_id, + year=2026, + status="pending", + **RUN_VERSIONS, + ) + return ids + + +def test_the_simulation_service_records_the_variables_a_household_run_calculates( + session: Session, managed_v2_roles: ManagedV2Roles, public_api_rows: PublicApiRows +) -> None: + """The service inserts a household run's variables once; nobody changes them. + + The Modal worker and API v1 read them; the catalog writer and the Stage + 12 role can't. + """ + run_variables = v2_model("household_run_variables") + act_as(session, managed_v2_roles.simulation_service) + ids = _create_household_run(session, public_api_rows) + add_row( + session, + run_variables, + simulation_run_id=ids["run"], + simulation_id=ids["simulation"], + simulation_type="household", + variables=["household_net_income"], + ) + this_run = col(run_variables.simulation_run_id) == ids["run"] + + for role in ( + managed_v2_roles.simulation_service, + managed_v2_roles.modal_worker, + managed_v2_roles.runtime, + ): + act_as(session, role) + assert session.execute( + select(col(run_variables.variables)).where(this_run) + ).scalar_one() == ["household_net_income"] + for statement in ( + update(HouseholdRunVariablesColumns) + .where(col(HouseholdRunVariablesColumns.simulation_run_id) == ids["run"]) + .values(variables=["household_tax"]), + delete(run_variables).where(this_run), + ): + _refused(session, statement) + for role in (managed_v2_roles.modal_worker, managed_v2_roles.runtime): + act_as(session, role) + _refused( + session, + insert(HouseholdRunVariablesColumns).values( + simulation_run_id=uuid4(), + simulation_id=ids["simulation"], + variables=["household_tax"], + ), + ) + for role in (managed_v2_roles.stage12, CATALOG_WRITER_ROLE): + act_as(session, role) + _refused(session, _row_count(run_variables)) + + +def _start_household_calculation( + session: Session, run_ids: dict[str, UUID] +) -> UUID | None: + """Start the run's earnings variation, unless one that hasn't failed exists. + + This is what the simulation service inserts; return the new calculation's + ID, or None. Identical requests share the run and the key, and the + partial unique index's condition is sent as a literal, as in the index. + """ + run_calculations = v2_model("household_run_calculations") + return session.execute( + postgresql.insert(run_calculations) + .values( + id=uuid4(), + simulation_run_id=run_ids["run"], + simulation_id=run_ids["simulation"], + simulation_type="household", + variables=["employment_income", "household_net_income"], + axes=EARNINGS_VARIATION, + key_version=1, + calculation_key=CALCULATION_KEY, + status="pending", + ) + .on_conflict_do_nothing( + index_elements=[ + col(run_calculations.simulation_run_id), + col(run_calculations.key_version), + col(run_calculations.calculation_key), + ], + index_where=unfailed(col(run_calculations.status), SimulationStatus.FAILED), + ) + .returning(col(run_calculations.id)) + ).scalar_one_or_none() + + +def test_the_simulation_service_starts_household_run_calculations( + session: Session, managed_v2_roles: ManagedV2Roles, public_api_rows: PublicApiRows +) -> None: + """The service inserts a calculation once per request, and records or fails it. + + It never claims a calculation, writes its result, changes the run or the + request it calculates or deletes it. + """ + run_calculations = v2_model("household_run_calculations") + act_as(session, managed_v2_roles.simulation_service) + ids = _create_household_run(session, public_api_rows) + + calculation_id = _start_household_calculation(session, ids) + joined_calculation = _start_household_calculation(session, ids) + recorded = session.execute( + update(run_calculations) + .where( + col(run_calculations.id) == calculation_id, + col(run_calculations.status) == "pending", + col(run_calculations.modal_call_id).is_(None), + ) + .values(modal_call_id="fc-household", updated_at=func.now()) + .returning(col(run_calculations.id)) + ).scalar_one() + failed = _update_from_status( + session, + run_calculations, + calculation_id, + "pending", + status="failed", + error_message="modal_refused: refused", + completed_at=func.now(), + updated_at=func.now(), + ) + + assert calculation_id is not None + assert joined_calculation is None + assert recorded == failed == calculation_id + for statement in ( + update_row(run_calculations, calculation_id, started_at=func.now()), + update_row(run_calculations, calculation_id, result={"people": {}}), + update_row( + run_calculations, + calculation_id, + simulation_run_id=col(run_calculations.simulation_run_id), + ), + update_row(run_calculations, calculation_id, variables=["household_tax"]), + delete(run_calculations).where(col(run_calculations.id) == calculation_id), + ): + _refused(session, statement) + + +def test_modal_workers_claim_household_run_calculations_and_write_results( + session: Session, managed_v2_roles: ManagedV2Roles, public_api_rows: PublicApiRows +) -> None: + """A worker claims a pending calculation under its call and finishes it. + + It never inserts a calculation, changes the run or request it calculates + or deletes one. API v1 reads the result and writes nothing; the catalog + writer and the Stage 12 role can't read it. + """ + run_calculations = v2_model("household_run_calculations") + act_as(session, managed_v2_roles.simulation_service) + ids = _create_household_run(session, public_api_rows) + calculation_id = _start_household_calculation(session, ids) + act_as(session, managed_v2_roles.modal_worker) + result = {"people": {"you": {"household_net_income": {"2026": [0.0, 1.0]}}}} + + claimed = _update_from_status( + session, + run_calculations, + calculation_id, + "pending", + status="running", + started_at=func.now(), + modal_call_id="fc-household", + updated_at=func.now(), + ) + succeeded = _update_from_status( + session, + run_calculations, + calculation_id, + "running", + status="succeeded", + result=result, + completed_at=func.now(), + updated_at=func.now(), + ) + + assert claimed == succeeded == calculation_id + new_calculation = insert(HouseholdRunCalculationColumns).values( + id=uuid4(), simulation_run_id=ids["run"], status="pending" + ) + for statement in ( + new_calculation, + update_row( + run_calculations, + calculation_id, + simulation_run_id=col(run_calculations.simulation_run_id), + ), + update_row(run_calculations, calculation_id, axes=None), + delete(run_calculations).where(col(run_calculations.id) == calculation_id), + ): + _refused(session, statement) + act_as(session, managed_v2_roles.runtime) + assert ( + session.execute( + select(col(run_calculations.result)).where( + col(run_calculations.simulation_run_id) == ids["run"], + col(run_calculations.status) == "succeeded", + ) + ).scalar_one() + == result + ) + _refused(session, new_calculation) + _refused( + session, + update_row(HouseholdRunCalculationColumns, calculation_id, result=None), + ) + for role in (managed_v2_roles.stage12, CATALOG_WRITER_ROLE): + act_as(session, role) + _refused(session, _row_count(run_calculations)) diff --git a/tests/unit/test_alembic_workflows.py b/tests/unit/test_alembic_workflows.py index 08fe48c0a..13db413cb 100644 --- a/tests/unit/test_alembic_workflows.py +++ b/tests/unit/test_alembic_workflows.py @@ -228,6 +228,8 @@ def test_reusable_v2_alembic_check_uses_only_disposable_postgres(): assert "test_alembic_v2_saved_report_current_runs.py" in lifecycle_script assert "test_alembic_v2_report_revisions.py" in lifecycle_script assert "test_alembic_v2_report_types.py" in lifecycle_script + assert "test_alembic_v2_household_run_revisions.py" in lifecycle_script + assert "test_alembic_v2_household_run_tables.py" in lifecycle_script assert "redis:7.2-alpine" not in workflow assert "RUNTIME_CACHE_TEST_URL" not in workflow assert "test_v2_catalog_installed.py" not in workflow diff --git a/tests/unit/v2/test_alembic_v2_household_run_revisions.py b/tests/unit/v2/test_alembic_v2_household_run_revisions.py new file mode 100644 index 000000000..00e492812 --- /dev/null +++ b/tests/unit/v2/test_alembic_v2_household_run_revisions.py @@ -0,0 +1,102 @@ +"""Unit checks of the household run tables revision of the API v2 Alembic chain. + +The revision that adds household runs' variables and extra calculations, and +the links from an economy report's saved row to household reports' saved rows +(6ec3d17299b6). As in ``test_alembic_v2_revisions``, where the chain's order +is checked, these tests read the revision file and check the operations it +runs. +""" + +import re +from pathlib import Path + +from alembic.config import Config +from alembic.script import ScriptDirectory + +from policyengine_api.constants import REPO +from tests.unit.v2.test_alembic_v2_revisions import ( + HOUSEHOLD_RUN_TABLES_REVISION, + REPORT_TYPES_REVISION, +) + +NEW_TABLES = [ + "household_run_calculations", + "household_run_variables", + "user_report_household_reports", +] +# Each new unique constraint, which the new tables' composite keys refer to, +# and its table. +NEW_UNIQUE_CONSTRAINTS = [ + ("uq_simulation_runs_id_simulation", "simulation_runs"), + ("uq_simulations_id_type", "simulations"), + ("uq_user_report_associations_id_user_country", "user_report_associations"), +] + + +def _revision_text() -> str: + """Return the text of the one revision whose parent is the report types one.""" + script = ScriptDirectory.from_config(Config(str(REPO / "alembic-v2.ini"))) + children = [ + revision + for revision in script.walk_revisions() + if revision.down_revision == REPORT_TYPES_REVISION + ] + assert [child.revision for child in children] == [HOUSEHOLD_RUN_TABLES_REVISION] + assert children[0].path is not None + return Path(children[0].path).read_text(encoding="utf-8") + + +def test_household_run_tables_revision_is_generated_with_two_corrections() -> None: + """Three tables and three unique constraints, generated with two corrections. + + It is generated, with its ID chosen through ``--rev-id``. The new tables' + ``simulation_type`` and ``status`` reuse the existing enum types instead + of creating them again, and the unique constraints the new tables' keys + refer to are created before the tables and dropped after them. It writes + no data and changes no column; the downgrade removes exactly what the + upgrade adds. + """ + revision = _revision_text() + upgrade = revision[ + revision.index("def upgrade()") : revision.index("def downgrade()") + ] + downgrade = revision[revision.index("def downgrade()") :] + + assert ( + "Generation: uv run alembic -c alembic-v2.ini revision --autogenerate " + f"--rev-id {HOUSEHOLD_RUN_TABLES_REVISION}" in revision + ) + assert sorted(re.findall(r"op\.create_table\('(\w+)'", upgrade)) == NEW_TABLES + assert sorted(re.findall(r"op\.drop_table\('(\w+)'\)", downgrade)) == NEW_TABLES + assert ( + sorted(re.findall(r"op\.create_unique_constraint\('(\w+)', '(\w+)'", upgrade)) + == NEW_UNIQUE_CONSTRAINTS + ) + assert ( + sorted( + re.findall( + r"op\.drop_constraint\('(\w+)', '(\w+)', type_='unique'\)", downgrade + ) + ) + == NEW_UNIQUE_CONSTRAINTS + ) + # The keys need the unique constraints they refer to. + assert upgrade.rindex("op.create_unique_constraint(") < upgrade.index( + "op.create_table(" + ) + assert downgrade.rindex("op.drop_table(") < downgrade.index("op.drop_constraint(") + # Each enum column reuses its type: simulation_type twice, status once. + assert "sa.Enum(" not in upgrade + assert upgrade.count("create_type=False") == 3 + assert upgrade.count("name='v2_simulation_type'") == 2 + assert upgrade.count("name='v2_simulation_status'") == 1 + for body in (upgrade, downgrade): + for operation in ( + "op.execute(", + "op.bulk_insert(", + "op.alter_column(", + "op.add_column(", + "op.drop_column(", + ".drop(", + ): + assert operation not in body, operation diff --git a/tests/unit/v2/test_alembic_v2_revisions.py b/tests/unit/v2/test_alembic_v2_revisions.py index 12c32ad32..c39ed649a 100644 --- a/tests/unit/v2/test_alembic_v2_revisions.py +++ b/tests/unit/v2/test_alembic_v2_revisions.py @@ -22,6 +22,8 @@ "countries", "dynamic_parameter_values", "dynamic_parameters", + "household_run_calculations", + "household_run_variables", "legacy_household_mappings", "legacy_policy_mappings", "legacy_user_mappings", @@ -39,6 +41,7 @@ "user_dynamics", "user_identities", "user_invitations", + "user_report_household_reports", "user_report_run_associations", "user_type_changes", "withheld_area_codes", @@ -102,19 +105,26 @@ # and parent of the saved reports' current runs revision. PUBLISHED_REPORT_IMAGES_REVISION = "50430a2da57f" # The saved reports' current runs revision, on the published report images -# revision: a saved report stores the run of its report its page shows. +# revision: a saved report stores the run of its report its page shows. It is +# the parent of the report types revision. SAVED_REPORT_CURRENT_RUNS_REVISION = "7dcd2cd14330" # The report types revision, on the saved reports' current runs revision: -# every report names its type. +# every report names its type. It is the parent of the household run tables +# revision. REPORT_TYPES_REVISION = "24b571d7d079" +# The household run tables revision, on the report types revision: household +# runs' variables and extra calculations, and household reports' saved rows +# linked to an economy report's. +HOUSEHOLD_RUN_TABLES_REVISION = "6ec3d17299b6" def test_v2_revision_chain_has_generated_policy_and_user_identity_changes() -> None: config = Config(str(REPO / "alembic-v2.ini")) script = ScriptDirectory.from_config(config) assert script.get_heads() == [V2_ALEMBIC_HEAD_REVISION] - assert V2_ALEMBIC_HEAD_REVISION == REPORT_TYPES_REVISION + assert V2_ALEMBIC_HEAD_REVISION == HOUSEHOLD_RUN_TABLES_REVISION assert [revision.revision for revision in script.walk_revisions()] == [ + HOUSEHOLD_RUN_TABLES_REVISION, REPORT_TYPES_REVISION, SAVED_REPORT_CURRENT_RUNS_REVISION, PUBLISHED_REPORT_IMAGES_REVISION, diff --git a/tests/unit/v2/test_import_side_effects.py b/tests/unit/v2/test_import_side_effects.py index a66415c11..cd95c5842 100644 --- a/tests/unit/v2/test_import_side_effects.py +++ b/tests/unit/v2/test_import_side_effects.py @@ -69,7 +69,7 @@ def reject_ddl(*args, **kwargs): import sys after = set(pathlib.Path.cwd().iterdir()) assert before == after -assert len(V2_METADATA.tables) == 57 +assert len(V2_METADATA.tables) == 60 assert "policyengine_api.data.v2.catalog.initialization" not in sys.modules assert "policyengine_api.data.v2.policy_migration_qualification" not in sys.modules assert ( diff --git a/tests/unit/v2/test_me_routes.py b/tests/unit/v2/test_me_routes.py index e1de43f68..20c276e50 100644 --- a/tests/unit/v2/test_me_routes.py +++ b/tests/unit/v2/test_me_routes.py @@ -338,7 +338,6 @@ def test_export_answers_the_current_run_of_each_saved_report() -> None: user_policy_id=None, baseline_user_policy_id=None, source_note=None, - provisions=None, validation=None, budget_window_years=None, last_run_at=None, diff --git a/tests/unit/v2/test_models.py b/tests/unit/v2/test_models.py index 7b19fec35..e0fe58fbc 100644 --- a/tests/unit/v2/test_models.py +++ b/tests/unit/v2/test_models.py @@ -606,11 +606,17 @@ def test_associations_are_v1_anchored_without_client_refs() -> None: assert reference_check == ( f"{reference}_id IS NOT NULL OR legacy_{reference}_id IS NOT NULL" ) - # No uniqueness involves the owner, so a merge at sign-in can move + # Each uniqueness includes the row's ID, so a merge at sign-in can move # any association to another user unchanged. A saved report's - # (id, report_id) is what a published report's key references. + # (id, report_id) is what a published report's key references, and + # its (id, user_id, country_id) what a household report link's keys + # reference. assert table.unique_column_sets == ( - {("id", "country_id"), ("id", "report_id")} + { + ("id", "country_id"), + ("id", "report_id"), + ("id", "user_id", "country_id"), + } if reference == "report" else {("id", "country_id")} ) diff --git a/tests/unit/v2/test_privilege_manifest.py b/tests/unit/v2/test_privilege_manifest.py index 125e3d1ac..dc688c354 100644 --- a/tests/unit/v2/test_privilege_manifest.py +++ b/tests/unit/v2/test_privilege_manifest.py @@ -47,7 +47,9 @@ STAGE12_PACKAGES = frozenset({"comparison_runs"}) TEST_ENVIRONMENT = "staging" # The rows the simulation service creates, and the run tables among them. A -# simulation run's cliff calculation is started and finished like a run. +# simulation run's cliff calculation, and a household run's extra +# calculation, are started and finished like a run; the variables a household +# run calculated are recorded once, with the run. SIMULATION_SERVICE_CREATES = frozenset( { "simulations", @@ -57,10 +59,18 @@ "budget_window_runs", "household_jobs", "cliff_impacts", + "household_run_variables", + "household_run_calculations", } ) RUN_STATUS_TABLES = frozenset( - {"simulation_runs", "report_runs", "household_jobs", "cliff_impacts"} + { + "simulation_runs", + "report_runs", + "household_jobs", + "cliff_impacts", + "household_run_calculations", + } ) # The run columns the Modal workers update: a run's state and its results. WORKER_RUN_STATE_COLUMNS = frozenset( @@ -83,6 +93,7 @@ ), "household_jobs": frozenset({"result"}), "cliff_impacts": frozenset({"cliff_gap", "cliff_share"}), + "household_run_calculations": frozenset({"result"}), } # The run columns the simulation service updates: it records a Modal call's ID # when Modal accepts the call, and fails the run when Modal refuses it. @@ -154,6 +165,21 @@ ), # A cliff calculation always calculates the run it was inserted for. "cliff_impacts": frozenset({"simulation_run_id"}), + # A household run's variables, and an extra calculation's run and request. + "household_run_variables": frozenset( + {"simulation_run_id", "simulation_id", "simulation_type", "variables"} + ), + "household_run_calculations": frozenset( + { + "simulation_run_id", + "simulation_id", + "simulation_type", + "variables", + "axes", + "key_version", + "calculation_key", + } + ), } # The policy, dynamic, household and catalog rows a run needs. RUN_INPUT_TABLES = frozenset( @@ -646,3 +672,54 @@ def test_api_v1_stores_published_reports_card_images() -> None: for role, tables in declared.items(): if role != RUNTIME_ROLE: assert tables["published_report_images"] == NO_ACCESS, role + + +def test_household_runs_variables_are_recorded_once_by_the_simulation_service() -> None: + """The service inserts a household run's variables with the run. + + The Modal worker and API v1 read them, nobody changes or deletes them, and + the catalog writer and the Stage 12 role can't read them. + """ + assert "household_run_variables" in TABLE_ACCESS + declared = declared_privileges(TEST_ENVIRONMENT) + + assert declared[SIMULATION_SERVICE_ROLE]["household_run_variables"] == READ_INSERT + assert declared[MODAL_WORKER_ROLE]["household_run_variables"] == READ + assert declared[RUNTIME_ROLE]["household_run_variables"] == READ + for role in (CATALOG_WRITER_ROLE, stage12_role(TEST_ENVIRONMENT)): + assert declared[role]["household_run_variables"] == NO_ACCESS, role + + +def test_household_run_calculations_are_granted_as_cliff_calculations_are() -> None: + """The service inserts an extra calculation and records its call. + + The Modal worker claims it and writes its result or the failure, and never + inserts one; API v1 reads it. The catalog writer and the Stage 12 role + can do neither. + """ + assert "household_run_calculations" in TABLE_ACCESS + declared = declared_privileges(TEST_ENVIRONMENT) + + assert declared[SIMULATION_SERVICE_ROLE][ + "household_run_calculations" + ] == READ_INSERT | {update_columns(*SERVICE_RUN_STATE_COLUMNS)} + assert declared[MODAL_WORKER_ROLE]["household_run_calculations"] == READ | { + update_columns(*WORKER_RUN_STATE_COLUMNS, "result") + } + assert declared[RUNTIME_ROLE]["household_run_calculations"] == READ + for role in (CATALOG_WRITER_ROLE, stage12_role(TEST_ENVIRONMENT)): + assert declared[role]["household_run_calculations"] == NO_ACCESS, role + + +def test_api_v1_alone_links_household_reports_to_saved_reports() -> None: + """API v1 links, reads and unlinks a saved report's household reports. + + No other role reads the links. + """ + assert "user_report_household_reports" in TABLE_ACCESS + declared = declared_privileges(TEST_ENVIRONMENT) + + assert declared[RUNTIME_ROLE]["user_report_household_reports"] == READ_WRITE + for role, tables in declared.items(): + if role != RUNTIME_ROLE: + assert tables["user_report_household_reports"] == NO_ACCESS, role diff --git a/tests/unit/v2/test_simulation_run_models.py b/tests/unit/v2/test_simulation_run_models.py index 73de9828e..d674703d2 100644 --- a/tests/unit/v2/test_simulation_run_models.py +++ b/tests/unit/v2/test_simulation_run_models.py @@ -85,6 +85,8 @@ "labor_supply_responses", "labor_supply_decile_responses", "household_jobs", + "household_run_variables", + "household_run_calculations", "aggregates", "change_aggregates", *PER_SIMULATION_RESULT_TABLES,