From 3c2670f1656c61a1f964af92fe66e25763aa3bce Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:17:43 +0400 Subject: [PATCH 1/9] Add tests for household runs' tables and household report links that fail before the change MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Task D2 · 3a adds three API v2 tables in one revision on 7dcd2cd14330: household_run_variables (the variables a household simulation run calculated), household_run_calculations (a household run's stored extra calculations), and user_report_household_reports (links from an economy report's saved row to household reports' saved rows of the same owner and country), with the unique constraints their composite keys refer to. The tests cover the revision's schema and its exact downgrade, the database refusing rows for economy runs, mismatched simulations, other owners' or countries' saved rows and malformed variable lists, one unfailed calculation per request, the cascades from runs, simulations, saved rows and users, the revision file's operations, the new v2 head, the declared privileges, and the simulation service's and Modal workers' writes as their roles. Co-Authored-By: Claude Opus 5.5 --- tests/integration/privilege_statements.py | 25 +- tests/integration/simulation_rows.py | 18 +- .../test_alembic_v2_household_run_tables.py | 710 ++++++++++++++++++ .../test_v2_simulation_role_privileges.py | 260 ++++++- tests/unit/test_alembic_workflows.py | 2 + ...test_alembic_v2_household_run_revisions.py | 102 +++ tests/unit/v2/test_alembic_v2_revisions.py | 13 +- tests/unit/v2/test_privilege_manifest.py | 81 +- 8 files changed, 1200 insertions(+), 11 deletions(-) create mode 100644 tests/integration/test_alembic_v2_household_run_tables.py create mode 100644 tests/unit/v2/test_alembic_v2_household_run_revisions.py 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..4e201648e 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 v2 mapped class of ``table_name``; fail when no class maps it.""" + 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 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..42df12ba0 --- /dev/null +++ b/tests/integration/test_alembic_v2_household_run_tables.py @@ -0,0 +1,710 @@ +"""Check the revision that adds household runs' tables and household report links. + +Revision 6ec3d17299b6, on 7dcd2cd14330, 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. 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 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 = "7dcd2cd14330" +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 the v2 migration 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"), + ) + 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", + ), + "fk_household_run_variables_simulation": ( + simulation_key, + "simulations", + ("id", "simulation_type"), + "CASCADE", + ), + } + 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", + ), + "fk_household_run_calculations_simulation": ( + simulation_key, + "simulations", + ("id", "simulation_type"), + "CASCADE", + ), + } + 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", + ), + "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", + ), + } + 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 diff --git a/tests/integration/test_v2_simulation_role_privileges.py b/tests/integration/test_v2_simulation_role_privileges.py index 5b7df5d61..3d856357c 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``) would have no statement through the model, so its writes and refusals would go through a class that maps it; since revision ``4e30076d4b9f`` no model 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: @@ -639,6 +644,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 @@ -875,3 +882,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 7f2cab69d..cf3b1d2f3 100644 --- a/tests/unit/test_alembic_workflows.py +++ b/tests/unit/test_alembic_workflows.py @@ -226,6 +226,8 @@ def test_reusable_v2_alembic_check_uses_only_disposable_postgres(): assert "test_alembic_v2_inline_household_jobs.py" in lifecycle_script assert "test_alembic_v2_published_report_images.py" in lifecycle_script assert "test_alembic_v2_saved_report_current_runs.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..b737dbe35 --- /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, + SAVED_REPORT_CURRENT_RUNS_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 current runs one.""" + script = ScriptDirectory.from_config(Config(str(REPO / "alembic-v2.ini"))) + children = [ + revision + for revision in script.walk_revisions() + if revision.down_revision == SAVED_REPORT_CURRENT_RUNS_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 2fc67889e..e7f66cd8b 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,16 +105,22 @@ # 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 household run tables revision. SAVED_REPORT_CURRENT_RUNS_REVISION = "7dcd2cd14330" +# The household run tables revision, on the saved reports' current runs +# 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 == SAVED_REPORT_CURRENT_RUNS_REVISION + assert V2_ALEMBIC_HEAD_REVISION == HOUSEHOLD_RUN_TABLES_REVISION assert [revision.revision for revision in script.walk_revisions()] == [ + HOUSEHOLD_RUN_TABLES_REVISION, SAVED_REPORT_CURRENT_RUNS_REVISION, PUBLISHED_REPORT_IMAGES_REVISION, INLINE_HOUSEHOLD_JOBS_REVISION, 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 From 54db96770ad48592f1e6d8b8789f46dca99f027b Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:27:01 +0400 Subject: [PATCH 2/9] Add a test that signing in moves household report links, which fails before the change Signing in to an account that already has a user moves each of the browser's saved rows to that user with one update per table. The test checks that a link between two of those rows takes the new owner, and the revision test now records each key's update action. Co-Authored-By: Claude Opus 5.5 --- .../test_alembic_v2_household_run_tables.py | 56 +++++++++++++++++-- 1 file changed, 51 insertions(+), 5 deletions(-) diff --git a/tests/integration/test_alembic_v2_household_run_tables.py b/tests/integration/test_alembic_v2_household_run_tables.py index 42df12ba0..42cf079fe 100644 --- a/tests/integration/test_alembic_v2_household_run_tables.py +++ b/tests/integration/test_alembic_v2_household_run_tables.py @@ -15,11 +15,12 @@ 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. 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. +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 @@ -42,6 +43,9 @@ 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, @@ -110,6 +114,7 @@ def _schema_shape(sessions: sessionmaker[Session]) -> dict[str, dict[str, Any]]: key["referred_table"], tuple(key["referred_columns"]), key["options"].get("ondelete"), + key["options"].get("onupdate"), ) for key in inspector.get_foreign_keys(table_name) }, @@ -190,12 +195,14 @@ def _check_new_tables(revision: dict[str, Any]) -> None: "simulation_runs", ("id", "simulation_id"), "CASCADE", + None, ), "fk_household_run_variables_simulation": ( simulation_key, "simulations", ("id", "simulation_type"), "CASCADE", + None, ), } assert set(variables["checks"]) == { @@ -230,12 +237,14 @@ def _check_new_tables(revision: dict[str, Any]) -> None: "simulation_runs", ("id", "simulation_id"), "CASCADE", + None, ), "fk_household_run_calculations_simulation": ( simulation_key, "simulations", ("id", "simulation_type"), "CASCADE", + None, ), } assert calculations["indexes"] == { @@ -283,12 +292,14 @@ def _check_new_tables(revision: dict[str, Any]) -> None: "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"] == { @@ -708,3 +719,38 @@ def link(parent: UUID, child: UUID, **values: object) -> dict[str, object]: ) 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)] From c22574bb56fc7bea451155981812da0860e4f66e Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:30:22 +0400 Subject: [PATCH 3/9] Update existing schema tests for the household run tables, which fail before the change - The v2 metadata has 60 tables, not 57. - At head, user_report_associations has a third unique constraint, (id, user_id, country_id), which the household report links' keys reference. Each of its unique constraints still includes the row's ID, so signing in can still move any row to another owner. - household_run_variables and household_run_calculations are tables the simulation service writes; the integration test now checks that every table in that list exists at head. Co-Authored-By: Claude Opus 5.5 --- tests/integration/test_alembic_v2_lifecycle.py | 9 +++++---- .../integration/test_alembic_v2_simulation_runs.py | 14 +++++++++++--- tests/unit/v2/test_import_side_effects.py | 2 +- tests/unit/v2/test_simulation_run_models.py | 2 ++ 4 files changed, 19 insertions(+), 8 deletions(-) diff --git a/tests/integration/test_alembic_v2_lifecycle.py b/tests/integration/test_alembic_v2_lifecycle.py index e18b21bc0..9afc759a7 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 73b9c1d4b..7169a19fb 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/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_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, From 582ee41072d2a4ec3989fed22ecde088f4183c22 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:32:44 +0400 Subject: [PATCH 4/9] Add household runs' variables and extra calculations tables and household report links to API v2 Revision 6ec3d17299b6, autogenerated on 7dcd2cd14330, adds three tables: - household_run_variables: the variables a household simulation run calculated, one row per run. A run with no row calculated every variable. - household_run_calculations: a household run's stored extra calculations (such as an earnings variation) and their results, modelled on cliff_impacts. A partial unique index lets identical requests join one calculation that hasn't failed. - user_report_household_reports: links an economy report's saved row to a household report's saved row of the same owner in the same country. Both household tables name their run together with its simulation, and the simulation together with its type, checked to be 'household', so PostgreSQL accepts their rows only for household runs; deleting the run or simulation deletes them. The link table's two keys name each saved row together with the link's owner and country, cascading deletes and updates, so a link between two owners' or countries' rows is refused, deleting either row or the owner deletes the link, and moving the rows to another owner at sign-in gives the link that owner. The keys refer to three new unique constraints: simulations (id, simulation_type), simulation_runs (id, simulation_id) and user_report_associations (id, user_id, country_id). Two documented post-generation corrections: the new enum columns reuse the existing types, and the unique constraints are created before the tables that refer to them and dropped after them. Privileges: the simulation service reads and inserts household run variables, which the Modal worker and API v1's runtime role read; household run calculations are granted as cliff_impacts are; API v1's runtime role alone reads and writes the links. The v2 head is now 6ec3d17299b6, the Alembic v2 check runs the new revision tests, and the Alembic skill doc describes the revision. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/test_alembic_v2_lifecycle.sh | 4 +- changelog.d/v2-household-run-tables.added.md | 1 + docs/engineering/skills/alembic-migrations.md | 98 ++++++++++ ...add_household_run_tables_and_household_.py | 179 +++++++++++++++++ policyengine_api/data/v2/migration_target.py | 2 +- policyengine_api/data/v2/models/__init__.py | 6 + .../data/v2/models/associations.py | 72 +++++++ .../data/v2/models/simulations.py | 183 +++++++++++++++++- policyengine_api/data/v2/privileges.py | 10 + 9 files changed, 552 insertions(+), 3 deletions(-) create mode 100644 changelog.d/v2-household-run-tables.added.md create mode 100644 migrations/v2/versions/6ec3d17299b6_add_household_run_tables_and_household_.py diff --git a/.github/scripts/test_alembic_v2_lifecycle.sh b/.github/scripts/test_alembic_v2_lifecycle.sh index dc67fed63..1b19eae10 100755 --- a/.github/scripts/test_alembic_v2_lifecycle.sh +++ b/.github/scripts/test_alembic_v2_lifecycle.sh @@ -7,6 +7,7 @@ uv run --frozen --extra dev pytest -q \ tests/unit/v2/test_alembic_v2_revisions.py \ 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_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 \ @@ -23,4 +24,5 @@ uv run --frozen --extra dev pytest -q \ tests/integration/test_alembic_v2_published_reports.py \ 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_saved_report_current_runs.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 90d30dd7b..940927788 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -1997,3 +1997,101 @@ parent schema and checks each refusal as the database's owner. `tests/integration/test_v2_saved_report_current_runs.py`, which the cross-database integration check runs, checks the routes as API v1's runtime role. + +### API v2 household runs' tables and household report links + +Revision `6ec3d17299b6` (parent `7dcd2cd14330`, 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). 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. + +`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/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..4264132b2 --- /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: 7dcd2cd14330 +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] = '7dcd2cd14330' +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 b3e4f7a2c..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 = "7dcd2cd14330" +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 5db4d34a6..b369cdc98 100644 --- a/policyengine_api/data/v2/models/associations.py +++ b/policyengine_api/data/v2/models/associations.py @@ -314,6 +314,10 @@ class UserReportAssociation(TimestampedModel, table=True): report, not its kind: a budget window's years are report runs of the 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. """ __tablename__ = "user_report_associations" @@ -360,6 +364,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", @@ -426,6 +436,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. API v2 checks the rows' kinds, policies, dynamics and + years when it links them, which the database can't, since kinds live on + ``reports``. 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..e31936174 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,171 @@ 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. + + The simulation service records them when it creates the run, from the + names a household report's request lists, sorted and without repeats. 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 + calculation is made only for a run on the current versions. + + The simulation service inserts a pending calculation and records its + Modal call, or fails it when Modal refuses the call; the Modal worker + claims it under its call, then writes the calculated household + (``result``) with ``succeeded``, or ``failed`` with its ``code: message`` + error, as for a cliff calculation (``CliffImpact``). A run has at most one + calculation of each request that hasn't failed, which identical requests + join; a failed one never counts, and the next request starts 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..1c0714027 100644 --- a/policyengine_api/data/v2/privileges.py +++ b/policyengine_api/data/v2/privileges.py @@ -289,6 +289,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 +383,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. From 9482f9a20be86664b105d3dcef3f5ac152ea5e62 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:55:01 +0400 Subject: [PATCH 5/9] Correct the household tables' docstrings and describe the revision's locks Review round 1 found no bugs; this commit fixes its wording findings. - The privilege manifest's role descriptions now include the household runs' variable lists and extra calculations. - The three new models' docstrings say what a writer must do and what the database doesn't check, instead of describing later tasks' code as if it existed. - Test text says "API v2" instead of a bare "v2". - The Alembic skill doc's deploy notes describe the three tables the revision locks while it runs, and the deadlock it can cause with the simulation service. Co-Authored-By: Claude Opus 5.5 --- docs/engineering/skills/alembic-migrations.md | 10 ++++++++ .../data/v2/models/associations.py | 6 ++--- .../data/v2/models/simulations.py | 24 ++++++++++--------- policyengine_api/data/v2/privileges.py | 13 ++++++---- tests/integration/simulation_rows.py | 4 ++-- .../test_alembic_v2_household_run_tables.py | 2 +- 6 files changed, 37 insertions(+), 22 deletions(-) diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 940927788..cdc3fe2df 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -2087,6 +2087,16 @@ Deploying it: 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.** Each new unique constraint builds its index under + an `ACCESS EXCLUSIVE` lock, and the revision runs in one transaction, so + `simulation_runs`, then `simulations`, then `user_report_associations` + refuse every read and write until the migration commits, about as long as + the three index builds take together. API v1's and the simulation service's + statements, which time out after 5 seconds, fail meanwhile. A simulation + service transaction that has inserted a simulation and then inserts its run + can also deadlock with the migration, which PostgreSQL ends by aborting one + of the two. `7dcd2cd14330` locked only `report_runs` this way; deploy this + revision 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`, diff --git a/policyengine_api/data/v2/models/associations.py b/policyengine_api/data/v2/models/associations.py index b369cdc98..01f5a1781 100644 --- a/policyengine_api/data/v2/models/associations.py +++ b/policyengine_api/data/v2/models/associations.py @@ -455,9 +455,9 @@ class UserReportHouseholdReport(TimestampedModel, table=True): 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. API v2 checks the rows' kinds, policies, dynamics and - years when it links them, which the database can't, since kinds live on - ``reports``. A link joins two different rows, at most once; a household + 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. """ diff --git a/policyengine_api/data/v2/models/simulations.py b/policyengine_api/data/v2/models/simulations.py index e31936174..9c8a106c1 100644 --- a/policyengine_api/data/v2/models/simulations.py +++ b/policyengine_api/data/v2/models/simulations.py @@ -343,10 +343,11 @@ def _variable_list_check(table_name: str) -> sa.CheckConstraint: class HouseholdRunVariables(SQLModel, table=True): """The variables a household simulation run calculated, one row per run. - The simulation service records them when it creates the run, from the - names a household report's request lists, sorted and without repeats. 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 + 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. """ @@ -382,13 +383,14 @@ class HouseholdRunCalculation(TimestampedModel, table=True): 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 - calculation is made only for a run on the current versions. - - The simulation service inserts a pending calculation and records its - Modal call, or fails it when Modal refuses the call; the Modal worker - claims it under its call, then writes the calculated household - (``result``) with ``succeeded``, or ``failed`` with its ``code: message`` - error, as for a cliff calculation (``CliffImpact``). A run has at most one + 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. A run has at most one calculation of each request that hasn't failed, which identical requests join; a failed one never counts, and the next request starts another. The row is only for a household simulation's run (``_household_only_keys``) diff --git a/policyengine_api/data/v2/privileges.py b/policyengine_api/data/v2/privileges.py index 1c0714027..373528e29 100644 --- a/policyengine_api/data/v2/privileges.py +++ b/policyengine_api/data/v2/privileges.py @@ -30,17 +30,20 @@ deploy check, not the connector analysis, covers it. - ``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 + jobs, simulation runs' cliff calculations, and household runs' variable + lists and extra calculations, and reads the policy, dynamic, household and + catalog rows a run needs. It starts the Modal calls of runs, household + jobs, cliff calculations and 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 the status of the runs, household jobs, cliff calculations and + household runs' extra 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 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 diff --git a/tests/integration/simulation_rows.py b/tests/integration/simulation_rows.py index 4e201648e..7bf1539cd 100644 --- a/tests/integration/simulation_rows.py +++ b/tests/integration/simulation_rows.py @@ -55,14 +55,14 @@ def add_row(session: Session, model: type[Any], **values: object) -> None: def v2_model(table_name: str) -> type[Any]: - """Return the v2 mapped class of ``table_name``; fail when no class maps it.""" + """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 v2 model should map {table_name}" + assert len(mapped_classes) == 1, f"one API v2 model should map {table_name}" return mapped_classes[0] diff --git a/tests/integration/test_alembic_v2_household_run_tables.py b/tests/integration/test_alembic_v2_household_run_tables.py index 42cf079fe..48c8b13a9 100644 --- a/tests/integration/test_alembic_v2_household_run_tables.py +++ b/tests/integration/test_alembic_v2_household_run_tables.py @@ -86,7 +86,7 @@ def _revision_ids() -> set[str]: - """Return the ID of every revision in the v2 migration chain.""" + """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()} From 7a74c74fc27e2437a8ac8a22b05c483a0a84f17a Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:06:32 +0400 Subject: [PATCH 6/9] Correct the revision's lock note and two descriptions of code that comes later Review round 2 found no bugs; this commit fixes its documentation findings. - The deploy note on locks now says that blocked statements wait until the migration commits unless a statement timeout ends them first, that the wait also includes the migration's own waits for each lock, which no lock_timeout bounds, that any transaction reading or writing a simulation and then its runs can deadlock with it, and that PostgreSQL may abort the migration, which rolls back and can be run again. It drops a misleading comparison with revision 7dcd2cd14330. - HouseholdRunCalculation's docstring and the privilege manifest describe joining a calculation and the household tables' writes as what the index and privileges allow, not as code that exists. Co-Authored-By: Claude Opus 5.5 --- docs/engineering/skills/alembic-migrations.md | 28 ++++++++++++------- .../data/v2/models/simulations.py | 7 +++-- policyengine_api/data/v2/privileges.py | 22 +++++++-------- 3 files changed, 33 insertions(+), 24 deletions(-) diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index cdc3fe2df..0821244c9 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -2087,16 +2087,24 @@ Deploying it: 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.** Each new unique constraint builds its index under - an `ACCESS EXCLUSIVE` lock, and the revision runs in one transaction, so - `simulation_runs`, then `simulations`, then `user_report_associations` - refuse every read and write until the migration commits, about as long as - the three index builds take together. API v1's and the simulation service's - statements, which time out after 5 seconds, fail meanwhile. A simulation - service transaction that has inserted a simulation and then inserts its run - can also deadlock with the migration, which PostgreSQL ends by aborting one - of the two. `7dcd2cd14330` locked only `report_runs` this way; deploy this - revision when few reports are running. +- **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`, diff --git a/policyengine_api/data/v2/models/simulations.py b/policyengine_api/data/v2/models/simulations.py index 9c8a106c1..2a5f3d1b0 100644 --- a/policyengine_api/data/v2/models/simulations.py +++ b/policyengine_api/data/v2/models/simulations.py @@ -390,9 +390,10 @@ class HouseholdRunCalculation(TimestampedModel, table=True): 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. A run has at most one - calculation of each request that hasn't failed, which identical requests - join; a failed one never counts, and the next request starts another. The + ``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``. diff --git a/policyengine_api/data/v2/privileges.py b/policyengine_api/data/v2/privileges.py index 373528e29..b26db4ab8 100644 --- a/policyengine_api/data/v2/privileges.py +++ b/policyengine_api/data/v2/privileges.py @@ -30,21 +30,21 @@ deploy check, not the connector analysis, covers it. - ``policyengine_v2_simulation_service``: the simulation API on Cloud Run. It creates simulations, reports, their runs, budget-window runs, household - jobs, simulation runs' cliff calculations, and household runs' variable - lists and extra calculations, and reads the policy, dynamic, household and - catalog rows a run needs. It starts the Modal calls of runs, household - jobs, cliff calculations and 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 + jobs and simulation runs' cliff calculations, and reads the policy, + 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, cliff calculations and - household runs' extra 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 + 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 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 From 17602fc638f17c13c1a9047097a9cfd0784fdfe2 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:38:18 +0400 Subject: [PATCH 7/9] Expect the saved reports' third unique constraint in the models test tests/unit/v2/test_models.py's test_associations_are_v1_anchored_without_client_refs still expected user_report_associations to have only (id, country_id) and (id, report_id) unique, so it failed in CI once the change added (id, user_id, country_id), which the household report links' keys reference. It now expects all three; each includes the row's ID, so a merge at sign-in can still move any row to another user. Co-Authored-By: Claude Opus 5.5 --- tests/unit/v2/test_models.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/tests/unit/v2/test_models.py b/tests/unit/v2/test_models.py index f8cec40b7..4e4fe0512 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")} ) From 7b7e5690b99ed580b36484578da4d0a7fb091e5a Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:44:00 +0400 Subject: [PATCH 8/9] Describe how a sign-in merge moves household report links in the user-login doc Review round 3 found no bugs. Its documentation finding: the Stage 12A user-login doc's "Conversion and merge" section still said no uniqueness on the association tables involves the owner. Every uniqueness includes the row's ID, which is why a merge never conflicts, and a household report link takes the new owner through its keys' update cascade. Co-Authored-By: Claude Opus 5.5 --- docs/migration/stage-12a-user-login.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/migration/stage-12a-user-login.md b/docs/migration/stage-12a-user-login.md index 7d9f6e3be..7f1b85f6a 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: From cb8200d2e8279a5116957c3532d6392071a0e723 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 4 Dec 2026 22:42:43 +0400 Subject: [PATCH 9/9] Stop passing provisions to UserReportRead in the export's current-run test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit D1 · 5a removed UserReportRead's provisions field, and D1 · 8 brought in test_export_answers_the_current_run_of_each_saved_report, which still passed provisions=None, so the test failed with a TypeError once both were on master. Co-Authored-By: Claude Opus 5.5 --- tests/unit/v2/test_me_routes.py | 1 - 1 file changed, 1 deletion(-) 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,