From 7676974764eda938470fa937ff3351855b6db2e4 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:33:26 +0400 Subject: [PATCH 1/5] Add tests for a saved report's current run that fail before the change A saved report (/v2/user-reports) stores which run of its report is current, as current_run_id: a report run, or a budget window's budget-window run. The tests cover the Alembic revision that adds the two run columns and their keys, the database refusing a run of another report and the deletion of a current run, the create and update routes setting, keeping, clearing and refusing the run, and the owner's and shared reads answering it. Co-Authored-By: Claude Opus 5.5 --- ...st_alembic_v2_saved_report_current_runs.py | 334 +++++++++++++++ .../test_v2_saved_report_current_runs.py | 399 ++++++++++++++++++ .../test_saved_report_current_run_routes.py | 72 ++++ 3 files changed, 805 insertions(+) create mode 100644 tests/integration/test_alembic_v2_saved_report_current_runs.py create mode 100644 tests/integration/test_v2_saved_report_current_runs.py create mode 100644 tests/unit/v2/test_saved_report_current_run_routes.py diff --git a/tests/integration/test_alembic_v2_saved_report_current_runs.py b/tests/integration/test_alembic_v2_saved_report_current_runs.py new file mode 100644 index 000000000..017806b50 --- /dev/null +++ b/tests/integration/test_alembic_v2_saved_report_current_runs.py @@ -0,0 +1,334 @@ +"""Check the revision that stores a saved report's current run, on disposable Postgres. + +Revision 7dcd2cd14330, on 50430a2da57f, adds two nullable columns to +``user_report_associations``: ``current_report_run_id``, the current report +run of an economy or household report, and ``current_budget_window_run_id``, +the current budget-window run of a budget window. Each is a foreign key +together with the saved report's ``report_id``, to ``report_runs`` and to +``budget_window_runs``, so the run must be one of that report's, and +``RESTRICT`` keeps a current run from being deleted; each is indexed. Checks +allow at most one of them, and either only on a saved report that names a +report. ``report_runs`` gains the unique constraint on ``(id, report_id)`` +that the first key refers to; ``budget_window_runs`` already has one. Nothing +else changes, and the downgrade removes exactly those. +""" + +from __future__ import annotations + +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, update +from sqlalchemy.dialects import postgresql +from sqlmodel import col + +from policyengine_api.data.v2.models import ( + BudgetWindowRun, + ReportRun, + 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, table_columns +from tests.integration.simulation_rows import add_row, refused +from tests.integration.stored_report_rows import ( + BudgetWindowYear, + RunSettings, + store_budget_window_run, + store_catalog, + store_report, + store_report_run, + store_year_simulations, +) + +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: published reports' card images. +PREVIOUS_REVISION = "50430a2da57f" +CURRENT_RUN_REVISION = "7dcd2cd14330" +SAVED_REPORTS = "user_report_associations" +VERSIONS = {"country_package_version": "1.5.0", "policyengine_version": "4.2.0"} +OTHER_VERSIONS = {**VERSIONS, "policyengine_version": "4.3.0"} + + +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) + }, + "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 test_the_revision_adds_the_current_run_keys_and_downgrades_exactly( + sessions: sessionmaker[Session], +) -> None: + assert CURRENT_RUN_REVISION in _revision_ids() + config = alembic_v2_config() + command.upgrade(config, "head") + command.downgrade(config, PREVIOUS_REVISION) + parent = _schema_shape(sessions) + command.upgrade(config, CURRENT_RUN_REVISION) + revision = _schema_shape(sessions) + command.downgrade(config, PREVIOUS_REVISION) + downgraded = _schema_shape(sessions) + + assert set(revision) == set(parent) + assert sorted( + table_name + for table_name in parent + if revision[table_name] != parent[table_name] + ) == ["report_runs", SAVED_REPORTS] + saved_before, saved_after = parent[SAVED_REPORTS], revision[SAVED_REPORTS] + assert _added(saved_before["columns"], saved_after["columns"]) == { + "current_report_run_id": ("UUID", True, None), + "current_budget_window_run_id": ("UUID", True, None), + } + assert _added(saved_before["foreign_keys"], saved_after["foreign_keys"]) == { + "fk_user_report_associations_current_report_run": ( + ("current_report_run_id", "report_id"), + "report_runs", + ("id", "report_id"), + "RESTRICT", + ), + "fk_user_report_associations_current_budget_window_run": ( + ("current_budget_window_run_id", "report_id"), + "budget_window_runs", + ("id", "report_id"), + "RESTRICT", + ), + } + assert _added(saved_before["indexes"], saved_after["indexes"]) == { + "ix_user_report_associations_current_report_run_id": ( + ("current_report_run_id",), + False, + None, + ), + "ix_user_report_associations_current_budget_window_run_id": ( + ("current_budget_window_run_id",), + False, + None, + ), + } + assert set(_added(saved_before["checks"], saved_after["checks"])) == { + "ck_user_report_associations_one_current_run", + "ck_user_report_associations_current_run_report", + } + assert saved_after["unique_constraints"] == saved_before["unique_constraints"] + runs_before, runs_after = parent["report_runs"], revision["report_runs"] + assert _added( + runs_before["unique_constraints"], runs_after["unique_constraints"] + ) == {"uq_report_runs_id_report": ("id", "report_id")} + for part in ("columns", "foreign_keys", "indexes", "checks"): + assert runs_after[part] == runs_before[part], part + assert downgraded == parent + + +def _saved_report_rows(session: Session) -> dict[str, UUID]: + """Store a report with a run, a budget window with a year, and a saved report. + + The saved report names the economy report and no run yet; the other + report has a run of its own. + """ + catalog = store_catalog(session, "us") + economy = store_report(session, catalog) + other = store_report(session, catalog) + window = store_report(session, catalog, budget_window_size=2) + window_run_id = store_budget_window_run( + session, catalog, window, RunSettings(versions=VERSIONS) + ) + year_run_id = store_report_run( + session, + catalog, + store_year_simulations(session, catalog, window, 2026), + RunSettings( + versions=VERSIONS, + budget_window_year=BudgetWindowYear( + budget_window_run_id=window_run_id, year=2026 + ), + ), + ).report_run_id + user_id = uuid4() + add_row(session, User, id=user_id, user_type="unauthenticated") + saved_report_id = uuid4() + add_row( + session, + UserReportAssociation, + id=saved_report_id, + user_id=user_id, + country_id="us", + report_id=economy.report_id, + ) + return { + "saved_report": saved_report_id, + "economy": economy.report_id, + "economy_run": store_report_run( + session, catalog, economy, RunSettings(versions=VERSIONS) + ).report_run_id, + "other_run": store_report_run( + session, catalog, other, RunSettings(versions=OTHER_VERSIONS) + ).report_run_id, + "window": window.report_id, + "window_run": window_run_id, + "window_year_run": year_run_id, + "user": user_id, + } + + +def _set_saved_report(session: Session, saved_report_id: UUID, **values: Any) -> None: + session.execute( + update(UserReportAssociation) + .where(col(UserReportAssociation.id) == saved_report_id) + .values(**values) + ) + + +def test_the_database_refuses_a_current_run_the_saved_report_cannot_have( + session: Session, +) -> None: + assert {"current_report_run_id", "current_budget_window_run_id"} <= set( + table_columns(session, SAVED_REPORTS) + ) + rows = _saved_report_rows(session) + saved_report_id = rows["saved_report"] + + for refused_values in ( + # A run of another report. + {"current_report_run_id": rows["other_run"]}, + # A budget-window run of another report. + {"current_budget_window_run_id": rows["window_run"]}, + # Two current runs, each one of the window's own: its budget-window run + # and its year's report run. + { + "report_id": rows["window"], + "budget_window_years": 2, + "current_report_run_id": rows["window_year_run"], + "current_budget_window_run_id": rows["window_run"], + }, + # A run on a saved report that names only a v1 report output. + { + "report_id": None, + "legacy_report_id": 615, + "current_report_run_id": rows["economy_run"], + }, + ): + with refused(session): + _set_saved_report(session, saved_report_id, **refused_values) + + _set_saved_report( + session, saved_report_id, current_report_run_id=rows["economy_run"] + ) + with refused(session): + session.execute( + delete(ReportRun).where(col(ReportRun.id) == rows["economy_run"]) + ) + _set_saved_report( + session, + saved_report_id, + report_id=rows["window"], + budget_window_years=2, + current_report_run_id=None, + current_budget_window_run_id=rows["window_run"], + ) + with refused(session): + session.execute( + delete(BudgetWindowRun).where(col(BudgetWindowRun.id) == rows["window_run"]) + ) + stored = session.get(UserReportAssociation, saved_report_id) + assert stored is not None + session.refresh(stored) + assert (stored.report_id, stored.current_budget_window_run_id) == ( + rows["window"], + rows["window_run"], + ) diff --git a/tests/integration/test_v2_saved_report_current_runs.py b/tests/integration/test_v2_saved_report_current_runs.py new file mode 100644 index 000000000..f1c73bc76 --- /dev/null +++ b/tests/integration/test_v2_saved_report_current_runs.py @@ -0,0 +1,399 @@ +"""A saved report stores which run of its report is current, on migrated PostgreSQL. + +A report page's link holds the saved report's ID, and the page shows the run +the saved report stores as current (``current_run_id``): a report run of an +economy or household report, or the budget-window run of a budget window, +the same IDs ``GET /v2/reports/{id}?run_id=`` takes. The owner sets it when +saving the report and with ``PATCH``, which refuses a run that isn't one of +the named report's own; naming another report clears it unless the same +request gives one of that report's runs. The user-report reads and the +shared read answer it. The routes run as API v1's runtime role. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any +from uuid import UUID, uuid4 + +import pytest +from alembic import command +from alembic.config import Config +from sqlalchemy import delete + +from policyengine_api.constants import REPO +from policyengine_api.data.v2.models import User +from policyengine_api.services.v2.identity.types import UnauthenticatedPrincipal +from policyengine_api.services.v2.user_reports.database_session import ( + UserReportDatabaseSession, +) +from policyengine_api.services.v2.user_reports.services import V2UserReportService +from tests.integration.stored_report_rows import ( + RunSettings, + delete_catalog, + store_catalog, + store_report, + store_report_run, +) +from tests.integration.user_report_run_support import store_window +from tests.unit.v2.user_route_support import user_route_client +from tests.unit.v2.user_service_support import default_legacy_references + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + + from fastapi.testclient import TestClient + from httpx import Response + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + from tests.integration.conftest import ManagedV2Roles + from tests.integration.stored_report_rows import CatalogRows + +VERSIONS = {"country_package_version": "1.5.0", "policyengine_version": "4.2.0"} +NEWER_VERSIONS = {**VERSIONS, "policyengine_version": "4.3.0"} +SAVED_REPORTS = "/v2/user-reports" +COUNTRY = "?country_id=us" + + +@dataclass(frozen=True) +class ReportsWithRuns: + """An economy report with two runs, another report with one, and a window. + + The window is a two-year budget window with one budget-window run, and a + report run for each year of it. + """ + + economy_id: UUID + economy_run_id: UUID + newer_economy_run_id: UUID + other_id: UUID + other_run_id: UUID + window_id: UUID + window_run_id: UUID + window_year_run_id: UUID + + +@pytest.fixture +def owner_sessions(v2_owner_sessions: sessionmaker[Session]) -> sessionmaker[Session]: + """Return the database owner's Session factories, its schema migrated to head.""" + command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") + return v2_owner_sessions + + +@pytest.fixture +def browsers(owner_sessions: sessionmaker[Session]) -> Iterator[list[UUID]]: + """Signed-out browsers' user IDs; their users and saved reports go afterwards.""" + user_ids: list[UUID] = [] + yield user_ids + with owner_sessions.begin() as session: + session.execute(delete(User).where(User.id.in_(user_ids))) + + +@pytest.fixture +def catalog( + owner_sessions: sessionmaker[Session], browsers: list[UUID] +) -> Iterator[CatalogRows]: + """Store a US catalog; delete it after the saved reports that name its reports.""" + with owner_sessions.begin() as session: + stored = store_catalog(session, "us") + yield stored + with owner_sessions.begin() as session: + session.execute(delete(User).where(User.id.in_(browsers))) + delete_catalog(session, stored) + + +@pytest.fixture +def reports( + owner_sessions: sessionmaker[Session], catalog: CatalogRows +) -> ReportsWithRuns: + with owner_sessions.begin() as session: + economy = store_report(session, catalog) + other = store_report(session, catalog) + window = store_window( + session, catalog, years=(2026, 2027), settings=RunSettings(VERSIONS) + ) + return ReportsWithRuns( + economy_id=economy.report_id, + economy_run_id=store_report_run( + session, catalog, economy, RunSettings(VERSIONS) + ).report_run_id, + newer_economy_run_id=store_report_run( + session, catalog, economy, RunSettings(NEWER_VERSIONS) + ).report_run_id, + other_id=other.report_id, + other_run_id=store_report_run( + session, catalog, other, RunSettings(VERSIONS) + ).report_run_id, + window_id=window.report.report_id, + window_run_id=window.window_run_id, + window_year_run_id=window.year_run_ids[0], + ) + + +@pytest.fixture +def service( + managed_v2_roles: ManagedV2Roles, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], +) -> V2UserReportService: + """Return the saved-report service, its Sessions acting as API v1's runtime role.""" + return V2UserReportService( + UserReportDatabaseSession(v2_sessions_as_role(managed_v2_roles.runtime)), + default_legacy_references(), + ) + + +def client_for_browser( + service: V2UserReportService, browsers: list[UUID] +) -> TestClient: + """Serve the saved-report routes to a new signed-out browser, as its owner.""" + principal = UnauthenticatedPrincipal(user_id=uuid4()) + browsers.append(principal.user_id) + client, _flask_calls = user_route_client( + require_user=lambda: principal, + v2_user_report_service_factory=lambda: service, + ) + return client + + +def as_json(fields: dict[str, Any]) -> dict[str, Any]: + return { + name: str(value) if isinstance(value, UUID) else value + for name, value in fields.items() + } + + +def save(client: TestClient, **fields: Any) -> Response: + return client.post( + f"{SAVED_REPORTS}{COUNTRY}", json=as_json({"country_id": "us", **fields}) + ) + + +def saved_item(client: TestClient, **fields: Any) -> dict[str, Any]: + response = save(client, **fields) + assert response.status_code == 201, response.text + return response.json()["result"]["item"] + + +def change(client: TestClient, saved_report_id: str, **fields: Any) -> Response: + return client.patch( + f"{SAVED_REPORTS}/{saved_report_id}{COUNTRY}", json=as_json(fields) + ) + + +def changed_item( + client: TestClient, saved_report_id: str, **fields: Any +) -> dict[str, Any]: + response = change(client, saved_report_id, **fields) + assert response.status_code == 200, response.text + return response.json()["result"]["item"] + + +def read_item(client: TestClient, path: str) -> dict[str, Any]: + response = client.get(f"{path}{COUNTRY}") + assert response.status_code == 200, response.text + return response.json()["result"]["item"] + + +def report_and_run(item: dict[str, Any]) -> tuple[str | None, str | None]: + return item["report_id"], item["current_run_id"] + + +def test_every_read_answers_the_run_a_report_was_saved_with( + browsers: list[UUID], reports: ReportsWithRuns, service: V2UserReportService +) -> None: + client = client_for_browser(service, browsers) + + created = saved_item( + client, report_id=reports.economy_id, current_run_id=reports.economy_run_id + ) + listed = client.get(f"{SAVED_REPORTS}{COUNTRY}") + # Anyone holding the link, with no credential. + shared_client, _flask_calls = user_route_client( + require_user=None, v2_user_report_service_factory=lambda: service + ) + shared = read_item(shared_client, f"/v2/shared-reports/{created['id']}") + + assert listed.status_code == 200, listed.text + assert [item["current_run_id"] for item in listed.json()["result"]["items"]] == [ + str(reports.economy_run_id) + ] + for item in ( + created, + read_item(client, f"{SAVED_REPORTS}/{created['id']}"), + shared, + ): + assert report_and_run(item) == ( + str(reports.economy_id), + str(reports.economy_run_id), + ) + + +def test_a_saved_budget_window_stores_its_budget_window_run( + browsers: list[UUID], reports: ReportsWithRuns, service: V2UserReportService +) -> None: + client = client_for_browser(service, browsers) + + created = saved_item( + client, + report_id=reports.window_id, + budget_window_years=2, + current_run_id=reports.window_run_id, + ) + + assert report_and_run(created) == ( + str(reports.window_id), + str(reports.window_run_id), + ) + assert report_and_run(read_item(client, f"{SAVED_REPORTS}/{created['id']}")) == ( + str(reports.window_id), + str(reports.window_run_id), + ) + + +def test_a_report_saved_without_a_run_has_no_current_run( + browsers: list[UUID], reports: ReportsWithRuns, service: V2UserReportService +) -> None: + client = client_for_browser(service, browsers) + + detailed_save = saved_item(client, report_id=reports.economy_id) + v1_report = saved_item(client, legacy_report_id=615) + + assert "current_run_id" in detailed_save + assert detailed_save["current_run_id"] is None + assert "current_run_id" in v1_report + assert v1_report["current_run_id"] is None + + +# Each refused save: the saved report's fields, from the stored reports. +REFUSED_SAVES: dict[str, Callable[[ReportsWithRuns], dict[str, Any]]] = { + "a-run-of-another-report": lambda stored: { + "report_id": stored.economy_id, + "current_run_id": stored.other_run_id, + }, + "a-budget-window-run-of-another-report": lambda stored: { + "report_id": stored.economy_id, + "current_run_id": stored.window_run_id, + }, + "a-year-of-the-budget-window": lambda stored: { + "report_id": stored.window_id, + "budget_window_years": 2, + "current_run_id": stored.window_year_run_id, + }, + "no-such-run": lambda stored: { + "report_id": stored.economy_id, + "current_run_id": UUID("5f8e2d1c-3b4a-4c6d-8e9f-0a1b2c3d4e5f"), + }, + "a-v1-report-output": lambda stored: { + "legacy_report_id": 615, + "current_run_id": stored.economy_run_id, + }, +} + + +@pytest.mark.parametrize( + "refused_fields", list(REFUSED_SAVES.values()), ids=list(REFUSED_SAVES) +) +def test_a_current_run_that_is_not_one_of_the_reports_own_is_refused( + browsers: list[UUID], + reports: ReportsWithRuns, + service: V2UserReportService, + refused_fields: Callable[[ReportsWithRuns], dict[str, Any]], +) -> None: + client = client_for_browser(service, browsers) + fields = refused_fields(reports) + + response = save(client, **fields) + listed = client.get(f"{SAVED_REPORTS}{COUNTRY}") + + assert response.status_code == 400, response.text + assert str(fields["current_run_id"]) in response.json()["message"] + assert listed.json()["result"]["items"] == [] + + +def test_the_owner_moves_keeps_and_clears_the_current_run( + browsers: list[UUID], reports: ReportsWithRuns, service: V2UserReportService +) -> None: + client = client_for_browser(service, browsers) + saved_id = saved_item( + client, report_id=reports.economy_id, current_run_id=reports.economy_run_id + )["id"] + + moved = changed_item(client, saved_id, current_run_id=reports.newer_economy_run_id) + renamed = changed_item(client, saved_id, name="Renamed") + refused = change(client, saved_id, current_run_id=reports.other_run_id) + after_refusal = read_item(client, f"{SAVED_REPORTS}/{saved_id}") + cleared = changed_item(client, saved_id, current_run_id=None) + + assert moved["current_run_id"] == str(reports.newer_economy_run_id) + assert (renamed["name"], renamed["current_run_id"]) == ( + "Renamed", + str(reports.newer_economy_run_id), + ) + assert refused.status_code == 400, refused.text + assert after_refusal["current_run_id"] == str(reports.newer_economy_run_id) + assert report_and_run(cleared) == (str(reports.economy_id), None) + + +def test_naming_another_report_clears_the_current_run_unless_one_of_its_runs_is_sent( + browsers: list[UUID], reports: ReportsWithRuns, service: V2UserReportService +) -> None: + client = client_for_browser(service, browsers) + saved_id = saved_item( + client, report_id=reports.economy_id, current_run_id=reports.economy_run_id + )["id"] + + same_report = changed_item(client, saved_id, report_id=reports.economy_id) + refused = change( + client, + saved_id, + report_id=reports.other_id, + current_run_id=reports.economy_run_id, + ) + after_refusal = read_item(client, f"{SAVED_REPORTS}/{saved_id}") + other_report = changed_item(client, saved_id, report_id=reports.other_id) + with_its_run = changed_item( + client, + saved_id, + report_id=reports.economy_id, + current_run_id=reports.economy_run_id, + ) + window = changed_item( + client, + saved_id, + report_id=reports.window_id, + budget_window_years=2, + current_run_id=reports.window_run_id, + ) + + assert report_and_run(same_report) == ( + str(reports.economy_id), + str(reports.economy_run_id), + ) + assert refused.status_code == 400, refused.text + assert report_and_run(after_refusal) == report_and_run(same_report) + assert report_and_run(other_report) == (str(reports.other_id), None) + assert report_and_run(with_its_run) == report_and_run(same_report) + assert report_and_run(window) == ( + str(reports.window_id), + str(reports.window_run_id), + ) + + +def test_only_the_owner_changes_a_saved_reports_current_run( + browsers: list[UUID], reports: ReportsWithRuns, service: V2UserReportService +) -> None: + owner = client_for_browser(service, browsers) + reader = client_for_browser(service, browsers) + saved_id = saved_item( + owner, report_id=reports.economy_id, current_run_id=reports.economy_run_id + )["id"] + # The reader saves something, so it is a user of its own. + saved_item(reader, report_id=reports.economy_id) + + refused = change(reader, saved_id, current_run_id=reports.newer_economy_run_id) + + assert refused.status_code == 404, refused.text + assert read_item(owner, f"{SAVED_REPORTS}/{saved_id}")["current_run_id"] == str( + reports.economy_run_id + ) diff --git a/tests/unit/v2/test_saved_report_current_run_routes.py b/tests/unit/v2/test_saved_report_current_run_routes.py new file mode 100644 index 000000000..9eea37525 --- /dev/null +++ b/tests/unit/v2/test_saved_report_current_run_routes.py @@ -0,0 +1,72 @@ +"""The saved-report routes take and answer a saved report's current run. + +``current_run_id`` names the run of its report a saved report's page shows: +a report run, or a budget window's budget-window run. The owner's writes take +it, null clearing it, and the owner's reads and the shared read answer it. +""" + +from __future__ import annotations + +from uuid import UUID + +from tests.unit.v2.user_route_support import RecordingService, user_route_client + +RUN_ID = UUID("0b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e") +SAVED_REPORT_ID = UUID("1c2d3e4f-5a6b-4c7d-8e9f-0a1b2c3d4e5f") + + +def test_the_openapi_document_types_the_current_run_on_every_saved_report_model() -> ( + None +): + client, _flask_calls = user_route_client() + + schemas = client.get("/v2/openapi.json").json()["components"]["schemas"] + + for schema_name in ( + "UserReportItem", + "SharedUserReportItem", + "UserReportCreateRequest", + "UserReportPatchRequest", + ): + current_run = schemas[schema_name]["properties"].get("current_run_id") + assert current_run is not None, schema_name + assert {"type": "string", "format": "uuid"} in current_run["anyOf"], schema_name + assert {"type": "null"} in current_run["anyOf"], schema_name + for schema_name in ("UserReportItem", "SharedUserReportItem"): + assert "current_run_id" in schemas[schema_name]["required"], schema_name + + +def test_a_patch_of_only_the_current_run_reaches_the_service() -> None: + reports = RecordingService() + client, _flask_calls = user_route_client( + v2_user_report_service_factory=lambda: reports + ) + + for current_run_id in (str(RUN_ID), None): + client.patch( + f"/v2/user-reports/{SAVED_REPORT_ID}?country_id=us", + json={"current_run_id": current_run_id}, + ) + + assert [name for name, _arguments in reports.calls] == [ + "patch_user_report", + "patch_user_report", + ] + sent = [arguments["association_input"] for _name, arguments in reports.calls] + assert [update.model_fields_set for update in sent] == [{"current_run_id"}] * 2 + assert [update.current_run_id for update in sent] == [RUN_ID, None] + + +def test_the_saved_report_writes_document_the_current_run_refusal() -> None: + client, _flask_calls = user_route_client() + + paths = client.get("/v2/openapi.json").json()["paths"] + + for method in ("post", "patch"): + path = ( + "/v2/user-reports" + if method == "post" + else "/v2/user-reports/{association_id}" + ) + answer = paths[path][method]["responses"]["400"] + assert "current_run_id" in answer["description"], method From fd4c44b405aa81cf87b79d5cdfd6547feb6fbf81 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:38:47 +0400 Subject: [PATCH 2/5] Store a saved report's current run in API v2 A saved report (/v2/user-reports) now stores which run of its report its page shows. The API answers it as current_run_id: one of the report's report runs, or a budget window's budget-window run, the IDs GET /v2/reports/{id}?run_id= takes. The database holds it in two nullable columns on user_report_associations, current_report_run_id and current_budget_window_run_id, each a foreign key together with report_id with RESTRICT, at most one set and either only with report_id; report_runs gains a unique constraint on (id, report_id) for the first key. Revision 7dcd2cd14330 is autogenerated. POST and PATCH /v2/user-reports take current_run_id and check it in the write's transaction against the report the saved report names, refusing another report's run with 400. A PATCH naming another report clears the current run unless it gives one of that report's runs, and null clears it. Only the owner can change it. The owner's reads and GET /v2/shared-reports/{id} return it. The route contracts and generated migration contract files include the field. Co-Authored-By: Claude Opus 5.5 --- .../v2-saved-report-current-run.added.md | 1 + docs/engineering/migration-contracts.md | 14 +-- docs/generated/migration_contracts.json | 7 ++ ...d14330_store_saved_reports_current_runs.py | 61 +++++++++++ .../data/v2/models/associations.py | 36 +++++++ policyengine_api/data/v2/models/reports.py | 2 + .../v2/user_reports/response_models.py | 8 ++ .../fastapi_routes/v2/user_reports/routes.py | 24 ++++- .../user_reports/database_connectors/reads.py | 25 +++++ .../services/v2/user_reports/services.py | 101 +++++++++++++++++- .../v2/user_reports/transformations.py | 39 ++++++- .../services/v2/user_reports/types.py | 20 +++- .../services/v2/user_reports/validators.py | 36 +++++++ tests/contract/registry.py | 3 + tests/unit/v2/test_admin_user_routes.py | 1 + tests/unit/v2/test_me_routes.py | 1 + .../test_saved_report_current_run_routes.py | 7 +- tests/unit/v2/test_shared_report_routes.py | 2 + .../v2/test_user_simulation_report_routes.py | 1 + 19 files changed, 364 insertions(+), 25 deletions(-) create mode 100644 changelog.d/v2-saved-report-current-run.added.md create mode 100644 migrations/v2/versions/7dcd2cd14330_store_saved_reports_current_runs.py diff --git a/changelog.d/v2-saved-report-current-run.added.md b/changelog.d/v2-saved-report-current-run.added.md new file mode 100644 index 000000000..b17e461cd --- /dev/null +++ b/changelog.d/v2-saved-report-current-run.added.md @@ -0,0 +1 @@ +A saved report (`/v2/user-reports`) stores which run of its report its page shows, as `current_run_id`: one of the report's runs, or a budget window's budget-window run. The owner sets it when saving the report and with `PATCH`, which refuses a run of another report and clears it when naming another report without one of its runs; the owner's reads and `GET /v2/shared-reports/{id}` return it. diff --git a/docs/engineering/migration-contracts.md b/docs/engineering/migration-contracts.md index 3f4f5596e..3884be55f 100644 --- a/docs/engineering/migration-contracts.md +++ b/docs/engineering/migration-contracts.md @@ -169,17 +169,17 @@ Generated from `policyengine_api/migration_registry.py` and `tests/contract/regi | Method | Path | Status | Route group | Required headers | Stable response fields | | --- | --- | ---: | --- | --- | --- | -| `POST` | `/v2/user-reports?country_id=us` | 201 | `report` | `Authorization` | `status`, `message`, `result.item.id`, `result.item.country_id`, `result.item.user_id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.description`, `result.item.user_policy_id`, `result.item.baseline_user_policy_id`, `result.item.source_note`, `result.item.provisions`, `result.item.validation`, `result.item.budget_window_years`, `result.item.last_run_at`, `result.item.created_at`, `result.item.updated_at` | -| `GET` | `/v2/user-reports/{association_id}?country_id=us` | 200 | `report` | `Authorization` | `status`, `message`, `result.item.id`, `result.item.country_id`, `result.item.user_id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.description`, `result.item.user_policy_id`, `result.item.baseline_user_policy_id`, `result.item.source_note`, `result.item.provisions`, `result.item.validation`, `result.item.budget_window_years`, `result.item.last_run_at`, `result.item.created_at`, `result.item.updated_at` | +| `POST` | `/v2/user-reports?country_id=us` | 201 | `report` | `Authorization` | `status`, `message`, `result.item.id`, `result.item.country_id`, `result.item.user_id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.description`, `result.item.user_policy_id`, `result.item.baseline_user_policy_id`, `result.item.source_note`, `result.item.provisions`, `result.item.validation`, `result.item.budget_window_years`, `result.item.last_run_at`, `result.item.current_run_id`, `result.item.created_at`, `result.item.updated_at` | +| `GET` | `/v2/user-reports/{association_id}?country_id=us` | 200 | `report` | `Authorization` | `status`, `message`, `result.item.id`, `result.item.country_id`, `result.item.user_id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.description`, `result.item.user_policy_id`, `result.item.baseline_user_policy_id`, `result.item.source_note`, `result.item.provisions`, `result.item.validation`, `result.item.budget_window_years`, `result.item.last_run_at`, `result.item.current_run_id`, `result.item.created_at`, `result.item.updated_at` | | `GET` | `/v2/user-reports?country_id=us` | 200 | `report` | `Authorization` | `status`, `message`, `result.items`, `result.offset`, `result.limit`, `result.has_more` | -| `PATCH` | `/v2/user-reports/{association_id}?country_id=us` | 200 | `report` | `Authorization` | `status`, `message`, `result.item.id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.description`, `result.item.user_policy_id`, `result.item.baseline_user_policy_id`, `result.item.source_note`, `result.item.provisions`, `result.item.validation`, `result.item.budget_window_years`, `result.item.last_run_at`, `result.item.updated_at` | +| `PATCH` | `/v2/user-reports/{association_id}?country_id=us` | 200 | `report` | `Authorization` | `status`, `message`, `result.item.id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.description`, `result.item.user_policy_id`, `result.item.baseline_user_policy_id`, `result.item.source_note`, `result.item.provisions`, `result.item.validation`, `result.item.budget_window_years`, `result.item.last_run_at`, `result.item.current_run_id`, `result.item.updated_at` | | `DELETE` | `/v2/user-reports/{association_id}?country_id=us` | 204 | `report` | `Authorization` | | -| `POST` | `/v2/user-reports?country_id=us` | 201 | `report` | `PolicyEngine-Unauthenticated-User` | `status`, `message`, `result.item.id`, `result.item.country_id`, `result.item.user_id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.description`, `result.item.user_policy_id`, `result.item.baseline_user_policy_id`, `result.item.source_note`, `result.item.provisions`, `result.item.validation`, `result.item.budget_window_years`, `result.item.last_run_at`, `result.item.created_at`, `result.item.updated_at` | -| `GET` | `/v2/user-reports/{association_id}?country_id=us` | 200 | `report` | `PolicyEngine-Unauthenticated-User` | `status`, `message`, `result.item.id`, `result.item.country_id`, `result.item.user_id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.description`, `result.item.user_policy_id`, `result.item.baseline_user_policy_id`, `result.item.source_note`, `result.item.provisions`, `result.item.validation`, `result.item.budget_window_years`, `result.item.last_run_at`, `result.item.created_at`, `result.item.updated_at` | +| `POST` | `/v2/user-reports?country_id=us` | 201 | `report` | `PolicyEngine-Unauthenticated-User` | `status`, `message`, `result.item.id`, `result.item.country_id`, `result.item.user_id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.description`, `result.item.user_policy_id`, `result.item.baseline_user_policy_id`, `result.item.source_note`, `result.item.provisions`, `result.item.validation`, `result.item.budget_window_years`, `result.item.last_run_at`, `result.item.current_run_id`, `result.item.created_at`, `result.item.updated_at` | +| `GET` | `/v2/user-reports/{association_id}?country_id=us` | 200 | `report` | `PolicyEngine-Unauthenticated-User` | `status`, `message`, `result.item.id`, `result.item.country_id`, `result.item.user_id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.description`, `result.item.user_policy_id`, `result.item.baseline_user_policy_id`, `result.item.source_note`, `result.item.provisions`, `result.item.validation`, `result.item.budget_window_years`, `result.item.last_run_at`, `result.item.current_run_id`, `result.item.created_at`, `result.item.updated_at` | | `GET` | `/v2/user-reports?country_id=us` | 200 | `report` | `PolicyEngine-Unauthenticated-User` | `status`, `message`, `result.items`, `result.offset`, `result.limit`, `result.has_more` | -| `PATCH` | `/v2/user-reports/{association_id}?country_id=us` | 200 | `report` | `PolicyEngine-Unauthenticated-User` | `status`, `message`, `result.item.id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.description`, `result.item.user_policy_id`, `result.item.baseline_user_policy_id`, `result.item.source_note`, `result.item.provisions`, `result.item.validation`, `result.item.budget_window_years`, `result.item.last_run_at`, `result.item.updated_at` | +| `PATCH` | `/v2/user-reports/{association_id}?country_id=us` | 200 | `report` | `PolicyEngine-Unauthenticated-User` | `status`, `message`, `result.item.id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.description`, `result.item.user_policy_id`, `result.item.baseline_user_policy_id`, `result.item.source_note`, `result.item.provisions`, `result.item.validation`, `result.item.budget_window_years`, `result.item.last_run_at`, `result.item.current_run_id`, `result.item.updated_at` | | `DELETE` | `/v2/user-reports/{association_id}?country_id=us` | 204 | `report` | `PolicyEngine-Unauthenticated-User` | | -| `GET` | `/v2/shared-reports/{association_id}?country_id=us` | 200 | `report` | none | `status`, `message`, `result.item.id`, `result.item.country_id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.source_note`, `result.item.provisions`, `result.item.validation`, `result.item.budget_window_years`, `result.item.baseline_reform`, `result.item.last_run_at`, `result.item.created_at`, `result.item.updated_at` | +| `GET` | `/v2/shared-reports/{association_id}?country_id=us` | 200 | `report` | none | `status`, `message`, `result.item.id`, `result.item.country_id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.source_note`, `result.item.provisions`, `result.item.validation`, `result.item.budget_window_years`, `result.item.baseline_reform`, `result.item.last_run_at`, `result.item.current_run_id`, `result.item.created_at`, `result.item.updated_at` | ### `user_account_v2` diff --git a/docs/generated/migration_contracts.json b/docs/generated/migration_contracts.json index b247e1fbe..503b92e3b 100644 --- a/docs/generated/migration_contracts.json +++ b/docs/generated/migration_contracts.json @@ -1171,6 +1171,7 @@ "result.item.validation", "result.item.budget_window_years", "result.item.last_run_at", + "result.item.current_run_id", "result.item.created_at", "result.item.updated_at" ] @@ -1200,6 +1201,7 @@ "result.item.validation", "result.item.budget_window_years", "result.item.last_run_at", + "result.item.current_run_id", "result.item.created_at", "result.item.updated_at" ] @@ -1244,6 +1246,7 @@ "result.item.validation", "result.item.budget_window_years", "result.item.last_run_at", + "result.item.current_run_id", "result.item.updated_at" ] }, @@ -1282,6 +1285,7 @@ "result.item.validation", "result.item.budget_window_years", "result.item.last_run_at", + "result.item.current_run_id", "result.item.created_at", "result.item.updated_at" ] @@ -1311,6 +1315,7 @@ "result.item.validation", "result.item.budget_window_years", "result.item.last_run_at", + "result.item.current_run_id", "result.item.created_at", "result.item.updated_at" ] @@ -1355,6 +1360,7 @@ "result.item.validation", "result.item.budget_window_years", "result.item.last_run_at", + "result.item.current_run_id", "result.item.updated_at" ] }, @@ -1388,6 +1394,7 @@ "result.item.budget_window_years", "result.item.baseline_reform", "result.item.last_run_at", + "result.item.current_run_id", "result.item.created_at", "result.item.updated_at" ] diff --git a/migrations/v2/versions/7dcd2cd14330_store_saved_reports_current_runs.py b/migrations/v2/versions/7dcd2cd14330_store_saved_reports_current_runs.py new file mode 100644 index 000000000..715be7863 --- /dev/null +++ b/migrations/v2/versions/7dcd2cd14330_store_saved_reports_current_runs.py @@ -0,0 +1,61 @@ +"""store saved reports current runs + +Revision ID: 7dcd2cd14330 +Revises: 50430a2da57f +Create Date: 2026-12-02 01:34:49.301853 +Generation: uv run alembic -c alembic-v2.ini revision --autogenerate --rev-id 7dcd2cd14330 + +Stores which run of its report a saved report's page shows (D1 · 0a). Adds +two nullable columns to user_report_associations: current_report_run_id, a +report run of an economy or household report, and +current_budget_window_run_id, a budget window's budget-window run. Each is a +foreign key together with report_id, to report_runs and budget_window_runs, +so the run must be one of the saved report's own report's, with RESTRICT, so +a run a saved report shows can't be deleted; each is indexed. Two checks +allow at most one of them, and either only with report_id. report_runs gains +the unique constraint on (id, report_id) the first key refers to; +budget_window_runs already has one. Existing saved reports start with no +current run. The ID was chosen with --rev-id. The operations are exactly as +generated. The downgrade drops the columns, with the runs they hold, and the +constraint. +""" + +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +import sqlmodel + + +revision: str = '7dcd2cd14330' +down_revision: Union[str, None] = '50430a2da57f' +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! ### + op.create_unique_constraint('uq_report_runs_id_report', 'report_runs', ['id', 'report_id']) + op.add_column('user_report_associations', sa.Column('current_report_run_id', sa.Uuid(), nullable=True)) + op.add_column('user_report_associations', sa.Column('current_budget_window_run_id', sa.Uuid(), nullable=True)) + op.create_index(op.f('ix_user_report_associations_current_budget_window_run_id'), 'user_report_associations', ['current_budget_window_run_id'], unique=False) + op.create_index(op.f('ix_user_report_associations_current_report_run_id'), 'user_report_associations', ['current_report_run_id'], unique=False) + op.create_foreign_key('fk_user_report_associations_current_budget_window_run', 'user_report_associations', 'budget_window_runs', ['current_budget_window_run_id', 'report_id'], ['id', 'report_id'], ondelete='RESTRICT') + op.create_foreign_key('fk_user_report_associations_current_report_run', 'user_report_associations', 'report_runs', ['current_report_run_id', 'report_id'], ['id', 'report_id'], ondelete='RESTRICT') + op.create_check_constraint(op.f('ck_user_report_associations_current_run_report'), 'user_report_associations', '(current_report_run_id IS NULL AND current_budget_window_run_id IS NULL) OR report_id IS NOT NULL') + op.create_check_constraint(op.f('ck_user_report_associations_one_current_run'), 'user_report_associations', 'current_report_run_id IS NULL OR current_budget_window_run_id IS NULL') + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_constraint(op.f('ck_user_report_associations_one_current_run'), 'user_report_associations', type_='check') + op.drop_constraint(op.f('ck_user_report_associations_current_run_report'), 'user_report_associations', type_='check') + op.drop_constraint('fk_user_report_associations_current_report_run', 'user_report_associations', type_='foreignkey') + op.drop_constraint('fk_user_report_associations_current_budget_window_run', 'user_report_associations', type_='foreignkey') + op.drop_index(op.f('ix_user_report_associations_current_report_run_id'), table_name='user_report_associations') + op.drop_index(op.f('ix_user_report_associations_current_budget_window_run_id'), table_name='user_report_associations') + op.drop_column('user_report_associations', 'current_budget_window_run_id') + op.drop_column('user_report_associations', 'current_report_run_id') + op.drop_constraint('uq_report_runs_id_report', 'report_runs', type_='unique') + # ### end Alembic commands ### diff --git a/policyengine_api/data/v2/models/associations.py b/policyengine_api/data/v2/models/associations.py index 446e473c5..11688f362 100644 --- a/policyengine_api/data/v2/models/associations.py +++ b/policyengine_api/data/v2/models/associations.py @@ -304,6 +304,14 @@ class UserReportAssociation(TimestampedModel, table=True): owner's saved reform and is cleared when that reform is deleted. A saved report an author published (``published_reports``) can't be repointed to another report, and deleting it deletes the published page. + + A saved report names the run of its report its page shows: a report run of + an economy or household report (``current_report_run_id``), or a budget + window's budget-window run (``current_budget_window_run_id``), never both, + and either only with ``report_id``. Each is a foreign key together with + ``report_id``, so the run must be one of that report's, with ``RESTRICT``, + so a run a saved report shows can't be deleted. Both are null for a saved + report with no current run yet. """ __tablename__ = "user_report_associations" @@ -325,6 +333,31 @@ class UserReportAssociation(TimestampedModel, table=True): f"{BUDGET_WINDOW_MAX_YEARS}", name="ck_user_report_associations_budget_window_years", ), + # The current run is one of the saved report's own report's runs. Named + # here: the naming convention's names are longer than PostgreSQL's + # 63-character limit. + sa.ForeignKeyConstraint( + ["current_report_run_id", "report_id"], + ["report_runs.id", "report_runs.report_id"], + name="fk_user_report_associations_current_report_run", + ondelete="RESTRICT", + ), + sa.ForeignKeyConstraint( + ["current_budget_window_run_id", "report_id"], + ["budget_window_runs.id", "budget_window_runs.report_id"], + name="fk_user_report_associations_current_budget_window_run", + ondelete="RESTRICT", + ), + sa.CheckConstraint( + "current_report_run_id IS NULL OR current_budget_window_run_id IS NULL", + name="ck_user_report_associations_one_current_run", + ), + # A key with a null column isn't checked, so a run needs the report. + sa.CheckConstraint( + "(current_report_run_id IS NULL AND current_budget_window_run_id IS NULL)" + " OR report_id IS NOT NULL", + name="ck_user_report_associations_current_run_report", + ), sa.Index( "ix_user_reports_country_user_created_id", "country_id", @@ -381,6 +414,9 @@ class UserReportAssociation(TimestampedModel, table=True): default=None, sa_type=sa.DateTime(timezone=True), ) + # The run the saved report's page shows; see the class docstring. + current_report_run_id: UUID | None = Field(default=None, index=True) + current_budget_window_run_id: UUID | None = Field(default=None, index=True) # Retired; see the module docstring. country: str | None = Field(default=None, max_length=16) label: str | None = Field(default=None, max_length=255) diff --git a/policyengine_api/data/v2/models/reports.py b/policyengine_api/data/v2/models/reports.py index 9e599f9eb..eeb231876 100644 --- a/policyengine_api/data/v2/models/reports.py +++ b/policyengine_api/data/v2/models/reports.py @@ -279,6 +279,8 @@ class ReportRun(TimestampedModel, table=True): __tablename__ = "report_runs" __table_args__ = ( + # A saved report's current report run is a key to a run of its report. + sa.UniqueConstraint("id", "report_id", name="uq_report_runs_id_report"), sa.UniqueConstraint( "report_id", "idempotency_key", diff --git a/policyengine_api/fastapi_routes/v2/user_reports/response_models.py b/policyengine_api/fastapi_routes/v2/user_reports/response_models.py index eaf66b19d..3d2f68b58 100644 --- a/policyengine_api/fastapi_routes/v2/user_reports/response_models.py +++ b/policyengine_api/fastapi_routes/v2/user_reports/response_models.py @@ -134,6 +134,10 @@ class UserReportItem(StrictUserReportAPIModel): ``baseline_user_policy_id`` the saved reform it was compared with instead of current law; each is null when not set or once that reform is deleted. ``budget_window_years`` is null for a report without a budget window. + ``current_run_id`` is the run of the detailed-save report the saved + report's page shows, as ``GET /v2/reports/{id}?run_id=`` takes it: one of + its report runs, or a budget window's budget-window run; null when it has + none yet, which a saved report naming only a v1 report output never has. """ id: UUID @@ -150,6 +154,7 @@ class UserReportItem(StrictUserReportAPIModel): validation: ReportValidationItem | None budget_window_years: int | None last_run_at: datetime | None + current_run_id: UUID | None created_at: datetime updated_at: datetime @@ -170,6 +175,8 @@ class SharedUserReportItem(StrictUserReportAPIModel): ``report_id`` is the detailed-save report it shows, and ``legacy_report_id`` the v1 report output; one of them is set. + ``current_run_id`` is the run of the detailed-save report its page shows, + as on the owner's read. """ id: UUID @@ -183,6 +190,7 @@ class SharedUserReportItem(StrictUserReportAPIModel): budget_window_years: int | None baseline_reform: SharedBaselineReformItem | None last_run_at: datetime | None + current_run_id: UUID | None created_at: datetime updated_at: datetime diff --git a/policyengine_api/fastapi_routes/v2/user_reports/routes.py b/policyengine_api/fastapi_routes/v2/user_reports/routes.py index 0b5f6784c..41ec651f8 100644 --- a/policyengine_api/fastapi_routes/v2/user_reports/routes.py +++ b/policyengine_api/fastapi_routes/v2/user_reports/routes.py @@ -46,14 +46,17 @@ ) from policyengine_api.services.v2.identity.types import AccountPrincipal -# Only a saved report's writes can refuse its budget window. +# Only a saved report's writes can refuse its budget window or current run. SAVED_REPORT_WRITE_RESPONSES: dict[int | str, dict[str, Any]] = { 400: { **USER_RESOURCE_ERROR_RESPONSES[400], "description": ( f"{USER_RESOURCE_ERROR_RESPONSES[400]['description']} Or " "budget_window_years disagrees with the budget window of the " - "detailed-save report the saved report names." + "detailed-save report the saved report names. Or current_run_id " + "is not a run of that report (a budget window's budget-window run, " + "else one of its report runs), or the saved report names no " + "detailed-save report." ), }, } @@ -148,7 +151,12 @@ def build_v2_user_report_router( "the same country. A saved report naming a detailed-save report " "answers last_run_at as the owner's newest request for one of that " "report's runs through /v2/reports, or null, whatever the request " - "sends; one naming only a v1 report output keeps the value sent." + "sends; one naming only a v1 report output keeps the value sent. " + "An optional current_run_id is the run of the detailed-save report " + "the saved report's page shows, as GET /v2/reports/{id}?run_id= " + "takes it: one of its report runs, or a budget window's " + "budget-window run (400 otherwise); without it the saved report " + "has no current run." ), ) def create_user_report( @@ -210,7 +218,12 @@ def read() -> UserReportPageResponse: "Updates the fields sent. A saved report that names a detailed-save " "report after the update, and whose report_id or last_run_at the " "request sends, answers last_run_at as the owner's newest request for " - "one of that report's runs through /v2/reports, or null. A published " + "one of that report's runs through /v2/reports, or null. " + "current_run_id sets the run of the detailed-save report the page " + "shows, which must be one of the runs of the report the update " + "leaves named (400 otherwise), and null clears it; an update naming " + "another report clears it unless it gives one of that report's " + "runs. Only the owner can change it. A published " "saved report (/v2/user-reports/{id}/publication) can't name another " "report, or have its name, the page's title, cleared, until the page " "is withdrawn (409)." @@ -279,7 +292,8 @@ def build_v2_shared_report_router( "Needs no credential: a saved report's ID is its link, and anyone " "holding it can read the report. The owner and the owner's " "saved-reform IDs are left out; the reform the report was compared " - "with is named instead." + "with is named instead. current_run_id is the run of the " + "detailed-save report the page shows." ), ) def get_shared_report( diff --git a/policyengine_api/services/v2/user_reports/database_connectors/reads.py b/policyengine_api/services/v2/user_reports/database_connectors/reads.py index f820bcfc6..4afb7f5d3 100644 --- a/policyengine_api/services/v2/user_reports/database_connectors/reads.py +++ b/policyengine_api/services/v2/user_reports/database_connectors/reads.py @@ -7,7 +7,9 @@ from sqlmodel import Session, col, select from policyengine_api.data.v2.models import ( + BudgetWindowRun, Report, + ReportRun, UserPolicy, UserReportAssociation, ) @@ -181,3 +183,26 @@ def read_report_budget_window_size( Report.id == report_id, Report.country == country_id ) ).one_or_none() + + +def read_run_of_report_exists( + session: Session, *, report_id: UUID, run_id: UUID, budget_window: bool +) -> bool: + """Return whether ``run_id`` is a run of the report. + + A budget window's runs are its budget-window runs (``budget_window``); + any other report's are its report runs. + """ + if budget_window: + found = session.exec( + select(BudgetWindowRun.id).where( + BudgetWindowRun.id == run_id, BudgetWindowRun.report_id == report_id + ) + ).one_or_none() + else: + found = session.exec( + select(ReportRun.id).where( + ReportRun.id == run_id, ReportRun.report_id == report_id + ) + ).one_or_none() + return found is not None diff --git a/policyengine_api/services/v2/user_reports/services.py b/policyengine_api/services/v2/user_reports/services.py index 6a4024d6b..81aa86b4c 100644 --- a/policyengine_api/services/v2/user_reports/services.py +++ b/policyengine_api/services/v2/user_reports/services.py @@ -12,7 +12,12 @@ that report's runs (``user_report_run_associations``), or null without one, set when it is saved or repointed and as the owner asks for runs, whatever a caller sends; a saved report naming only a v1 report output keeps the -caller's ``last_run_at``. +caller's ``last_run_at``. Its current run, the run of its detailed-save +report its page shows, is one of that report's runs (a budget window's +budget-window run, else a report run), checked in the write's transaction and +held to it by foreign keys; only the owner sets it, saving the report or with +an update, and an update naming another report clears it unless it gives one +of that report's runs. The owner always comes from the verified session principal (a signed-in user or a signed-out browser), and v1 references are checked in a short read-only v1 transaction before the v2 transaction opens. Reads never provision a @@ -60,6 +65,7 @@ read_owned_user_report_row, read_report_budget_window_size, read_report_exists, + read_run_of_report_exists, read_user_report_row, read_user_report_rows, ) @@ -67,6 +73,7 @@ update_user_report, ) from policyengine_api.services.v2.user_reports.transformations import ( + current_run_columns, owned_user_report_input, shared_user_report_read, user_report_page, @@ -78,6 +85,8 @@ require_matching_budget_window, require_owned_user_policy, require_published_report_kept, + require_report_for_current_run, + require_run_of_report, require_stored_report, require_user_report, ) @@ -217,6 +226,71 @@ def validate_saved_budget_window_after_update( ) +def validate_current_run( + session: Session, + *, + country_id: str, + report_id: UUID | None, + current_run_id: UUID | None, +) -> dict[str, UUID | None]: + """Check, in the write's transaction, that a current run is one of the report's. + + Return both current-run columns, the run in the one for the report's kind: + a budget window's run is a budget-window run, any other report's a report + run. A None ``current_run_id`` clears both. Raise + AssociationCurrentRunConflictError for a run without a ``report_id`` or + one that isn't a run of that report. The report was checked already. + """ + require_report_for_current_run(report_id=report_id, current_run_id=current_run_id) + if report_id is None or current_run_id is None: + return current_run_columns(None, budget_window=False) + budget_window = ( + read_report_budget_window_size( + session, country_id=country_id, report_id=report_id + ) + is not None + ) + require_run_of_report( + run_of_report=read_run_of_report_exists( + session, + report_id=report_id, + run_id=current_run_id, + budget_window=budget_window, + ), + run_id=current_run_id, + report_id=report_id, + budget_window=budget_window, + ) + return current_run_columns(current_run_id, budget_window=budget_window) + + +def current_run_after_update( + session: Session, + *, + association: UserReportAssociation, + association_input: UserReportUpdateInput, + report_id: UUID | None, +) -> dict[str, UUID | None]: + """Return the current-run columns an update sets; empty keeps them. + + ``report_id`` is the report the update leaves named. A supplied + ``current_run_id`` is checked against it (``validate_current_run``); + naming another report without one clears the current run, which was a run + of the report named before. + """ + supplied = association_input.model_fields_set + if "current_run_id" in supplied: + return validate_current_run( + session, + country_id=association.country_id, + report_id=report_id, + current_run_id=association_input.current_run_id, + ) + if "report_id" in supplied and report_id != association.report_id: + return current_run_columns(None, budget_window=False) + return {} + + def require_one_report_after_update( association: UserReportAssociation, association_input: UserReportUpdateInput ) -> None: @@ -297,7 +371,9 @@ def create_user_report( owner's saved policy in the same country, or AssociationLinkNotFoundError is raised. A saved detailed-save report's ``last_run_at`` is the owner's newest request for one of its runs, or - null, whatever the caller sends. + null, whatever the caller sends. A ``current_run_id`` must be one of + the detailed-save report's runs, or AssociationCurrentRunConflictError + is raised; without one the saved report has no current run. """ country_id = association_input.country_id require_one_reference( @@ -337,6 +413,13 @@ def create_user_report( ) creation_input = owned_user_report_input( association_input, user_id=owner.user_id + ).model_copy( + update=validate_current_run( + session, + country_id=country_id, + report_id=association_input.report_id, + current_run_id=association_input.current_run_id, + ) ) if association_input.report_id is not None: creation_input = creation_input.model_copy( @@ -462,7 +545,11 @@ def patch_user_report( the principal has no such report in this country. A saved report that names a detailed-save report after the update, and whose ``report_id`` or ``last_run_at`` the update supplies, takes the owner's newest - request for one of that report's runs as ``last_run_at``, or null. + request for one of that report's runs as ``last_run_at``, or null. A + supplied ``current_run_id`` must be one of the runs of the report the + update leaves named, or AssociationCurrentRunConflictError is raised, + and null clears it; an update naming another report without one + clears the current run. """ require_one_reference( "report", @@ -515,6 +602,14 @@ def patch_user_report( ) values = user_report_update_values(association_input) report_id = values.get("report_id", association.report_id) + values.update( + current_run_after_update( + session, + association=association, + association_input=association_input, + report_id=report_id, + ) + ) if ( report_id is not None and { diff --git a/policyengine_api/services/v2/user_reports/transformations.py b/policyengine_api/services/v2/user_reports/transformations.py index 422990839..7535cd054 100644 --- a/policyengine_api/services/v2/user_reports/transformations.py +++ b/policyengine_api/services/v2/user_reports/transformations.py @@ -22,6 +22,27 @@ from policyengine_api.data.v2.models import UserPolicy, UserReportAssociation +def current_run_id(association: UserReportAssociation) -> UUID | None: + """Return the run the saved report's page shows, from whichever column holds it.""" + if association.current_report_run_id is not None: + return association.current_report_run_id + return association.current_budget_window_run_id + + +def current_run_columns( + run_id: UUID | None, *, budget_window: bool +) -> dict[str, UUID | None]: + """Return both current-run columns for ``run_id``, which one holds it. + + A budget window's run is a budget-window run; any other report's is a + report run. A None ``run_id`` clears both. + """ + return { + "current_report_run_id": None if budget_window else run_id, + "current_budget_window_run_id": run_id if budget_window else None, + } + + def user_report_read(association: UserReportAssociation) -> UserReportRead: """Convert a stored association row to the service's read model.""" return UserReportRead( @@ -39,6 +60,7 @@ def user_report_read(association: UserReportAssociation) -> UserReportRead: validation=association.validation, budget_window_years=association.budget_window_years, last_run_at=association.last_run_at, + current_run_id=current_run_id(association), created_at=association.created_at, updated_at=association.updated_at, ) @@ -71,6 +93,7 @@ def shared_user_report_read( else SharedBaselineReformRead(name=baseline_reform.name) ), last_run_at=association.last_run_at, + current_run_id=current_run_id(association), created_at=association.created_at, updated_at=association.updated_at, ) @@ -99,9 +122,13 @@ def owned_user_report_input( *, user_id: UUID, ) -> UserReportCreationInput: - """Add the resolved owner and serialize the provision and validation snapshots.""" + """Add the resolved owner and serialize the provision and validation snapshots. + + The current run is left out: the service stores it in the column for its + report's kind (``current_run_columns``). + """ return UserReportCreationInput( - **fields.model_dump(exclude={"provisions", "validation"}), + **fields.model_dump(exclude={"provisions", "validation", "current_run_id"}), provisions=stored_provisions(fields.provisions), validation=stored_validation(fields.validation), user_id=user_id, @@ -111,10 +138,14 @@ def owned_user_report_input( def user_report_update_values( association_input: UserReportUpdateInput, ) -> dict[str, Any]: - """Return explicitly supplied fields with JSON documents normalized.""" + """Return explicitly supplied fields with JSON documents normalized. + + The current run is left out: the service stores it in the column for its + report's kind (``current_run_columns``). + """ values = association_input.model_dump( exclude_unset=True, - exclude={"provisions", "validation"}, + exclude={"provisions", "validation", "current_run_id"}, ) if "provisions" in association_input.model_fields_set: values["provisions"] = stored_provisions(association_input.provisions) diff --git a/policyengine_api/services/v2/user_reports/types.py b/policyengine_api/services/v2/user_reports/types.py index 5170bbdc5..e2ce7bec9 100644 --- a/policyengine_api/services/v2/user_reports/types.py +++ b/policyengine_api/services/v2/user_reports/types.py @@ -201,7 +201,9 @@ class UserReportCreateFields(_ReportPresentationFields): The saved report names a detailed-save report of the country (``report_id``) or a v1 report output (``legacy_report_id``); a request naming both is refused, since v1 report numbers are not connected to - detailed-save reports. + detailed-save reports. ``current_run_id`` is the run of the detailed-save + report the saved report's page shows: one of its report runs, or a budget + window's budget-window run; none when left out. """ country_id: CountryId @@ -209,6 +211,7 @@ class UserReportCreateFields(_ReportPresentationFields): legacy_report_id: LegacyRecordId | None = None user_policy_id: ResourceId | None = None baseline_user_policy_id: ResourceId | None = None + current_run_id: ResourceId | None = None @model_validator(mode="after") def require_report_reference(self) -> UserReportCreateFields: @@ -233,6 +236,8 @@ class UserReportCreationInput(StrictUserReportModel): validation: StoredJSONObject | None = None budget_window_years: int | None = None last_run_at: AwareDatetime | None = None + current_report_run_id: ResourceId | None = None + current_budget_window_run_id: ResourceId | None = None class UserReportUpdateInput(_ReportPresentationFields): @@ -241,13 +246,15 @@ class UserReportUpdateInput(_ReportPresentationFields): At least one field must be supplied. ``report_id`` repoints the saved report to another detailed-save report and ``legacy_report_id`` to another v1 report output; neither can be cleared, and a saved report never comes - to name both. The saved-reform links are cleared with null. + to name both. The saved-reform links are cleared with null, and so is + ``current_run_id``, the run of the detailed-save report the page shows. """ report_id: ResourceId | None = None legacy_report_id: LegacyRecordId | None = None user_policy_id: ResourceId | None = None baseline_user_policy_id: ResourceId | None = None + current_run_id: ResourceId | None = None @model_validator(mode="after") def require_valid_supplied_field(self) -> UserReportUpdateInput: @@ -264,6 +271,7 @@ def require_valid_supplied_field(self) -> UserReportUpdateInput: "validation", "budget_window_years", "last_run_at", + "current_run_id", } supplied = self.model_fields_set.intersection(mutable_fields) if not supplied: @@ -281,7 +289,8 @@ class UserReportRead: """A stored user-report association as the service returns it to its owner. Unlike SharedUserReportRead, it includes the owner, the description and the - owner's saved-reform links. + owner's saved-reform links. ``current_run_id`` is the run of the + detailed-save report the saved report's page shows, or None. """ id: UUID @@ -298,6 +307,7 @@ class UserReportRead: validation: StoredJSONObject | None budget_window_years: int | None last_run_at: datetime | None + current_run_id: UUID | None created_at: datetime updated_at: datetime @@ -314,7 +324,8 @@ class SharedUserReportRead: """What anyone holding a saved report's link may read. The owner and the owner's saved-reform IDs stay private; the reform the - report was compared with is named instead of linked. + report was compared with is named instead of linked. ``current_run_id`` is + the run of the detailed-save report the saved report's page shows. """ id: UUID @@ -328,6 +339,7 @@ class SharedUserReportRead: budget_window_years: int | None baseline_reform: SharedBaselineReformRead | None last_run_at: datetime | None + current_run_id: UUID | None created_at: datetime updated_at: datetime diff --git a/policyengine_api/services/v2/user_reports/validators.py b/policyengine_api/services/v2/user_reports/validators.py index 9b4cc403b..16a7669a8 100644 --- a/policyengine_api/services/v2/user_reports/validators.py +++ b/policyengine_api/services/v2/user_reports/validators.py @@ -30,6 +30,10 @@ class AssociationBudgetWindowConflictError(AssociationReferenceConflictError): """A saved report's budget_window_years disagrees with the report it names.""" +class AssociationCurrentRunConflictError(AssociationReferenceConflictError): + """A saved report's current_run_id is not a run of the report it names (400).""" + + class PublishedUserReportRepointError(AssociationConflictError): """A published saved report can't name another report until withdrawn (409).""" @@ -93,6 +97,38 @@ def require_matching_budget_window( raise AssociationBudgetWindowConflictError(msg) +def require_report_for_current_run( + *, report_id: UUID | None, current_run_id: UUID | None +) -> None: + """Refuse a current run on a saved report that names no detailed-save report. + + Only a detailed-save report has runs, so a saved report naming only a v1 + report output has none. Raise AssociationCurrentRunConflictError. + """ + if current_run_id is not None and report_id is None: + msg = ( + f"current_run_id {current_run_id} needs a report_id: a saved report " + "naming only a v1 report output has no runs" + ) + raise AssociationCurrentRunConflictError(msg) + + +def require_run_of_report( + *, run_of_report: bool, run_id: UUID, report_id: UUID, budget_window: bool +) -> None: + """Raise AssociationCurrentRunConflictError unless ``run_of_report``. + + ``run_of_report`` says whether ``run_id`` is a run of the report: a + budget-window run of a budget window (``budget_window``), else a report + run of the report. + """ + if run_of_report: + return + kind = "budget-window run" if budget_window else "report run" + msg = f"current_run_id {run_id} is not a {kind} of report {report_id}" + raise AssociationCurrentRunConflictError(msg) + + def require_user_report( association: UserReportAssociation | None, *, diff --git a/tests/contract/registry.py b/tests/contract/registry.py index b3f495853..2df942a4a 100644 --- a/tests/contract/registry.py +++ b/tests/contract/registry.py @@ -473,6 +473,7 @@ class WorkflowContract: "validation", "budget_window_years", "last_run_at", + "current_run_id", ), patch_fields=( "report_id", @@ -486,6 +487,7 @@ class WorkflowContract: "validation", "budget_window_years", "last_run_at", + "current_run_id", ), ), # A saved report's ID is its shareable link: anyone can read it, @@ -508,6 +510,7 @@ class WorkflowContract: "result.item.budget_window_years", "result.item.baseline_reform", "result.item.last_run_at", + "result.item.current_run_id", "result.item.created_at", "result.item.updated_at", ), diff --git a/tests/unit/v2/test_admin_user_routes.py b/tests/unit/v2/test_admin_user_routes.py index df6c25ba0..78abf6750 100644 --- a/tests/unit/v2/test_admin_user_routes.py +++ b/tests/unit/v2/test_admin_user_routes.py @@ -177,6 +177,7 @@ def _saved_items() -> AccountExport: validation=None, budget_window_years=None, last_run_at=None, + current_run_id=None, created_at=CREATED_AT, updated_at=CREATED_AT, ), diff --git a/tests/unit/v2/test_me_routes.py b/tests/unit/v2/test_me_routes.py index f2c5c723d..f74fb2a7a 100644 --- a/tests/unit/v2/test_me_routes.py +++ b/tests/unit/v2/test_me_routes.py @@ -297,6 +297,7 @@ def test_export_serializes_stored_rows_outside_current_input_bounds() -> None: validation={"matched_at": long_text, "map_model_version": "1"}, budget_window_years=None, last_run_at=None, + current_run_id=None, created_at=CREATED_AT, updated_at=CREATED_AT, ) diff --git a/tests/unit/v2/test_saved_report_current_run_routes.py b/tests/unit/v2/test_saved_report_current_run_routes.py index 9eea37525..f60d23992 100644 --- a/tests/unit/v2/test_saved_report_current_run_routes.py +++ b/tests/unit/v2/test_saved_report_current_run_routes.py @@ -30,8 +30,11 @@ def test_the_openapi_document_types_the_current_run_on_every_saved_report_model( ): current_run = schemas[schema_name]["properties"].get("current_run_id") assert current_run is not None, schema_name - assert {"type": "string", "format": "uuid"} in current_run["anyOf"], schema_name - assert {"type": "null"} in current_run["anyOf"], schema_name + # A UUID or null; the request models' UUID type also carries a description. + assert { + (option.get("type"), option.get("format")) + for option in current_run["anyOf"] + } == {("string", "uuid"), ("null", None)}, schema_name for schema_name in ("UserReportItem", "SharedUserReportItem"): assert "current_run_id" in schemas[schema_name]["required"], schema_name diff --git a/tests/unit/v2/test_shared_report_routes.py b/tests/unit/v2/test_shared_report_routes.py index 9409f7233..e63789549 100644 --- a/tests/unit/v2/test_shared_report_routes.py +++ b/tests/unit/v2/test_shared_report_routes.py @@ -48,6 +48,7 @@ def _shared_report_read() -> SharedUserReportRead: budget_window_years=10, baseline_reform=SharedBaselineReformRead(name="Current plan"), last_run_at=LAST_RUN_AT, + current_run_id=None, created_at=CREATED_AT, updated_at=CREATED_AT + timedelta(seconds=1), ) @@ -86,6 +87,7 @@ def test_anyone_reads_a_saved_report_by_its_link_without_the_owner() -> None: "budget_window_years": 10, "baseline_reform": {"name": "Current plan"}, "last_run_at": "2026-02-01T12:00:00Z", + "current_run_id": None, "created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-01T00:00:01Z", } diff --git a/tests/unit/v2/test_user_simulation_report_routes.py b/tests/unit/v2/test_user_simulation_report_routes.py index 08279e8ae..b848d43f7 100644 --- a/tests/unit/v2/test_user_simulation_report_routes.py +++ b/tests/unit/v2/test_user_simulation_report_routes.py @@ -120,6 +120,7 @@ def _report_read() -> UserReportRead: validation=VALIDATION, budget_window_years=10, last_run_at=LAST_RUN_AT, + current_run_id=None, created_at=CREATED_AT, updated_at=CREATED_AT + timedelta(seconds=1), ) From a5ed2fa48e2cb7184c7fd018489f73cb1236c189 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:57:16 +0400 Subject: [PATCH 3/5] Add tests for the current runs revision's head and CI test lists that fail before the fix The expected v2 Alembic head (V2_ALEMBIC_HEAD_REVISION) and the revision chain must end at 7dcd2cd14330, the Alembic check's script must run the revision's integration test, and the v2 integration check must run the saved reports' current-run tests after the managed roles get their privileges. A further test checks that the revision is used exactly as generated; it passes already. Co-Authored-By: Claude Opus 5.5 --- tests/unit/test_alembic_workflows.py | 8 ++- tests/unit/v2/test_alembic_v2_revisions.py | 76 +++++++++++++++++++++- 2 files changed, 81 insertions(+), 3 deletions(-) diff --git a/tests/unit/test_alembic_workflows.py b/tests/unit/test_alembic_workflows.py index 638016e46..7f2cab69d 100644 --- a/tests/unit/test_alembic_workflows.py +++ b/tests/unit/test_alembic_workflows.py @@ -225,6 +225,7 @@ def test_reusable_v2_alembic_check_uses_only_disposable_postgres(): assert "test_alembic_v2_household_job_revisions.py" in lifecycle_script 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 "redis:7.2-alpine" not in workflow assert "RUNTIME_CACHE_TEST_URL" not in workflow assert "test_v2_catalog_installed.py" not in workflow @@ -246,7 +247,10 @@ def test_reusable_v2_integration_check_runs_shared_report_rows_as_managed_roles( def test_reusable_v2_integration_check_runs_the_users_report_run_tests(): - """Reading a report by run and users' run records run as the runtime role.""" + """Reading a report by run, users' run records and saved reports' current runs. + + They run as the runtime role, after the managed roles get their privileges. + """ workflow = _workflow("v2-integration-check.yml") privileges_applied = workflow.index("reconcile_v2_privileges.py apply") @@ -257,7 +261,9 @@ def test_reusable_v2_integration_check_runs_the_users_report_run_tests(): "test_v2_user_budget_window_runs.py", "test_v2_forced_report_reruns.py", "test_v2_user_report_views.py", + "test_v2_saved_report_current_runs.py", ): + assert module in workflow, module assert privileges_applied < workflow.index(module), module diff --git a/tests/unit/v2/test_alembic_v2_revisions.py b/tests/unit/v2/test_alembic_v2_revisions.py index 7b8c09d9a..2fc67889e 100644 --- a/tests/unit/v2/test_alembic_v2_revisions.py +++ b/tests/unit/v2/test_alembic_v2_revisions.py @@ -98,16 +98,21 @@ # household job may hold a household sent in the request. It is the parent # of the published report images revision. INLINE_HOUSEHOLD_JOBS_REVISION = "b2d498bf5fa3" -# The published report images revision, on the inline household jobs revision. +# The published report images revision, on the inline household jobs revision, +# 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. +SAVED_REPORT_CURRENT_RUNS_REVISION = "7dcd2cd14330" 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 == PUBLISHED_REPORT_IMAGES_REVISION + assert V2_ALEMBIC_HEAD_REVISION == SAVED_REPORT_CURRENT_RUNS_REVISION assert [revision.revision for revision in script.walk_revisions()] == [ + SAVED_REPORT_CURRENT_RUNS_REVISION, PUBLISHED_REPORT_IMAGES_REVISION, INLINE_HOUSEHOLD_JOBS_REVISION, PUBLISHED_REPORTS_REVISION, @@ -1391,3 +1396,70 @@ def test_published_report_images_revision_is_generated_as_is() -> None: "op.drop_constraint(", ): assert operation not in body, operation + + +def test_saved_report_current_runs_revision_is_generated_as_is() -> None: + """The current runs revision adds two keyed columns and one constraint. + + It is generated on the published report images revision, with its ID + chosen by ``--rev-id`` and no correction: two nullable run columns on + ``user_report_associations``, each indexed and a ``RESTRICT`` key with + ``report_id``, two checks, and the unique ``(id, report_id)`` on + ``report_runs`` the first key needs. It writes no data, and its downgrade + removes exactly those. + """ + script = ScriptDirectory.from_config(Config(str(REPO / "alembic-v2.ini"))) + children = [ + revision + for revision in script.walk_revisions() + if revision.down_revision == PUBLISHED_REPORT_IMAGES_REVISION + ] + assert [child.revision for child in children] == [ + SAVED_REPORT_CURRENT_RUNS_REVISION + ] + revision = Path(children[0].path).read_text(encoding="utf-8") + 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 {SAVED_REPORT_CURRENT_RUNS_REVISION}" in revision + ) + assert "The operations are exactly as generated." in " ".join(revision.split()) + run_columns = ["current_report_run_id", "current_budget_window_run_id"] + assert ( + re.findall( + r"op\.add_column\('user_report_associations', sa\.Column\('(\w+)'", upgrade + ) + == run_columns + ) + assert re.findall( + r"op\.drop_column\('user_report_associations', '(\w+)'", downgrade + ) == [ + "current_budget_window_run_id", + "current_report_run_id", + ] + assert re.findall(r"op\.create_foreign_key\('(\w+)'", upgrade) == [ + "fk_user_report_associations_current_budget_window_run", + "fk_user_report_associations_current_report_run", + ] + assert upgrade.count("ondelete='RESTRICT'") == 2 + assert re.findall(r"op\.create_unique_constraint\('(\w+)', '(\w+)'", upgrade) == [ + ("uq_report_runs_id_report", "report_runs") + ] + assert re.findall(r"op\.create_check_constraint\(op\.f\('(\w+)'\)", upgrade) == [ + "ck_user_report_associations_current_run_report", + "ck_user_report_associations_one_current_run", + ] + assert len(re.findall(r"op\.drop_constraint\(", downgrade)) == 5 + for body in (upgrade, downgrade): + for operation in ( + "op.execute(", + "op.bulk_insert(", + "op.alter_column(", + "op.create_table(", + "op.drop_table(", + ): + assert operation not in body, operation From abe333d0392193c3c9b11a4de612e802ca947ad0 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:59:17 +0400 Subject: [PATCH 4/5] Make the current runs revision the expected v2 head and run its tests in CI Review round 1 found that V2_ALEMBIC_HEAD_REVISION still named 50430a2da57f, so catalog publication would refuse the migrated database at deploy, and that no CI job ran the two new integration test files. The constant now names 7dcd2cd14330, the Alembic v2 check's script runs the revision's test, and the v2 integration check runs the saved reports' current-run tests with the users' report-run tests, after the managed roles get their privileges. The Alembic skill describes the revision, including the simulation service's model of report_runs, which needs uq_report_runs_id_report too, and releases from before the revision. The model and revision docstrings say the keys check the run's report, not its kind. The Stage 12A document lists current_run_id on the shared read. Each database refusal test names the constraint that refuses it, and a test covers updates that send a run to a saved report naming only a v1 report output, or a budget window's year run. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/test_alembic_v2_lifecycle.sh | 3 +- .github/workflows/v2-integration-check.yml | 4 +- docs/engineering/skills/alembic-migrations.md | 53 +++++++++++++++++++ docs/migration/stage-12a-user-login.md | 8 ++- ...d14330_store_saved_reports_current_runs.py | 4 +- policyengine_api/data/v2/migration_target.py | 2 +- .../data/v2/models/associations.py | 6 ++- ...st_alembic_v2_saved_report_current_runs.py | 49 +++++++++++------ .../test_v2_saved_report_current_runs.py | 29 ++++++++++ 9 files changed, 133 insertions(+), 25 deletions(-) diff --git a/.github/scripts/test_alembic_v2_lifecycle.sh b/.github/scripts/test_alembic_v2_lifecycle.sh index 213c59171..dc67fed63 100755 --- a/.github/scripts/test_alembic_v2_lifecycle.sh +++ b/.github/scripts/test_alembic_v2_lifecycle.sh @@ -22,4 +22,5 @@ uv run --frozen --extra dev pytest -q \ tests/integration/test_alembic_v2_parameter_values_dynamic_id_drop.py \ 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_published_report_images.py \ + tests/integration/test_alembic_v2_saved_report_current_runs.py diff --git a/.github/workflows/v2-integration-check.yml b/.github/workflows/v2-integration-check.yml index 9b6562132..3d5ce5c3e 100644 --- a/.github/workflows/v2-integration-check.yml +++ b/.github/workflows/v2-integration-check.yml @@ -73,8 +73,8 @@ jobs: run: uv run --frozen --extra dev python scripts/reconcile_v2_privileges.py apply --create-missing-roles - name: Verify the managed v2 roles hold their declared privileges run: uv run --frozen --extra dev python scripts/reconcile_v2_privileges.py verify - - name: Test v2 metadata publication, resource routes, the countries list, reports, simulations and users' report runs - run: uv run --frozen --extra dev coverage run --branch -m pytest -q tests/integration/test_v2_catalog_publication.py tests/integration/test_v2_catalog_publication_time_periods.py tests/integration/test_v2_catalog_publication_pruning.py tests/integration/test_v2_catalog_publication_dynamic_parameters.py tests/integration/test_v2_catalog_spm_availability.py tests/integration/test_v2_catalog_statistics.py tests/integration/test_v2_metadata_routes.py tests/integration/test_v2_dynamic_parameter_routes.py tests/integration/test_v2_country_routes.py tests/integration/test_v2_report_reads.py tests/integration/test_v2_report_creation.py tests/integration/test_v2_budget_window_report_reads.py tests/integration/test_v2_budget_window_report_creation.py tests/integration/test_v2_report_runs.py tests/integration/test_v2_report_reads_by_run.py tests/integration/test_v2_user_report_runs.py tests/integration/test_v2_user_report_run_requesters.py tests/integration/test_v2_user_budget_window_runs.py tests/integration/test_v2_forced_report_reruns.py tests/integration/test_v2_user_report_views.py + - name: Test v2 metadata publication, resource routes, the countries list, reports, simulations, users' report runs and saved reports' current runs + run: uv run --frozen --extra dev coverage run --branch -m pytest -q tests/integration/test_v2_catalog_publication.py tests/integration/test_v2_catalog_publication_time_periods.py tests/integration/test_v2_catalog_publication_pruning.py tests/integration/test_v2_catalog_publication_dynamic_parameters.py tests/integration/test_v2_catalog_spm_availability.py tests/integration/test_v2_catalog_statistics.py tests/integration/test_v2_metadata_routes.py tests/integration/test_v2_dynamic_parameter_routes.py tests/integration/test_v2_country_routes.py tests/integration/test_v2_report_reads.py tests/integration/test_v2_report_creation.py tests/integration/test_v2_budget_window_report_reads.py tests/integration/test_v2_budget_window_report_creation.py tests/integration/test_v2_report_runs.py tests/integration/test_v2_report_reads_by_run.py tests/integration/test_v2_user_report_runs.py tests/integration/test_v2_user_report_run_requesters.py tests/integration/test_v2_user_budget_window_runs.py tests/integration/test_v2_forced_report_reruns.py tests/integration/test_v2_user_report_views.py tests/integration/test_v2_saved_report_current_runs.py - name: Test v2 policy and dynamic persistence and immediate v1 mirroring run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_policy_persistence.py tests/integration/test_v2_dynamic_persistence.py tests/integration/test_v1_policy_dual_write.py tests/integration/test_mysql_policy_dual_write.py tests/integration/test_v2_user_policy_mirroring.py tests/integration/test_v1_user_policy_dual_write.py - name: Test signed-in identity provisioning, user associations, saved detailed-save records, user types, published reports and the one-time migration of saved records diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 2b46b4bcf..90d30dd7b 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -1944,3 +1944,56 @@ which the Alembic v2 check runs, downgrades to the parent and upgrades again. integration check runs, checks the key, the checks and the deletions as API v1's runtime role, which holds `SELECT, INSERT, UPDATE, DELETE` on the table. + +### API v2 saved reports' current runs + +Revision `7dcd2cd14330` (parent `50430a2da57f`, ID chosen with `--rev-id`) +was autogenerated after `UserReportAssociation` +(`policyengine_api/data/v2/models/associations.py`) and `ReportRun` +(`policyengine_api/data/v2/models/reports.py`) changed. A saved report stores +the run of its report its page shows (D1 · 0a), which the API answers as +`current_run_id`: + +- `user_report_associations` gains two nullable columns, each indexed: + `current_report_run_id`, a report run of an economy or household report, + and `current_budget_window_run_id`, a budget window's budget-window run; +- each is a foreign key together with `report_id` + (`fk_user_report_associations_current_report_run` to `report_runs (id, + report_id)`, `fk_user_report_associations_current_budget_window_run` to + `budget_window_runs (id, report_id)`), `ON DELETE RESTRICT`, so the run is + one of the saved report's own report's and can't be deleted while a saved + report shows it. The keys check the run's report, not its kind: a budget + window's years are report runs of the window, and only API v2's write + check refuses one as the window's current run; +- `ck_user_report_associations_one_current_run` allows at most one of them, + and `ck_user_report_associations_current_run_report` allows either only + with `report_id`, since a key with a null column isn't checked; +- `report_runs` gains `uq_report_runs_id_report` on `(id, report_id)`, which + the first key refers to; `budget_window_runs` already had + `uq_budget_window_runs_id_report`. + +The operations are exactly as generated. Existing saved reports start with +no current run. The downgrade drops the two columns, with the runs they hold, +and the constraints. + +Deploying it: + +- **The simulation service's models.** PolicyEngine/policyengine-sim-api + models `report_runs` in `policyengine-simulation-persistence` and compares + its 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). Its `ReportRun` needs `uq_report_runs_id_report` too, + or that weekly comparison fails once this revision is on `master`. +- **Releases from before the revision.** One still serving during a + deploy's traffic shift, or restored by a rollback, doesn't know the + columns: repointing a saved report that has a current run to another + report doesn't clear it, so the new key refuses the update. Nothing sets a + current run until app v3 sends one. + +`tests/unit/v2/test_alembic_v2_revisions.py` checks the revision file. +`tests/integration/test_alembic_v2_saved_report_current_runs.py`, which the +Alembic v2 check runs, compares the revision and its downgrade with the +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. diff --git a/docs/migration/stage-12a-user-login.md b/docs/migration/stage-12a-user-login.md index ca40d1205..7d9f6e3be 100644 --- a/docs/migration/stage-12a-user-login.md +++ b/docs/migration/stage-12a-user-login.md @@ -596,13 +596,19 @@ A saved report's ID is its shareable link, so `GET /v2/shared-reports/{id}` takes no credential and sits outside the authenticated user-report router. It never provisions a user. Its item is `{id, country_id, report_id, legacy_report_id, name, source_note, provisions, validation, -budget_window_years, baseline_reform, last_run_at, created_at, updated_at}`: +budget_window_years, baseline_reform, last_run_at, current_run_id, +created_at, updated_at}`: - `user_id`, `user_policy_id`, and `baseline_user_policy_id` are left out; the owner and the owner's saved reforms stay private. - `baseline_reform` is `{"name": ...}` when the report was compared with one of the owner's saved reforms, and null otherwise, including after that reform is deleted. +- `current_run_id` is the run of the detailed-save report the report's page + shows, as on the owner's read (D1 · 0a): one of its report runs, or a + budget window's budget-window run, as `GET /v2/reports/{id}?run_id=` takes + it. Only the owner sets it, saving the report or with `PATCH`; there is no + re-run from a shared link. - Anyone holding the ID can read the report's name, source note, and provisions. There is no shared list or search, and the owner routes stay owner-scoped. diff --git a/migrations/v2/versions/7dcd2cd14330_store_saved_reports_current_runs.py b/migrations/v2/versions/7dcd2cd14330_store_saved_reports_current_runs.py index 715be7863..6689f7b1e 100644 --- a/migrations/v2/versions/7dcd2cd14330_store_saved_reports_current_runs.py +++ b/migrations/v2/versions/7dcd2cd14330_store_saved_reports_current_runs.py @@ -11,7 +11,9 @@ current_budget_window_run_id, a budget window's budget-window run. Each is a foreign key together with report_id, to report_runs and budget_window_runs, so the run must be one of the saved report's own report's, with RESTRICT, so -a run a saved report shows can't be deleted; each is indexed. Two checks +a run a saved report shows can't be deleted; each is indexed. The keys +check the run's report, not its kind: a budget window's year runs are +report runs of the window, which API v2's write check refuses. Two checks allow at most one of them, and either only with report_id. report_runs gains the unique constraint on (id, report_id) the first key refers to; budget_window_runs already has one. Existing saved reports start with no diff --git a/policyengine_api/data/v2/migration_target.py b/policyengine_api/data/v2/migration_target.py index c036c7705..b3e4f7a2c 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 = "50430a2da57f" +V2_ALEMBIC_HEAD_REVISION = "7dcd2cd14330" 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/associations.py b/policyengine_api/data/v2/models/associations.py index 11688f362..5db4d34a6 100644 --- a/policyengine_api/data/v2/models/associations.py +++ b/policyengine_api/data/v2/models/associations.py @@ -310,8 +310,10 @@ class UserReportAssociation(TimestampedModel, table=True): window's budget-window run (``current_budget_window_run_id``), never both, and either only with ``report_id``. Each is a foreign key together with ``report_id``, so the run must be one of that report's, with ``RESTRICT``, - so a run a saved report shows can't be deleted. Both are null for a saved - report with no current run yet. + so a run a saved report shows can't be deleted. The keys check the run's + 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. """ __tablename__ = "user_report_associations" diff --git a/tests/integration/test_alembic_v2_saved_report_current_runs.py b/tests/integration/test_alembic_v2_saved_report_current_runs.py index 017806b50..172bf46f0 100644 --- a/tests/integration/test_alembic_v2_saved_report_current_runs.py +++ b/tests/integration/test_alembic_v2_saved_report_current_runs.py @@ -283,33 +283,46 @@ def test_the_database_refuses_a_current_run_the_saved_report_cannot_have( rows = _saved_report_rows(session) saved_report_id = rows["saved_report"] - for refused_values in ( + # Each write, with the constraint that refuses it. + for constraint, refused_values in ( # A run of another report. - {"current_report_run_id": rows["other_run"]}, + ( + "fk_user_report_associations_current_report_run", + {"current_report_run_id": rows["other_run"]}, + ), # A budget-window run of another report. - {"current_budget_window_run_id": rows["window_run"]}, + ( + "fk_user_report_associations_current_budget_window_run", + {"current_budget_window_run_id": rows["window_run"]}, + ), # Two current runs, each one of the window's own: its budget-window run # and its year's report run. - { - "report_id": rows["window"], - "budget_window_years": 2, - "current_report_run_id": rows["window_year_run"], - "current_budget_window_run_id": rows["window_run"], - }, + ( + "ck_user_report_associations_one_current_run", + { + "report_id": rows["window"], + "budget_window_years": 2, + "current_report_run_id": rows["window_year_run"], + "current_budget_window_run_id": rows["window_run"], + }, + ), # A run on a saved report that names only a v1 report output. - { - "report_id": None, - "legacy_report_id": 615, - "current_report_run_id": rows["economy_run"], - }, + ( + "ck_user_report_associations_current_run_report", + { + "report_id": None, + "legacy_report_id": 615, + "current_report_run_id": rows["economy_run"], + }, + ), ): - with refused(session): + with refused(session, match=constraint): _set_saved_report(session, saved_report_id, **refused_values) _set_saved_report( session, saved_report_id, current_report_run_id=rows["economy_run"] ) - with refused(session): + with refused(session, match="fk_user_report_associations_current_report_run"): session.execute( delete(ReportRun).where(col(ReportRun.id) == rows["economy_run"]) ) @@ -321,7 +334,9 @@ def test_the_database_refuses_a_current_run_the_saved_report_cannot_have( current_report_run_id=None, current_budget_window_run_id=rows["window_run"], ) - with refused(session): + with refused( + session, match="fk_user_report_associations_current_budget_window_run" + ): session.execute( delete(BudgetWindowRun).where(col(BudgetWindowRun.id) == rows["window_run"]) ) diff --git a/tests/integration/test_v2_saved_report_current_runs.py b/tests/integration/test_v2_saved_report_current_runs.py index f1c73bc76..f53edf52e 100644 --- a/tests/integration/test_v2_saved_report_current_runs.py +++ b/tests/integration/test_v2_saved_report_current_runs.py @@ -380,6 +380,35 @@ def test_naming_another_report_clears_the_current_run_unless_one_of_its_runs_is_ ) +def test_an_update_refuses_a_run_the_saved_report_cannot_have( + browsers: list[UUID], reports: ReportsWithRuns, service: V2UserReportService +) -> None: + client = client_for_browser(service, browsers) + v1_report_id = saved_item(client, legacy_report_id=615)["id"] + window_id = saved_item( + client, + report_id=reports.window_id, + budget_window_years=2, + current_run_id=reports.window_run_id, + )["id"] + + v1_report = change(client, v1_report_id, current_run_id=reports.economy_run_id) + window_year = change(client, window_id, current_run_id=reports.window_year_run_id) + + for refused_update, run_id in ( + (v1_report, reports.economy_run_id), + (window_year, reports.window_year_run_id), + ): + assert refused_update.status_code == 400, refused_update.text + assert str(run_id) in refused_update.json()["message"] + assert ( + read_item(client, f"{SAVED_REPORTS}/{v1_report_id}")["current_run_id"] is None + ) + assert read_item(client, f"{SAVED_REPORTS}/{window_id}")["current_run_id"] == str( + reports.window_run_id + ) + + def test_only_the_owner_changes_a_saved_reports_current_run( browsers: list[UUID], reports: ReportsWithRuns, service: V2UserReportService ) -> None: From 85a16a248fd37d07e71cb384c3ec4c5ffb3325a7 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:34:55 +0400 Subject: [PATCH 5/5] Keep the saved-report service free of SQL-named calls and read report_id's own key CI's test shard 6 failed two existing tests on the change: test_user_services_construct_no_sql flags any call named update in a user service, and patch_user_report merged the current-run columns with dict.update, so it now merges them with |=. The saved-report model test expected report_id in one foreign key; it is also in the two current-run keys now, so the test picks the key to reports and checks the two run keys (RESTRICT, to report_runs and budget_window_runs). Co-Authored-By: Claude Opus 5.5 --- .../services/v2/user_reports/services.py | 12 +++++------- tests/unit/v2/test_models.py | 19 +++++++++++++++++-- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/policyengine_api/services/v2/user_reports/services.py b/policyengine_api/services/v2/user_reports/services.py index 81aa86b4c..b2a94032a 100644 --- a/policyengine_api/services/v2/user_reports/services.py +++ b/policyengine_api/services/v2/user_reports/services.py @@ -602,13 +602,11 @@ def patch_user_report( ) values = user_report_update_values(association_input) report_id = values.get("report_id", association.report_id) - values.update( - current_run_after_update( - session, - association=association, - association_input=association_input, - report_id=report_id, - ) + values |= current_run_after_update( + session, + association=association, + association_input=association_input, + report_id=report_id, ) if ( report_id is not None diff --git a/tests/unit/v2/test_models.py b/tests/unit/v2/test_models.py index e83e16843..f8cec40b7 100644 --- a/tests/unit/v2/test_models.py +++ b/tests/unit/v2/test_models.py @@ -642,13 +642,28 @@ def test_saved_simulations_and_reports_name_stored_v2_rows() -> None: "user_policies.id", "countries.id", "reports.id", + # The current run is a run of the saved report's report (D1 · 0a). + "report_runs.id", + "report_runs.report_id", + "budget_window_runs.id", + "budget_window_runs.report_id", } simulation_key = simulations.foreign_key("simulation_id") assert simulation_key.target == "simulations.id" assert simulation_key.ondelete == "RESTRICT" - report_key = reports.foreign_key("report_id") - assert report_key.target == "reports.id" + # report_id is also in the current-run keys; its own key names reports. + (report_key,) = ( + reference + for reference in reports.foreign_keys_of("report_id") + if reference.target == "reports.id" + ) assert report_key.ondelete == "RESTRICT" + for run_column, run_table in ( + ("current_report_run_id", "report_runs"), + ("current_budget_window_run_id", "budget_window_runs"), + ): + run_key = reports.foreign_key(run_column) + assert (run_key.target, run_key.ondelete) == (f"{run_table}.id", "RESTRICT") user_policy_key = reports.foreign_keys_of("user_policy_id")[0] assert user_policy_key.ondelete == "SET NULL" for column_name in ("provisions", "validation"):