From 9286d3f3755fb3a900b7306e5b4e0680de6aca5a Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:52:08 +0400 Subject: [PATCH 1/7] Move the report revision tests into a module of their own The v2 revision test module was at 1,465 of the 1,500 lines allowed for test code. The shared reports, published reports, published report images and saved reports' current runs revision tests move, unchanged, to test_alembic_v2_report_revisions, which imports their revision IDs from the main module, as the household job revision module does. Co-Authored-By: Claude Opus 5.5 --- .../v2/test_alembic_v2_report_revisions.py | 252 ++++++++++++++++++ tests/unit/v2/test_alembic_v2_revisions.py | 227 ---------------- 2 files changed, 252 insertions(+), 227 deletions(-) create mode 100644 tests/unit/v2/test_alembic_v2_report_revisions.py diff --git a/tests/unit/v2/test_alembic_v2_report_revisions.py b/tests/unit/v2/test_alembic_v2_report_revisions.py new file mode 100644 index 000000000..7252c3cbc --- /dev/null +++ b/tests/unit/v2/test_alembic_v2_report_revisions.py @@ -0,0 +1,252 @@ +"""Unit checks of the report revisions of the API v2 Alembic chain. + +The revisions of the report, report run and saved report tables: shared +reports (94dc43079186), published reports (8c867f67f87f), published report +images (50430a2da57f) and saved reports' current runs (7dcd2cd14330). As in +``test_alembic_v2_revisions``, where the chain's order is checked, these tests +read each revision file and check the operations it runs. +""" + +import re +from pathlib import Path + +from alembic.config import Config +from alembic.script import ScriptDirectory + +from policyengine_api.constants import REPO +from tests.unit.v2.test_alembic_v2_revisions import ( + INLINE_HOUSEHOLD_JOBS_REVISION, + PARAMETER_VALUES_DYNAMIC_ID_DROP_REVISION, + PUBLISHED_REPORT_IMAGES_REVISION, + PUBLISHED_REPORTS_REVISION, + SAVED_REPORT_CURRENT_RUNS_REVISION, + SHARED_REPORTS_REVISION, + WITHHELD_AREA_CODES_REVISION, +) + + +def test_shared_reports_revision_is_generated_with_one_documented_correction() -> None: + """The shared reports revision lets identical requests share reports and runs. + + It is generated on the withheld area codes revision, with one correction: + ``user_report_run_associations.trigger`` reuses the report runs' + ``v2_report_run_trigger`` type. It creates only that table, writes no + data, makes three per-user columns nullable (the integration shape test + checks the direction), and its downgrade reverses what the upgrade does. + """ + script = ScriptDirectory.from_config(Config(str(REPO / "alembic-v2.ini"))) + children = [ + revision + for revision in script.walk_revisions() + if revision.down_revision == WITHHELD_AREA_CODES_REVISION + ] + assert len(children) == 1 + assert children[0].revision == SHARED_REPORTS_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" + in revision + ) + assert revision.count("Dialect correction:") == 1 + assert re.search( + r"""name=["']v2_report_run_trigger["'],\s*create_type=False""", upgrade + ) + assert re.findall(r"""op\.create_table\(\s*["'](\w+)["']""", upgrade) == [ + "user_report_run_associations" + ] + assert re.findall(r"""op\.drop_table\(\s*["'](\w+)["']""", downgrade) == [ + "user_report_run_associations" + ] + assert upgrade.count("op.add_column(") == downgrade.count("op.drop_column(") == 8 + # The per-user columns of shared rows become nullable, and back. + for body in (upgrade, downgrade): + assert sorted( + re.findall(r"""op\.alter_column\(\s*["'](\w+)["'],\s*["'](\w+)["']""", body) + ) == [ + ("budget_window_runs", "trigger"), + ("report_runs", "trigger"), + ("reports", "label"), + ] + assert "op.execute(" not in body + assert "op.bulk_insert(" not in body + assert "op.drop_column(" not in upgrade + assert "op.drop_table(" not in upgrade + + +def test_published_reports_revision_is_generated_with_one_documented_correction() -> ( + None +): + """The published reports revision adds published reports and their versions. + + It is generated on the parameter values dynamic_id drop, with one + correction to the order Alembic gave: the unique constraint on + ``user_report_associations (id, report_id)``, which the published + reports' composite foreign key references, is created before that table + and dropped after it. It creates only the two tables, writes no data, + and its downgrade drops what the upgrade creates. + """ + script = ScriptDirectory.from_config(Config(str(REPO / "alembic-v2.ini"))) + children = [ + revision + for revision in script.walk_revisions() + if revision.down_revision == PARAMETER_VALUES_DYNAMIC_ID_DROP_REVISION + ] + assert len(children) == 1 + assert children[0].revision == PUBLISHED_REPORTS_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()") :] + unique_constraint = "uq_user_report_associations_id_report_id" + + assert ( + "Generation: uv run alembic -c alembic-v2.ini revision --autogenerate" + in revision + ) + assert "One correction to the generated operations" in revision + assert re.findall(r"""op\.create_table\(\s*["'](\w+)["']""", upgrade) == [ + "published_reports", + "published_report_versions", + ] + assert re.findall(r"""op\.drop_table\(\s*["'](\w+)["']""", downgrade) == [ + "published_report_versions", + "published_reports", + ] + # The constraint exists before the key that references it, and goes after. + assert upgrade.index(unique_constraint) < upgrade.index( + "op.create_table('published_reports'" + ) + assert downgrade.index(unique_constraint) > downgrade.index( + "op.drop_table('published_reports')" + ) + assert upgrade.count("op.create_unique_constraint(") == 1 + assert downgrade.count("op.drop_constraint(") == 1 + for body in (upgrade, downgrade): + assert "op.execute(" not in body + assert "op.bulk_insert(" not in body + assert "op.alter_column(" not in body + assert "op.drop_table(" not in upgrade + assert "op.create_table(" not in downgrade + + +def test_published_report_images_revision_is_generated_as_is() -> None: + """The card images revision adds one table and nothing else. + + It is generated on the inline household jobs revision with no correction: it + creates ``published_report_images`` with its key to ``published_reports`` + and its three checks, writes no data, and its downgrade drops the table. + """ + script = ScriptDirectory.from_config(Config(str(REPO / "alembic-v2.ini"))) + children = [ + revision + for revision in script.walk_revisions() + if revision.down_revision == INLINE_HOUSEHOLD_JOBS_REVISION + ] + assert [child.revision for child in children] == [PUBLISHED_REPORT_IMAGES_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" + in revision + ) + assert "The operations are exactly as generated." in " ".join(revision.split()) + assert re.findall(r"""op\.create_table\(\s*["'](\w+)["']""", upgrade) == [ + "published_report_images" + ] + assert re.findall(r"""op\.drop_table\(\s*["'](\w+)["']""", downgrade) == [ + "published_report_images" + ] + assert "ondelete='CASCADE'" in upgrade + assert re.findall(r"name=op\.f\('(ck_\w+)'\)", upgrade) == [ + "ck_published_report_images_sha256", + "ck_published_report_images_media_type", + "ck_published_report_images_size", + ] + for body in (upgrade, downgrade): + for operation in ( + "op.execute(", + "op.bulk_insert(", + "op.alter_column(", + "op.add_column(", + "op.create_index(", + "op.create_unique_constraint(", + "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 diff --git a/tests/unit/v2/test_alembic_v2_revisions.py b/tests/unit/v2/test_alembic_v2_revisions.py index 2fc67889e..927f89bb9 100644 --- a/tests/unit/v2/test_alembic_v2_revisions.py +++ b/tests/unit/v2/test_alembic_v2_revisions.py @@ -1073,59 +1073,6 @@ def test_withheld_area_codes_revision_creates_only_the_table_and_its_type() -> N assert "op.bulk_insert(" not in body -def test_shared_reports_revision_is_generated_with_one_documented_correction() -> None: - """The shared reports revision lets identical requests share reports and runs. - - It is generated on the withheld area codes revision, with one correction: - ``user_report_run_associations.trigger`` reuses the report runs' - ``v2_report_run_trigger`` type. It creates only that table, writes no - data, makes three per-user columns nullable (the integration shape test - checks the direction), and its downgrade reverses what the upgrade does. - """ - script = ScriptDirectory.from_config(Config(str(REPO / "alembic-v2.ini"))) - children = [ - revision - for revision in script.walk_revisions() - if revision.down_revision == WITHHELD_AREA_CODES_REVISION - ] - assert len(children) == 1 - assert children[0].revision == SHARED_REPORTS_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" - in revision - ) - assert revision.count("Dialect correction:") == 1 - assert re.search( - r"""name=["']v2_report_run_trigger["'],\s*create_type=False""", upgrade - ) - assert re.findall(r"""op\.create_table\(\s*["'](\w+)["']""", upgrade) == [ - "user_report_run_associations" - ] - assert re.findall(r"""op\.drop_table\(\s*["'](\w+)["']""", downgrade) == [ - "user_report_run_associations" - ] - assert upgrade.count("op.add_column(") == downgrade.count("op.drop_column(") == 8 - # The per-user columns of shared rows become nullable, and back. - for body in (upgrade, downgrade): - assert sorted( - re.findall(r"""op\.alter_column\(\s*["'](\w+)["'],\s*["'](\w+)["']""", body) - ) == [ - ("budget_window_runs", "trigger"), - ("report_runs", "trigger"), - ("reports", "label"), - ] - assert "op.execute(" not in body - assert "op.bulk_insert(" not in body - assert "op.drop_column(" not in upgrade - assert "op.drop_table(" not in upgrade - - def test_user_invitations_revision_adds_its_table_and_the_dismissal_column() -> None: """The revision after shared reports adds invitations and dismissals. @@ -1289,177 +1236,3 @@ def test_report_column_drops_revision_drops_only_the_named_columns() -> None: assert "op.execute(" not in body assert "op.bulk_insert(" not in body assert "op.drop_table(" not in body - - -def test_published_reports_revision_is_generated_with_one_documented_correction() -> ( - None -): - """The published reports revision adds published reports and their versions. - - It is generated on the parameter values dynamic_id drop, with one - correction to the order Alembic gave: the unique constraint on - ``user_report_associations (id, report_id)``, which the published - reports' composite foreign key references, is created before that table - and dropped after it. It creates only the two tables, writes no data, - and its downgrade drops what the upgrade creates. - """ - script = ScriptDirectory.from_config(Config(str(REPO / "alembic-v2.ini"))) - children = [ - revision - for revision in script.walk_revisions() - if revision.down_revision == PARAMETER_VALUES_DYNAMIC_ID_DROP_REVISION - ] - assert len(children) == 1 - assert children[0].revision == PUBLISHED_REPORTS_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()") :] - unique_constraint = "uq_user_report_associations_id_report_id" - - assert ( - "Generation: uv run alembic -c alembic-v2.ini revision --autogenerate" - in revision - ) - assert "One correction to the generated operations" in revision - assert re.findall(r"""op\.create_table\(\s*["'](\w+)["']""", upgrade) == [ - "published_reports", - "published_report_versions", - ] - assert re.findall(r"""op\.drop_table\(\s*["'](\w+)["']""", downgrade) == [ - "published_report_versions", - "published_reports", - ] - # The constraint exists before the key that references it, and goes after. - assert upgrade.index(unique_constraint) < upgrade.index( - "op.create_table('published_reports'" - ) - assert downgrade.index(unique_constraint) > downgrade.index( - "op.drop_table('published_reports')" - ) - assert upgrade.count("op.create_unique_constraint(") == 1 - assert downgrade.count("op.drop_constraint(") == 1 - for body in (upgrade, downgrade): - assert "op.execute(" not in body - assert "op.bulk_insert(" not in body - assert "op.alter_column(" not in body - assert "op.drop_table(" not in upgrade - assert "op.create_table(" not in downgrade - - -def test_published_report_images_revision_is_generated_as_is() -> None: - """The card images revision adds one table and nothing else. - - It is generated on the inline household jobs revision with no correction: it - creates ``published_report_images`` with its key to ``published_reports`` - and its three checks, writes no data, and its downgrade drops the table. - """ - script = ScriptDirectory.from_config(Config(str(REPO / "alembic-v2.ini"))) - children = [ - revision - for revision in script.walk_revisions() - if revision.down_revision == INLINE_HOUSEHOLD_JOBS_REVISION - ] - assert [child.revision for child in children] == [PUBLISHED_REPORT_IMAGES_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" - in revision - ) - assert "The operations are exactly as generated." in " ".join(revision.split()) - assert re.findall(r"""op\.create_table\(\s*["'](\w+)["']""", upgrade) == [ - "published_report_images" - ] - assert re.findall(r"""op\.drop_table\(\s*["'](\w+)["']""", downgrade) == [ - "published_report_images" - ] - assert "ondelete='CASCADE'" in upgrade - assert re.findall(r"name=op\.f\('(ck_\w+)'\)", upgrade) == [ - "ck_published_report_images_sha256", - "ck_published_report_images_media_type", - "ck_published_report_images_size", - ] - for body in (upgrade, downgrade): - for operation in ( - "op.execute(", - "op.bulk_insert(", - "op.alter_column(", - "op.add_column(", - "op.create_index(", - "op.create_unique_constraint(", - "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 74c120cdbd0ae33c17e00fb9fd6ffce24c3ab1d3 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:54:42 +0400 Subject: [PATCH 2/7] =?UTF-8?q?Test=20the=20current-run=20cases=20D1=20?= =?UTF-8?q?=C2=B7=200a's=20review=20found=20untested?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A one-year budget window is saved with null budget_window_years yet takes its budget-window run and refuses its year's run; moving a saved budget window to an economy report's run switches the stored current-run column; the /v2/me/export and admin saved-items reads pass a non-null current run through. They cover behaviour that already exists, so they pass before any change. Co-Authored-By: Claude Opus 5.5 --- .../test_v2_saved_report_current_runs.py | 84 ++++++++++++++++++- tests/unit/v2/test_admin_user_routes.py | 30 +++++++ tests/unit/v2/test_me_routes.py | 42 ++++++++++ 3 files changed, 155 insertions(+), 1 deletion(-) diff --git a/tests/integration/test_v2_saved_report_current_runs.py b/tests/integration/test_v2_saved_report_current_runs.py index f53edf52e..6f7692eac 100644 --- a/tests/integration/test_v2_saved_report_current_runs.py +++ b/tests/integration/test_v2_saved_report_current_runs.py @@ -22,7 +22,7 @@ from sqlalchemy import delete from policyengine_api.constants import REPO -from policyengine_api.data.v2.models import User +from policyengine_api.data.v2.models import User, UserReportAssociation from policyengine_api.services.v2.identity.types import UnauthenticatedPrincipal from policyengine_api.services.v2.user_reports.database_session import ( UserReportDatabaseSession, @@ -49,6 +49,7 @@ from tests.integration.conftest import ManagedV2Roles from tests.integration.stored_report_rows import CatalogRows + from tests.integration.user_report_run_support import StoredWindow VERSIONS = {"country_package_version": "1.5.0", "policyengine_version": "4.2.0"} NEWER_VERSIONS = {**VERSIONS, "policyengine_version": "4.3.0"} @@ -131,6 +132,17 @@ def reports( ) +@pytest.fixture +def one_year_window( + owner_sessions: sessionmaker[Session], catalog: CatalogRows +) -> StoredWindow: + """Store a one-year budget window with one budget-window run and its year's run.""" + with owner_sessions.begin() as session: + return store_window( + session, catalog, years=(2026,), settings=RunSettings(VERSIONS) + ) + + @pytest.fixture def service( managed_v2_roles: ManagedV2Roles, @@ -426,3 +438,73 @@ def test_only_the_owner_changes_a_saved_reports_current_run( assert read_item(owner, f"{SAVED_REPORTS}/{saved_id}")["current_run_id"] == str( reports.economy_run_id ) + + +def test_a_one_year_budget_window_stores_its_budget_window_run( + browsers: list[UUID], one_year_window: StoredWindow, service: V2UserReportService +) -> None: + """A one-year window is saved with no window size, yet runs as a budget window. + + The saved report stores ``budget_window_years`` as null, as for a report + with no window, but its current run is its budget-window run, and the run + of its one year is refused. + """ + client = client_for_browser(service, browsers) + window_id = one_year_window.report.report_id + (year_run_id,) = one_year_window.year_run_ids + + created = saved_item( + client, report_id=window_id, current_run_id=one_year_window.window_run_id + ) + refused = save(client, report_id=window_id, current_run_id=year_run_id) + + assert created["budget_window_years"] is None + assert report_and_run(created) == ( + str(window_id), + str(one_year_window.window_run_id), + ) + assert refused.status_code == 400, refused.text + assert str(year_run_id) in refused.json()["message"] + + +def test_the_owner_moves_a_saved_budget_window_to_an_economy_reports_run( + browsers: list[UUID], + owner_sessions: sessionmaker[Session], + reports: ReportsWithRuns, + service: V2UserReportService, +) -> None: + """Moving from a budget-window run to a report run switches the stored column. + + The update names an economy report and one of its report runs: the run + moves from the budget-window column to the report-run column, which the + database's checks accept. + """ + client = client_for_browser(service, browsers) + saved_id = saved_item( + client, + report_id=reports.window_id, + budget_window_years=2, + current_run_id=reports.window_run_id, + )["id"] + + moved = changed_item( + client, + saved_id, + report_id=reports.economy_id, + budget_window_years=None, + current_run_id=reports.economy_run_id, + ) + with owner_sessions() as session: + stored = session.get(UserReportAssociation, UUID(saved_id)) + assert stored is not None + stored_runs = ( + stored.current_report_run_id, + stored.current_budget_window_run_id, + ) + + assert report_and_run(moved) == ( + str(reports.economy_id), + str(reports.economy_run_id), + ) + assert moved["budget_window_years"] is None + assert stored_runs == (reports.economy_run_id, None) diff --git a/tests/unit/v2/test_admin_user_routes.py b/tests/unit/v2/test_admin_user_routes.py index 78abf6750..006964f20 100644 --- a/tests/unit/v2/test_admin_user_routes.py +++ b/tests/unit/v2/test_admin_user_routes.py @@ -2,6 +2,7 @@ from __future__ import annotations +from dataclasses import replace from datetime import UTC, datetime from uuid import UUID @@ -64,6 +65,9 @@ SAVED_REPORT_ID = UUID("00000000-0000-0000-0000-000000000086") SAVED_DYNAMIC_ID = UUID("00000000-0000-0000-0000-000000000087") DYNAMIC_ID = UUID("00000000-0000-0000-0000-000000000088") +# The detailed-save report a saved report names, and its current run. +REPORT_ID = UUID("00000000-0000-0000-0000-000000000089") +CURRENT_RUN_ID = UUID("00000000-0000-0000-0000-00000000008a") LAST_SEEN_AT = datetime(2026, 2, 1, tzinfo=UTC) SAVED_ITEMS_PATH = f"/v2/admin/users/{TARGET_ID}/saved-items" @@ -334,6 +338,32 @@ def test_admins_read_a_users_saved_items_as_its_own_export_returns_them() -> Non ] +def test_admins_read_the_current_run_of_each_saved_report() -> None: + """A saved detailed-save report's current run reaches the admin read as stored.""" + (saved_report,) = _saved_items().reports + with_run = replace( + saved_report, + report_id=REPORT_ID, + legacy_report_id=None, + current_run_id=CURRENT_RUN_ID, + ) + + def result(name: str, kwargs: dict): + if name == "get_user_saved_items": + return replace(_saved_items(), reports=(with_run,)) + return _result(name, kwargs) + + client, _service = _client(RecordingService(result)) + + response = client.get(SAVED_ITEMS_PATH) + + assert response.status_code == 200 + assert [ + (item["id"], item["report_id"], item["current_run_id"]) + for item in response.json()["result"]["reports"] + ] == [(str(SAVED_REPORT_ID), str(REPORT_ID), str(CURRENT_RUN_ID))] + + def test_saved_items_of_an_unauthenticated_or_absent_user_are_not_found() -> None: not_found_error = SignedInUserNotFoundError("No signed-in user has this ID") diff --git a/tests/unit/v2/test_me_routes.py b/tests/unit/v2/test_me_routes.py index f74fb2a7a..8e1f0f958 100644 --- a/tests/unit/v2/test_me_routes.py +++ b/tests/unit/v2/test_me_routes.py @@ -2,6 +2,7 @@ from __future__ import annotations +from dataclasses import replace from datetime import UTC, datetime from uuid import UUID @@ -54,6 +55,9 @@ ) RECORD_ID = UUID("00000000-0000-0000-0000-000000000065") +# The detailed-save report a saved report names, and its current run. +REPORT_ID = UUID("00000000-0000-0000-0000-000000000067") +CURRENT_RUN_ID = UUID("00000000-0000-0000-0000-000000000068") UNAUTHENTICATED_HEADERS = {"PolicyEngine-Unauthenticated-User": str(BROWSER_USER_ID)} @@ -329,6 +333,44 @@ def result(name: str, kwargs: dict): assert "retired_key" not in body["reports"][0]["provisions"][0] +def test_export_answers_the_current_run_of_each_saved_report() -> None: + """A saved detailed-save report's current run reaches the export as stored.""" + saved_report = UserReportRead( + id=RECORD_ID, + country_id="us", + user_id=OWNER_ID, + report_id=REPORT_ID, + legacy_report_id=None, + name="Child benefit", + description=None, + user_policy_id=None, + baseline_user_policy_id=None, + source_note=None, + provisions=None, + validation=None, + budget_window_years=None, + last_run_at=None, + current_run_id=CURRENT_RUN_ID, + created_at=CREATED_AT, + updated_at=CREATED_AT, + ) + + def result(name: str, kwargs: dict): + if name == "export_account": + return replace(_result(name, kwargs), reports=(saved_report,)) + return _result(name, kwargs) + + client, _service = _client(RecordingService(result)) + + exported = client.get("/v2/me/export?country_id=us") + + assert exported.status_code == 200 + assert [ + (item["report_id"], item["current_run_id"]) + for item in exported.json()["result"]["reports"] + ] == [(str(REPORT_ID), str(CURRENT_RUN_ID))] + + def test_unauthenticated_principals_reach_every_account_operation() -> None: client, service = _client(require_user=signed_out_browser) From 9a1a5f717893b22a4e92984afbb8743ac8c3db17 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:56:48 +0400 Subject: [PATCH 3/7] Test that every report names its type in reports.type A new v2 revision must set each report's type from household_id and budget_window_size (a budget window stored as economy, or a report with no type, takes the type its columns give), then make reports.type required with ck_reports_type: economy, household or budget_window, matching those columns. The database then refuses a type that disagrees with the report. These tests fail until the revision exists. Co-Authored-By: Claude Opus 5.5 --- .../test_alembic_v2_report_types.py | 239 ++++++++++++++++++ .../v2/test_alembic_v2_report_revisions.py | 64 ++++- tests/unit/v2/test_alembic_v2_revisions.py | 3 + 3 files changed, 305 insertions(+), 1 deletion(-) create mode 100644 tests/integration/test_alembic_v2_report_types.py diff --git a/tests/integration/test_alembic_v2_report_types.py b/tests/integration/test_alembic_v2_report_types.py new file mode 100644 index 000000000..2762e04bf --- /dev/null +++ b/tests/integration/test_alembic_v2_report_types.py @@ -0,0 +1,239 @@ +"""Check the revision that makes every report name its type, on disposable Postgres. + +Revision 24b571d7d079, on 7dcd2cd14330, makes ``reports.type`` required and +adds ``ck_reports_type``: the type is ``economy``, ``household`` or +``budget_window``, a report names a household exactly when it is a household +report, and it has a budget window exactly when it is a budget window. Before +it, the simulation service stored a budget window as ``economy`` and some +reports had no type, so the revision first sets each report's type from its +``household_id`` and ``budget_window_size``, the one data step Anthony +approved for it (D1 · 8). The downgrade removes the check and makes the +column optional again; the types it set stay. +""" + +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 select, update +from sqlalchemy.dialects import postgresql +from sqlmodel import col + +from policyengine_api.data.v2.models import Household, Report +from policyengine_api.data.v2.privileges import declared_privileges +from tests.fixtures.database_sessions import ( + grant_declared_v2_privileges, + schema_inspector, +) +from tests.fixtures.integration.alembic_v2 import alembic_v2_config +from tests.integration.simulation_rows import add_row, refused +from tests.integration.stored_report_rows import ( + CatalogRows, + delete_catalog, + store_catalog, + store_report, +) + +if TYPE_CHECKING: + from collections.abc import Iterator + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + from tests.integration.conftest import ManagedV2Roles + +# The revision before it: saved reports' current runs. +PREVIOUS_REVISION = "7dcd2cd14330" +REPORT_TYPES_REVISION = "24b571d7d079" + + +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 _reports_shape(sessions: sessionmaker[Session]) -> dict[str, Any]: + """Reflect the ``reports`` table's columns and checks.""" + with sessions() as session: + inspector = schema_inspector(session) + return { + "columns": { + column["name"]: ( + column["type"].compile(dialect=postgresql.dialect()), + column["nullable"], + ) + for column in inspector.get_columns("reports") + }, + "checks": { + check["name"]: check["sqltext"] + for check in inspector.get_check_constraints("reports") + }, + } + + +def _store_household(session: Session, catalog: CatalogRows) -> UUID: + """Store a household in the catalog's country; ``delete_catalog`` removes it.""" + household_id = uuid4() + add_row( + session, + Household, + id=household_id, + country_id=catalog.country, + household_data={}, + canonicalization_version=1, + content_hash=uuid4().hex * 2, + ) + catalog.household_ids.append(household_id) + return household_id + + +def _set_type(session: Session, report_id: UUID, report_type: str | None) -> None: + session.execute( + update(Report).where(col(Report.id) == report_id).values(type=report_type) + ) + + +def _stored_types(session: Session, report_ids: dict[str, UUID]) -> dict[str, str]: + rows = session.execute( + select(col(Report.id), col(Report.type)).where( + col(Report.id).in_(list(report_ids.values())) + ) + ).all() + type_by_id: dict[UUID, str] = {row[0]: row[1] for row in rows} + return {name: type_by_id[report_id] for name, report_id in report_ids.items()} + + +@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), + ) + + +def test_the_revision_sets_each_reports_type_then_requires_it( + sessions: sessionmaker[Session], +) -> None: + """Each report takes the type its columns give; the downgrade keeps them. + + Before the revision, reports are stored as the simulation service stored + them: a budget window as ``economy``, and some reports with no type. + """ + assert REPORT_TYPES_REVISION in _revision_ids() + config = alembic_v2_config() + command.upgrade(config, "head") + command.downgrade(config, PREVIOUS_REVISION) + parent = _reports_shape(sessions) + with sessions.begin() as session: + catalog = store_catalog(session, "us") + reports = { + "economy": store_report(session, catalog), + "economy_without_type": store_report(session, catalog), + "household": store_report( + session, catalog, household_id=_store_household(session, catalog) + ), + "household_without_type": store_report( + session, catalog, household_id=_store_household(session, catalog) + ), + "window_as_economy": store_report(session, catalog, budget_window_size=3), + "one_year_window_without_type": store_report( + session, catalog, budget_window_size=1 + ), + } + report_ids = {name: report.report_id for name, report in reports.items()} + for name, stored_type in ( + ("economy", "economy"), + ("economy_without_type", None), + ("household", "household"), + ("household_without_type", None), + ("window_as_economy", "economy"), + ("one_year_window_without_type", None), + ): + _set_type(session, report_ids[name], stored_type) + + try: + command.upgrade(config, REPORT_TYPES_REVISION) + revision = _reports_shape(sessions) + with sessions() as session: + set_types = _stored_types(session, report_ids) + command.downgrade(config, PREVIOUS_REVISION) + downgraded = _reports_shape(sessions) + with sessions() as session: + kept_types = _stored_types(session, report_ids) + finally: + with sessions.begin() as session: + delete_catalog(session, catalog) + + assert set_types == { + "economy": "economy", + "economy_without_type": "economy", + "household": "household", + "household_without_type": "household", + "window_as_economy": "budget_window", + "one_year_window_without_type": "budget_window", + } + assert kept_types == set_types + assert parent["columns"]["type"] == ("VARCHAR(128)", True) + assert revision["columns"] == { + **parent["columns"], + "type": ("VARCHAR(128)", False), + } + assert set(revision["checks"]) - set(parent["checks"]) == {"ck_reports_type"} + assert { + name: sqltext + for name, sqltext in revision["checks"].items() + if name != "ck_reports_type" + } == parent["checks"] + assert downgraded == parent + + +def test_the_database_refuses_a_type_that_disagrees_with_the_report( + sessions: sessionmaker[Session], +) -> None: + """A report's type must be one of the three, and match its columns.""" + command.upgrade(alembic_v2_config(), "head") + with sessions() as session: + try: + catalog = store_catalog(session, "us") + economy = store_report(session, catalog).report_id + household = store_report( + session, catalog, household_id=_store_household(session, catalog) + ).report_id + window = store_report(session, catalog, budget_window_size=2).report_id + + # Each write, with the constraint that refuses it. + for constraint, report_id, refused_type in ( + ("ck_reports_type", economy, "budget_window"), + ("ck_reports_type", economy, "household"), + ("ck_reports_type", economy, "single_year"), + ("ck_reports_type", household, "economy"), + ("ck_reports_type", window, "economy"), + ('"type" of relation "reports"', window, None), + ): + with refused(session, match=constraint): + _set_type(session, report_id, refused_type) + + assert _stored_types( + session, + {"economy": economy, "household": household, "window": window}, + ) == { + "economy": "economy", + "household": "household", + "window": "budget_window", + } + finally: + session.rollback() diff --git a/tests/unit/v2/test_alembic_v2_report_revisions.py b/tests/unit/v2/test_alembic_v2_report_revisions.py index 7252c3cbc..155ba6ca1 100644 --- a/tests/unit/v2/test_alembic_v2_report_revisions.py +++ b/tests/unit/v2/test_alembic_v2_report_revisions.py @@ -2,7 +2,8 @@ The revisions of the report, report run and saved report tables: shared reports (94dc43079186), published reports (8c867f67f87f), published report -images (50430a2da57f) and saved reports' current runs (7dcd2cd14330). As in +images (50430a2da57f), saved reports' current runs (7dcd2cd14330) and report +types (24b571d7d079). As in ``test_alembic_v2_revisions``, where the chain's order is checked, these tests read each revision file and check the operations it runs. """ @@ -19,6 +20,7 @@ PARAMETER_VALUES_DYNAMIC_ID_DROP_REVISION, PUBLISHED_REPORT_IMAGES_REVISION, PUBLISHED_REPORTS_REVISION, + REPORT_TYPES_REVISION, SAVED_REPORT_CURRENT_RUNS_REVISION, SHARED_REPORTS_REVISION, WITHHELD_AREA_CODES_REVISION, @@ -250,3 +252,63 @@ def test_saved_report_current_runs_revision_is_generated_as_is() -> None: "op.drop_table(", ): assert operation not in body, operation + + +def test_report_types_revision_is_generated_with_one_approved_data_step() -> None: + """Every report names its type: ``reports.type`` becomes required, with a check. + + It is generated, with its ID chosen through ``--rev-id``, after + ``Report.type`` became required and ``ck_reports_type`` was added. Its one + hand-written step, which Anthony approved for it (D1 · 8), runs first and + sets each report's type from its ``household_id`` and + ``budget_window_size``, since the simulation service stored a budget window + as ``economy`` and some reports have none. The generated downgrade drops + the check and makes the column optional again. + """ + paths = sorted( + (REPO / "migrations/v2/versions").glob(f"{REPORT_TYPES_REVISION}_*.py") + ) + assert len(paths) == 1 + revision = paths[0].read_text(encoding="utf-8") + upgrade = revision[ + revision.index("def upgrade()") : revision.index("def downgrade()") + ] + downgrade = revision[revision.index("def downgrade()") :] + parent = SAVED_REPORT_CURRENT_RUNS_REVISION + + assert ( + "Generation: uv run alembic -c alembic-v2.ini revision --autogenerate " + f"--rev-id {REPORT_TYPES_REVISION}" + ) in revision + assert re.search( + rf"""down_revision: Union\[str, None\] = ["']{parent}["']""", revision + ) + assert "D1 · 8" in revision + assert "correction" not in revision.lower() + assert sorted(re.findall(r"op\.\w+", upgrade)) == [ + "op.alter_column", + "op.create_check_constraint", + "op.execute", + "op.f", + ] + assert re.search( + r"""op\.alter_column\(\s*["']reports["'],\s*["']type["'][^)]*nullable=False""", + upgrade, + ) + assert re.search( + r"""op\.create_check_constraint\(\s*op\.f\(["']ck_reports_type["']\),\s*["']reports["']""", + upgrade, + ) + # The data step runs before the generated operations that need it. + assert upgrade.count("Approved hand-written data step") == 1 + assert upgrade.index("op.execute(") < upgrade.index("op.alter_column(") + assert sorted(re.findall(r"op\.\w+", downgrade)) == [ + "op.alter_column", + "op.drop_constraint", + "op.f", + ] + assert re.search( + r"""op\.alter_column\(\s*["']reports["'],\s*["']type["'][^)]*nullable=True""", + downgrade, + ) + assert "op.bulk_insert(" not in revision diff --git a/tests/unit/v2/test_alembic_v2_revisions.py b/tests/unit/v2/test_alembic_v2_revisions.py index 927f89bb9..e399cb9f3 100644 --- a/tests/unit/v2/test_alembic_v2_revisions.py +++ b/tests/unit/v2/test_alembic_v2_revisions.py @@ -104,6 +104,9 @@ # 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" +# The report types revision, on the saved reports' current runs revision: +# every report names its type. +REPORT_TYPES_REVISION = "24b571d7d079" def test_v2_revision_chain_has_generated_policy_and_user_identity_changes() -> None: From 36c91cdab8ccca21af5c7a75ba244b944647a0f4 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:11:25 +0400 Subject: [PATCH 4/7] Require each report's type and read it in place of the derived kind MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A v2 revision (24b571d7d079) sets each stored report's type from its household_id and budget_window_size, then makes reports.type NOT NULL and adds ck_reports_type: economy, household or budget_window, agreeing with those columns. The data step is the hand-written one approved for D1 · 8; the operations are as generated. API v1 reads reports.type wherever it told report types apart from their columns (stored-report reads and re-runs, published-report runs), and removes report_kind and the unused set_report_type. A saved report's create or update reads the report it names once, through read_named_report, and checks its budget window and current run against that read. Tests and fixtures that store reports now give each its type. Co-Authored-By: Claude Opus 5.5 --- changelog.d/required-report-types.changed.md | 1 + ...24b571d7d079_require_each_report_s_type.py | 73 +++++++++ policyengine_api/data/v2/migration_target.py | 2 +- policyengine_api/data/v2/models/reports.py | 28 +++- policyengine_api/data/v2/report_runs.py | 34 +--- .../services/v2/published_reports/services.py | 15 +- .../v2/published_reports/transformations.py | 10 +- .../services/v2/stored_reports/services.py | 33 ++-- .../v2/stored_reports/transformations.py | 11 -- .../services/v2/stored_reports/types.py | 7 +- .../services/v2/stored_reports/validators.py | 36 +++-- .../user_reports/database_connectors/reads.py | 33 ++-- .../services/v2/user_reports/services.py | 148 ++++++++++-------- .../services/v2/user_reports/types.py | 17 ++ .../services/v2/user_reports/validators.py | 14 +- tests/integration/stored_report_rows.py | 8 +- .../integration/test_alembic_v2_lifecycle.py | 1 + .../test_alembic_v2_saved_item_keys.py | 1 + .../test_alembic_v2_simulation_runs.py | 9 ++ .../test_alembic_v2_withheld_area_codes.py | 1 + .../test_v2_catalog_publication.py | 1 + .../integration/test_v2_household_reports.py | 1 + .../test_v2_saved_detailed_save_records.py | 17 +- .../integration/test_v2_shared_report_rows.py | 3 + .../test_v2_simulation_role_privileges.py | 1 + .../test_v2_user_identity_persistence.py | 1 + tests/unit/v2/published_report_support.py | 1 + tests/unit/v2/sqlite_report_rows.py | 1 + .../v2/test_alembic_v2_report_revisions.py | 4 +- .../unit/v2/test_budget_window_year_checks.py | 20 ++- tests/unit/v2/test_household_report_reads.py | 2 + .../test_report_dataset_independent_keys.py | 1 + tests/unit/v2/test_report_rerun_service.py | 6 + tests/unit/v2/test_report_run_creation.py | 1 + tests/unit/v2/test_report_runs.py | 38 +---- 35 files changed, 337 insertions(+), 243 deletions(-) create mode 100644 changelog.d/required-report-types.changed.md create mode 100644 migrations/v2/versions/24b571d7d079_require_each_report_s_type.py diff --git a/changelog.d/required-report-types.changed.md b/changelog.d/required-report-types.changed.md new file mode 100644 index 000000000..9548caead --- /dev/null +++ b/changelog.d/required-report-types.changed.md @@ -0,0 +1 @@ +Every API v2 report now names its type in `reports.type`: `economy`, `household` or `budget_window`. A v2 revision sets each stored report's type from whether it names a household or has a budget window (the simulation service stored budget windows as `economy` before), then makes the column required and adds the check `ck_reports_type`, which refuses a type that disagrees with those columns. API v1 reads the stored type to tell report types apart, and saving or updating a saved report reads the report it names once. diff --git a/migrations/v2/versions/24b571d7d079_require_each_report_s_type.py b/migrations/v2/versions/24b571d7d079_require_each_report_s_type.py new file mode 100644 index 000000000..060795d17 --- /dev/null +++ b/migrations/v2/versions/24b571d7d079_require_each_report_s_type.py @@ -0,0 +1,73 @@ +"""require each report's type + +Revision ID: 24b571d7d079 +Revises: 7dcd2cd14330 +Create Date: 2026-12-03 22:58:07.202943 +Generation: uv run alembic -c alembic-v2.ini revision --autogenerate --rev-id 24b571d7d079 + +Makes every report name its type (D1 · 8): reports.type becomes NOT NULL, +and ck_reports_type requires it to be economy, household or budget_window, +with a household report naming its household and a budget window having a +size, of one year or more. The ID was chosen with --rev-id; the operations +are exactly as generated. + +The data step before them is hand-written: the user's explicit migration +decision for D1 · 8 (2026-12-03), which the generated-only rule for revisions +requires. Until D1 · 7a the simulation service stored a budget window's type +as economy, and a report may have no type, so the step sets every report +whose type differs from the one its household_id and budget_window_size give +to that type. The simulation service writes budget_window from D1 · 7a on, +which must be deployed before this revision runs, or its next budget window +would fail the check. The downgrade drops the check and makes the column +optional again; the types the step set stay, since the earlier schema +allows them. +""" + +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +import sqlmodel + + +revision: str = '24b571d7d079' +down_revision: Union[str, None] = '7dcd2cd14330' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # Approved hand-written data step (the user's migration decision, D1 · 8, + # 2026-12-03): set each report's type from the columns its kind sets, + # before the generated operations require it and check it. + reports = sa.table( + "reports", + sa.column("type", sa.String), + sa.column("household_id", sa.Uuid), + sa.column("budget_window_size", sa.Integer), + ) + type_from_columns = sa.case( + (reports.c.household_id.is_not(None), "household"), + (reports.c.budget_window_size.is_not(None), "budget_window"), + else_="economy", + ) + op.execute( + reports.update() + .where(reports.c.type.is_distinct_from(type_from_columns)) + .values(type=type_from_columns) + ) + # ### commands auto generated by Alembic - please adjust! ### + op.alter_column('reports', 'type', + existing_type=sa.VARCHAR(length=128), + nullable=False) + op.create_check_constraint(op.f('ck_reports_type'), 'reports', "type IN ('economy', 'household', 'budget_window') AND (type = 'household') = (household_id IS NOT NULL) AND (type = 'budget_window') = (budget_window_size IS NOT NULL)") + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_constraint(op.f('ck_reports_type'), 'reports', type_='check') + op.alter_column('reports', 'type', + existing_type=sa.VARCHAR(length=128), + nullable=True) + # ### end Alembic commands ### diff --git a/policyengine_api/data/v2/migration_target.py b/policyengine_api/data/v2/migration_target.py index b3e4f7a2c..d3fff7a6b 100644 --- a/policyengine_api/data/v2/migration_target.py +++ b/policyengine_api/data/v2/migration_target.py @@ -27,7 +27,7 @@ from sqlmodel import Session V2_ALEMBIC_DISPOSABLE_TEST = "V2_ALEMBIC_DISPOSABLE_TEST" -V2_ALEMBIC_HEAD_REVISION = "7dcd2cd14330" +V2_ALEMBIC_HEAD_REVISION = "24b571d7d079" 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/reports.py b/policyengine_api/data/v2/models/reports.py index eeb231876..26905a6e2 100644 --- a/policyengine_api/data/v2/models/reports.py +++ b/policyengine_api/data/v2/models/reports.py @@ -7,12 +7,12 @@ from datetime import datetime from enum import StrEnum -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, Literal, get_args from uuid import UUID import sqlalchemy as sa from sqlalchemy.dialects import postgresql -from sqlmodel import Field, Relationship +from sqlmodel import AutoString, Field, Relationship from policyengine_api.data.v2.models.base import ( UNFAILED_UNFORCED_RUNS, @@ -45,6 +45,13 @@ WithheldAreaCode, ) +# What a report compares, as ``reports.type`` names it: two economy +# simulations, two household simulations, or two economy simulations in each +# year of a budget window. +ReportType = Literal["economy", "household", "budget_window"] +# The SQL list of every report type, for ``ck_reports_type``. +REPORT_TYPES_SQL = ", ".join(f"'{report_type}'" for report_type in get_args(ReportType)) + # A budget window compares at most this many years, none after LAST_YEAR. MAX_BUDGET_WINDOW_YEARS = 75 LAST_YEAR = 2200 @@ -82,6 +89,12 @@ class Report(TimestampedModel, table=True): A report is shared by everyone who asks for it, so it names no user. A report's name and description are on each user's saved report. + ``type`` says what the report compares (``ReportType``), and readers take + it from there. The simulation service sets it; ``ck_reports_type`` keeps + it in step with ``household_id`` and ``budget_window_size``. A budget + window's runs are its budget-window runs; any other report's, its report + runs. + The simulation service finds a report by ``definition_key``, the SHA-256 of what it compares (its country, type, each side's policy and dynamic, the dataset name, region code, year and SPM selection both sides share, @@ -104,6 +117,15 @@ class Report(TimestampedModel, table=True): f"AND year IS NOT NULL AND year + budget_window_size - 1 <= {LAST_YEAR})", name="ck_reports_budget_window_size", ), + # A report's type is one of the three, and agrees with the columns its + # kind sets: a household report names its household, and a budget + # window has a size (one year or more). + sa.CheckConstraint( + f"type IN ({REPORT_TYPES_SQL}) " + "AND (type = 'household') = (household_id IS NOT NULL) " + "AND (type = 'budget_window') = (budget_window_size IS NOT NULL)", + name="ck_reports_type", + ), sa.Index("ix_reports_country_type_created_at", "country", "type", "created_at"), sa.UniqueConstraint("key_version", "definition_key"), sa.CheckConstraint("key_version > 0", name="ck_reports_key_version"), @@ -122,7 +144,7 @@ class Report(TimestampedModel, table=True): ) country: str = Field(max_length=16) - type: str | None = Field(default=None, max_length=128) + type: ReportType = Field(sa_type=AutoString(length=128)) tax_benefit_model_id: UUID = Field( foreign_key="tax_benefit_models.id", ondelete="RESTRICT", diff --git a/policyengine_api/data/v2/report_runs.py b/policyengine_api/data/v2/report_runs.py index 61c14fc07..94647ffca 100644 --- a/policyengine_api/data/v2/report_runs.py +++ b/policyengine_api/data/v2/report_runs.py @@ -1,8 +1,8 @@ """Durable report-definition and report-run operations for API v2-alpha. -``set_report_type`` and ``create_report_run`` lock ``reports`` rows with -``SELECT ... FOR UPDATE``, which needs ``UPDATE`` on ``reports``; no managed -role holds it, so none can run them. ``complete_report_run`` sets +``create_report_run`` locks ``reports`` rows with ``SELECT ... FOR +UPDATE``, which needs ``UPDATE`` on ``reports``; no managed role holds it, +so none can run it. ``complete_report_run`` sets ``markdown``, which no managed role may update either. The simulation API creates and completes reports and report runs with its own code. """ @@ -37,10 +37,6 @@ class ReportRunNotFoundError(LookupError): """Raised when a requested durable report run does not exist.""" -class ReportTypeImmutableError(ValueError): - """Raised when a report type change would reinterpret existing runs.""" - - class ReportRunStateError(ValueError): """Raised when a worker transition is invalid for the durable run.""" @@ -83,30 +79,6 @@ def _locked_report(session: Session, report_id: UUID) -> Report: return report -def set_report_type( - session: Session, - *, - report_id: UUID, - report_type: str | None, -) -> Report: - """Set a report's optional type only while it has no execution history.""" - report = _locked_report(session, report_id) - if report.type == report_type: - return report - - existing_run_id = session.exec( - select(ReportRun.id).where(ReportRun.report_id == report_id).limit(1) - ).first() - if existing_run_id is not None: - msg = "report type is immutable after the first report run" - raise ReportTypeImmutableError(msg) - - report.type = report_type - session.add(report) - session.flush() - return report - - def create_report_run( session: Session, *, diff --git a/policyengine_api/services/v2/published_reports/services.py b/policyengine_api/services/v2/published_reports/services.py index 689464c3e..f230d4092 100644 --- a/policyengine_api/services/v2/published_reports/services.py +++ b/policyengine_api/services/v2/published_reports/services.py @@ -92,7 +92,6 @@ require_unpublished, require_versions, ) -from policyengine_api.services.v2.stored_reports.transformations import report_kind from policyengine_api.services.v2.user_reports.database_connectors.reads import ( lock_owned_user_report_row, read_owned_user_policy_row, @@ -211,15 +210,13 @@ def _succeeded_run(session: Session, *, report_id: UUID, run_id: UUID) -> Publis has no such run, and PublicationRunNotSucceededError unless it has succeeded. """ - kind = report_kind( - require_report_row( - publication_reads.read_report_row(session, report_id=report_id), - report_id=report_id, - ) - ) + report_type = require_report_row( + publication_reads.read_report_row(session, report_id=report_id), + report_id=report_id, + ).type read_status = ( publication_reads.read_budget_window_run_status - if kind == "budget_window" + if report_type == "budget_window" else publication_reads.read_report_run_status ) require_succeeded_run( @@ -227,7 +224,7 @@ def _succeeded_run(session: Session, *, report_id: UUID, run_id: UUID) -> Publis report_id=report_id, run_id=run_id, ) - return published_run(kind, run_id) + return published_run(report_type, run_id) class V2PublishedReportService: diff --git a/policyengine_api/services/v2/published_reports/transformations.py b/policyengine_api/services/v2/published_reports/transformations.py index 4a08397b4..2bfcfef1c 100644 --- a/policyengine_api/services/v2/published_reports/transformations.py +++ b/policyengine_api/services/v2/published_reports/transformations.py @@ -39,16 +39,14 @@ PublishedReportVersion, ReportRun, ) + from policyengine_api.data.v2.models.reports import ReportType from policyengine_api.services.v2.published_reports.types import ( PublicationFields, PublicationUpdateInput, PublishedReportCardRow, ShownVersions, ) - from policyengine_api.services.v2.stored_reports.types import ( - ReportKind, - StoredReportRead, - ) + from policyengine_api.services.v2.stored_reports.types import StoredReportRead from policyengine_api.services.v2.user_reports.types import SharedUserReportRead @@ -89,9 +87,9 @@ def publication_update_values(edit: PublicationUpdateInput) -> dict[str, Any]: return values -def published_run(kind: ReportKind, run_id: UUID) -> PublishedRun: +def published_run(report_type: ReportType, run_id: UUID) -> PublishedRun: """Return the run a version shows: a budget window's is a budget-window run.""" - if kind == "budget_window": + if report_type == "budget_window": return PublishedRun(budget_window_run_id=run_id) return PublishedRun(report_run_id=run_id) diff --git a/policyengine_api/services/v2/stored_reports/services.py b/policyengine_api/services/v2/stored_reports/services.py index 95f50e066..4038fbfc6 100644 --- a/policyengine_api/services/v2/stored_reports/services.py +++ b/policyengine_api/services/v2/stored_reports/services.py @@ -118,7 +118,6 @@ household_report_summary_read, listed_reports, report_cliffs, - report_kind, report_policy_ids, report_read, report_runs_read, @@ -206,7 +205,7 @@ def _with_run( when the report has no such run. """ report_id = stored.report.id - if report_kind(stored.report) == "budget_window": + if stored.report.type == "budget_window": window_run = require_report_run( read_budget_window_run(session, report_id=report_id, run_id=run_id), report_id=report_id, @@ -278,11 +277,11 @@ def _record_request(recording: _RunRecording, request: ReportRunRequest) -> UUID def _summary_read( stored: StoredReportRows, *, current_versions: PackageVersions ) -> StoredReportSummaryRead: - """Return the report's definition and the run read, as its kind reads them.""" - kind = report_kind(stored.report) - if kind == "household": + """Return the report's definition and the run read, as its type reads them.""" + report_type = stored.report.type + if report_type == "household": return household_report_summary_read(stored, current_versions=current_versions) - if kind == "budget_window": + if report_type == "budget_window": return budget_window_summary_read(stored, current_versions=current_versions) return report_summary_read(stored, current_versions=current_versions) @@ -398,10 +397,10 @@ def _read_report( requester=requester, recorded_user_id=recorded_user_id, ) - kind = report_kind(stored.report) - if kind == "budget_window": + report_type = stored.report.type + if report_type == "budget_window": return self._budget_window(session, stored) - if kind == "household": + if report_type == "household": return self._household_report(session, stored) return self._economy_report(session, stored) @@ -431,9 +430,7 @@ def get_budget_window_year( """ with _storage_failures(), self._database_session.read() as session: stored = _stored_report(session, country_id=country_id, report_id=report_id) - require_budget_window_year( - stored.report, kind=report_kind(stored.report), year=year - ) + require_budget_window_year(stored.report, year=year) stored = _as_seen_with_run( session, stored, run_id=run_id, requester=requester ) @@ -700,22 +697,22 @@ def rerun_report( requested_at = utc_now() with _storage_failures(), self._database_session.read() as session: stored = _stored_report(session, country_id=country_id, report_id=report_id) - kind = report_kind(stored.report) + report_type = stored.report.type recording = self._run_recording(requester) if force: require_admin_to_force(None if recording is None else recording.requester) - require_cliffs_available(kind, include_cliffs=include_cliffs) + require_cliffs_available(report_type, include_cliffs=include_cliffs) started = submissions.rerun_report( ReportRerunInput( country_id=country_id, report_id=report_id, - kind=kind, + kind=report_type, force=force, policy_ids=report_policy_ids(stored), include_cliffs=include_cliffs, ) ) - if kind != "budget_window": + if report_type != "budget_window": request = ReportRunRequest( country_id=country_id, report_id=report_id, @@ -766,9 +763,9 @@ def list_report_runs( with _storage_failures(), self._database_session.read() as session: stored = _stored_report(session, country_id=country_id, report_id=report_id) current_versions = self._current_versions(country_id) - # A kind added to ReportKind later fails mypy (a missing return) + # A type added to ReportType later fails mypy (a missing return) # until it has a case here. - match report_kind(stored.report): + match stored.report.type: case "budget_window": window_runs = read_budget_window_runs(session, report_id=report_id) return budget_window_runs_read( diff --git a/policyengine_api/services/v2/stored_reports/transformations.py b/policyengine_api/services/v2/stored_reports/transformations.py index e67e76911..ab43213d3 100644 --- a/policyengine_api/services/v2/stored_reports/transformations.py +++ b/policyengine_api/services/v2/stored_reports/transformations.py @@ -31,7 +31,6 @@ from policyengine_api.data.v2.models import ( BudgetWindowRun, CliffImpact, - Report, ReportRun, Simulation, ) @@ -51,22 +50,12 @@ ) from policyengine_api.services.v2.stored_reports.types import ( CliffCalculationStatusName, - ReportKind, ReportRunsKind, ReportStatusName, StoredReportRows, ) -def report_kind(report: Report) -> ReportKind: - """Return what the report compares, from the columns its kind sets.""" - if report.household_id is not None: - return "household" - if report.budget_window_size is not None: - return "budget_window" - return "economy" - - def report_run_read(run: ReportRun) -> ReportRunRead: """Return the run's status, versions and times.""" return ReportRunRead( diff --git a/policyengine_api/services/v2/stored_reports/types.py b/policyengine_api/services/v2/stored_reports/types.py index e0cb5b402..7dceab16a 100644 --- a/policyengine_api/services/v2/stored_reports/types.py +++ b/policyengine_api/services/v2/stored_reports/types.py @@ -46,11 +46,8 @@ # A report's status is its run's (the run a read answers), or not_run while it # has none, as a report migrated from v1 has none. ReportStatusName = Literal["not_run", "pending", "running", "succeeded", "failed"] -# What a report compares: two economy simulations, two household simulations, -# or two economy simulations in each year of a budget window. -ReportKind = Literal["economy", "household", "budget_window"] -# The kinds whose runs are their report runs; a budget window's are its -# budget-window runs. +# The report types whose runs are their report runs; a budget window's are its +# budget-window runs. A report's type is ``reports.type`` (``ReportType``). ReportRunsKind = Literal["economy", "household"] # How far a side's cliff calculation has got: not_calculated while its # simulation run has none, else its calculation's status (failed once its diff --git a/policyengine_api/services/v2/stored_reports/validators.py b/policyengine_api/services/v2/stored_reports/validators.py index 1d17b118a..64af8330d 100644 --- a/policyengine_api/services/v2/stored_reports/validators.py +++ b/policyengine_api/services/v2/stored_reports/validators.py @@ -18,13 +18,11 @@ from uuid import UUID from policyengine_api.data.v2.models import BudgetWindowRun, Report, ReportRun + from policyengine_api.data.v2.models.reports import ReportType from policyengine_api.services.v2.report_run_records.types import ( CheckedRequester, ) - from policyengine_api.services.v2.stored_reports.types import ( - ReportKind, - StoredReportRows, - ) + from policyengine_api.services.v2.stored_reports.types import StoredReportRows # A report run, or a budget window's budget-window run. RunT = TypeVar("RunT") @@ -87,25 +85,26 @@ class CliffsNotAvailableError(ValueError): """ -def require_budget_window_year(report: Report, *, kind: ReportKind, year: int) -> None: +def require_budget_window_year(report: Report, *, year: int) -> None: """Allow a read of ``year`` of the report only for a year of its budget window. The window is ``report.budget_window_size`` years from its first year, - ``report.year``. Raise NotABudgetWindowError when the report, of - ``kind``, is an economy or household report, and - BudgetWindowYearNotFoundError when ``year`` is outside the window or the - window names no first year. + ``report.year``. Raise NotABudgetWindowError when the report's type is + economy or household, and BudgetWindowYearNotFoundError when ``year`` is + outside the window or the window names no first year. """ - if kind != "budget_window": - described = "an economy report" if kind == "economy" else "a household report" + if report.type != "budget_window": + described = ( + "an economy report" if report.type == "economy" else "a household report" + ) msg = ( f"Report {report.id} is {described}, not a budget window, so it has " f"no year {year}" ) raise NotABudgetWindowError(msg) first_year, window_size = report.year, report.budget_window_size - # A window's size is what makes it one (report_kind), so only its first - # year can be missing. + # The database requires a budget window's size (ck_reports_type), so only + # its first year can be missing. if first_year is None or window_size is None: msg = ( f"Report {report.id}'s budget window names no first year, so it has " @@ -140,10 +139,13 @@ def require_window_year_run( return year_run -def require_cliffs_available(kind: ReportKind, *, include_cliffs: bool) -> None: - """Raise CliffsNotAvailableError when a re-run of a ``kind`` asks for cliffs.""" - if include_cliffs and kind != "economy": - name = "a household report" if kind == "household" else "a budget window" +def require_cliffs_available(report_type: ReportType, *, include_cliffs: bool) -> None: + """Raise CliffsNotAvailableError when a re-run asks for cliffs it can't have. + + Only an economy report's simulation runs have cliff calculations. + """ + if include_cliffs and report_type != "economy": + name = "a household report" if report_type == "household" else "a budget window" msg = f"include_cliffs: {name} has no cliff impacts, so it cannot be true" raise CliffsNotAvailableError(msg) 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 4afb7f5d3..cbf2f2799 100644 --- a/policyengine_api/services/v2/user_reports/database_connectors/reads.py +++ b/policyengine_api/services/v2/user_reports/database_connectors/reads.py @@ -13,6 +13,7 @@ UserPolicy, UserReportAssociation, ) +from policyengine_api.services.v2.user_reports.types import NamedReport if TYPE_CHECKING: from uuid import UUID @@ -158,31 +159,21 @@ def read_owned_user_policy_exists( ) -def read_report_exists(session: Session, *, country_id: str, report_id: UUID) -> bool: - """Return whether a detailed-save report with this id is stored in the country.""" - return ( - session.exec( - select(Report.id).where( - Report.id == report_id, Report.country == country_id - ) - ).one_or_none() - is not None - ) - - -def read_report_budget_window_size( +def read_named_report( session: Session, *, country_id: str, report_id: UUID -) -> int | None: - """Return the country's report's budget window size, or None. - - None means the report has no budget window, or the country has no such - report. - """ - return session.exec( - select(Report.budget_window_size).where( +) -> NamedReport | None: + """Return the country's report's type and budget window, or None if it has none.""" + row = session.exec( + select(col(Report.type), col(Report.budget_window_size)).where( Report.id == report_id, Report.country == country_id ) ).one_or_none() + if row is None: + return None + report_type, budget_window_size = row + return NamedReport( + id=report_id, type=report_type, budget_window_size=budget_window_size + ) def read_run_of_report_exists( diff --git a/policyengine_api/services/v2/user_reports/services.py b/policyengine_api/services/v2/user_reports/services.py index b2a94032a..fb138b92c 100644 --- a/policyengine_api/services/v2/user_reports/services.py +++ b/policyengine_api/services/v2/user_reports/services.py @@ -60,11 +60,10 @@ from policyengine_api.services.v2.user_reports.database_connectors.reads import ( lock_owned_user_report_row, read_all_user_report_rows, + read_named_report, read_owned_user_policy_exists, read_owned_user_policy_row, 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, @@ -103,6 +102,7 @@ UserReportDatabaseSession, ) from policyengine_api.services.v2.user_reports.types import ( + NamedReport, SharedUserReportRead, UserReportCreateFields, UserReportPage, @@ -156,68 +156,86 @@ def validate_linked_user_policy( ) -def validate_stored_report( +def read_stored_report( session: Session, *, country_id: str, report_id: UUID | None -) -> None: - """Check, in the write's transaction, that a named report is stored in the country. +) -> NamedReport | None: + """Read, in the write's transaction, the detailed-save report a saved report names. - A None ``report_id`` passes; otherwise raise AssociationReportNotFoundError. + This is the write's one read of the report: its budget window and current + run are checked against what it returns. A None ``report_id`` returns + None; otherwise raise AssociationReportNotFoundError unless the country + stores the report. """ if report_id is None: - return - require_stored_report( - stored=read_report_exists(session, country_id=country_id, report_id=report_id), + return None + return require_stored_report( + read_named_report(session, country_id=country_id, report_id=report_id), report_id=report_id, country_id=country_id, ) -def validate_saved_budget_window( +def report_after_update( session: Session, *, - country_id: str, - report_id: UUID | None, - budget_window_years: int | None, + association: UserReportAssociation, + association_input: UserReportUpdateInput, +) -> NamedReport | None: + """Read the detailed-save report the update leaves named, if the update checks it. + + A supplied ``report_id`` is read, and must be stored in the country + (``read_stored_report``). The saved report's own report is read only + when the update supplies a field checked against it, + ``budget_window_years`` or ``current_run_id``. None means the update + leaves no report named, or checks nothing against it. + """ + supplied = association_input.model_fields_set + if "report_id" in supplied: + report_id = association_input.report_id + elif supplied.intersection({"budget_window_years", "current_run_id"}): + report_id = association.report_id + else: + return None + return read_stored_report( + session, country_id=association.country_id, report_id=report_id + ) + + +def validate_saved_budget_window( + report: NamedReport | None, *, budget_window_years: int | None ) -> None: - """Check, in the write's transaction, the saved window against the report's. + """Check the saved window against the named report's. - A None ``report_id`` passes: a v1 report output stores no window of its - own. Otherwise raise AssociationBudgetWindowConflictError unless + A None ``report`` passes: a v1 report output stores no window of its own. + Otherwise raise AssociationBudgetWindowConflictError unless ``budget_window_years`` agrees with the report's budget window. """ - if report_id is None: + if report is None: return require_matching_budget_window( - report_id=report_id, - budget_window_size=read_report_budget_window_size( - session, country_id=country_id, report_id=report_id - ), + report_id=report.id, + budget_window_size=report.budget_window_size, budget_window_years=budget_window_years, ) def validate_saved_budget_window_after_update( - session: Session, + report: NamedReport | None, *, association: UserReportAssociation, association_input: UserReportUpdateInput, ) -> None: """Check the window the update leaves against the report it leaves named. - Only an update that names a report or a window is checked, so a record - saved before the check can still be renamed. + ``report`` is that report (``report_after_update``). Only an update that + names a report or a window is checked, so a record saved before the check + can still be renamed. """ supplied = association_input.model_fields_set if not supplied.intersection({"report_id", "budget_window_years"}): return validate_saved_budget_window( - session, - country_id=association.country_id, - report_id=( - association_input.report_id - if "report_id" in supplied - else association.report_id - ), + report, budget_window_years=( association_input.budget_window_years if "budget_window_years" in supplied @@ -229,36 +247,34 @@ def validate_saved_budget_window_after_update( def validate_current_run( session: Session, *, - country_id: str, - report_id: UUID | None, + report: NamedReport | 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. + ``report`` is the detailed-save report the saved report names, already + read (``read_stored_report``). Return both current-run columns, the run + in the one for the report's type: 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 or one that isn't a run of that report. """ - 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_report_for_current_run( + report_id=None if report is None else report.id, + current_run_id=current_run_id, ) + if report is None or current_run_id is None: + return current_run_columns(None, budget_window=False) + budget_window = report.type == "budget_window" require_run_of_report( run_of_report=read_run_of_report_exists( session, - report_id=report_id, + report_id=report.id, run_id=current_run_id, budget_window=budget_window, ), run_id=current_run_id, - report_id=report_id, + report_id=report.id, budget_window=budget_window, ) return current_run_columns(current_run_id, budget_window=budget_window) @@ -269,24 +285,22 @@ def current_run_after_update( *, association: UserReportAssociation, association_input: UserReportUpdateInput, - report_id: UUID | None, + report: NamedReport | 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. + ``report`` is the report the update leaves named (``report_after_update``), + read whenever the update supplies ``report_id`` or ``current_run_id``. 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, + session, report=report, current_run_id=association_input.current_run_id ) - if "report_id" in supplied and report_id != association.report_id: + if "report_id" in supplied and association_input.report_id != association.report_id: return current_run_columns(None, budget_window=False) return {} @@ -392,14 +406,11 @@ def create_user_report( principal, country_id=country_id, ) - validate_stored_report( + report = read_stored_report( session, country_id=country_id, report_id=association_input.report_id ) validate_saved_budget_window( - session, - country_id=country_id, - report_id=association_input.report_id, - budget_window_years=association_input.budget_window_years, + report, budget_window_years=association_input.budget_window_years ) for linked_user_policy_id in ( association_input.user_policy_id, @@ -416,8 +427,7 @@ def create_user_report( ).model_copy( update=validate_current_run( session, - country_id=country_id, - report_id=association_input.report_id, + report=report, current_run_id=association_input.current_run_id, ) ) @@ -586,11 +596,11 @@ def patch_user_report( ) is not None, ) - validate_stored_report( - session, country_id=country_id, report_id=association_input.report_id + report = report_after_update( + session, association=association, association_input=association_input ) validate_saved_budget_window_after_update( - session, association=association, association_input=association_input + report, association=association, association_input=association_input ) for link_field in ("user_policy_id", "baseline_user_policy_id"): if link_field in association_input.model_fields_set: @@ -606,7 +616,7 @@ def patch_user_report( session, association=association, association_input=association_input, - report_id=report_id, + report=report, ) if ( report_id is not None diff --git a/policyengine_api/services/v2/user_reports/types.py b/policyengine_api/services/v2/user_reports/types.py index e2ce7bec9..45780d568 100644 --- a/policyengine_api/services/v2/user_reports/types.py +++ b/policyengine_api/services/v2/user_reports/types.py @@ -28,6 +28,8 @@ from datetime import datetime from uuid import UUID + from policyengine_api.data.v2.models.reports import ReportType + MAXIMUM_PROVISIONS_BYTES = 64 * 1024 REPORT_SOURCE_NOTE_MAX_LENGTH = 10_000 MAXIMUM_CALIBRATION_MATCHES = 500 @@ -344,6 +346,21 @@ class SharedUserReportRead: updated_at: datetime +@dataclass(frozen=True) +class NamedReport: + """The detailed-save report a saved report names, as a write checks it. + + ``type`` is the report's stored ``reports.type``: a budget window's runs + are budget-window runs, any other report's report runs. + ``budget_window_size`` is the report's window, which the saved report's + ``budget_window_years`` must agree with. + """ + + id: UUID + type: ReportType + budget_window_size: int | None + + @dataclass(frozen=True) class UserReportListing: """One page of a user's associations to read, optionally for one v1 report.""" diff --git a/policyengine_api/services/v2/user_reports/validators.py b/policyengine_api/services/v2/user_reports/validators.py index 16a7669a8..43be2650c 100644 --- a/policyengine_api/services/v2/user_reports/validators.py +++ b/policyengine_api/services/v2/user_reports/validators.py @@ -15,7 +15,10 @@ from uuid import UUID from policyengine_api.data.v2.models import UserReportAssociation - from policyengine_api.services.v2.user_reports.types import UserReportUpdateInput + from policyengine_api.services.v2.user_reports.types import ( + NamedReport, + UserReportUpdateInput, + ) class UserReportNotFoundError(AssociationNotFoundError): @@ -58,10 +61,13 @@ def report_not_found( ) -def require_stored_report(*, stored: bool, report_id: UUID, country_id: str) -> None: - """Raise AssociationReportNotFoundError unless the report is ``stored``.""" - if not stored: +def require_stored_report( + report: NamedReport | None, *, report_id: UUID, country_id: str +) -> NamedReport: + """Return the report, or raise AssociationReportNotFoundError if it is None.""" + if report is None: raise report_not_found(report_id=report_id, country_id=country_id) + return report def require_matching_budget_window( diff --git a/tests/integration/stored_report_rows.py b/tests/integration/stored_report_rows.py index 495d9cde2..8df62e065 100644 --- a/tests/integration/stored_report_rows.py +++ b/tests/integration/stored_report_rows.py @@ -350,7 +350,13 @@ def store_report( # noqa: PLR0913 # the session and catalog, then each column Report, id=report.report_id, country=catalog.country, - type="economy", + type=( + "household" + if household_id is not None + else "economy" + if budget_window_size is None + else "budget_window" + ), tax_benefit_model_id=catalog.model_id, policy_id=catalog.policy_id, baseline_simulation_id=report.baseline_simulation_id, diff --git a/tests/integration/test_alembic_v2_lifecycle.py b/tests/integration/test_alembic_v2_lifecycle.py index e18b21bc0..892d8a4b9 100644 --- a/tests/integration/test_alembic_v2_lifecycle.py +++ b/tests/integration/test_alembic_v2_lifecycle.py @@ -852,6 +852,7 @@ def report_run_checks() -> set[str | None]: add_row( session, Report, + type="economy", id=report_id, country="us", tax_benefit_model_id=public_api_rows.model_id, diff --git a/tests/integration/test_alembic_v2_saved_item_keys.py b/tests/integration/test_alembic_v2_saved_item_keys.py index 6cf14e7b0..d908236ce 100644 --- a/tests/integration/test_alembic_v2_saved_item_keys.py +++ b/tests/integration/test_alembic_v2_saved_item_keys.py @@ -130,6 +130,7 @@ def _insert_report(session: Session, rows: PublicApiRows) -> UUID: add_row( session, Report, + type="economy", id=report_id, country="us", tax_benefit_model_id=rows.model_id, diff --git a/tests/integration/test_alembic_v2_simulation_runs.py b/tests/integration/test_alembic_v2_simulation_runs.py index 73b9c1d4b..8c4b01d7b 100644 --- a/tests/integration/test_alembic_v2_simulation_runs.py +++ b/tests/integration/test_alembic_v2_simulation_runs.py @@ -339,6 +339,7 @@ def _insert_report_run( add_row( session, Report, + type="economy", id=report_id, country="us", tax_benefit_model_id=public_api_rows.model_id, @@ -663,10 +664,18 @@ def test_a_report_runs_labor_supply_and_spm_receipt_are_typed( def _insert_report( session: Session, public_api_rows: PublicApiRows, **values: object ) -> UUID: + """Store a report whose type is the one its household and window give.""" report_id = uuid4() + if values.get("household_id") is not None: + report_type = "household" + elif values.get("budget_window_size") is not None: + report_type = "budget_window" + else: + report_type = "economy" add_row( session, Report, + type=report_type, id=report_id, country="us", tax_benefit_model_id=public_api_rows.model_id, diff --git a/tests/integration/test_alembic_v2_withheld_area_codes.py b/tests/integration/test_alembic_v2_withheld_area_codes.py index 554d2f9c0..b6e1c39e6 100644 --- a/tests/integration/test_alembic_v2_withheld_area_codes.py +++ b/tests/integration/test_alembic_v2_withheld_area_codes.py @@ -208,6 +208,7 @@ def _insert_report_run(session: Session) -> dict[str, UUID]: add_row( session, Report, + type="economy", id=ids["report"], country="uk", tax_benefit_model_id=public_api_rows.model_id, diff --git a/tests/integration/test_v2_catalog_publication.py b/tests/integration/test_v2_catalog_publication.py index 4203ec36f..5f04c1a2c 100644 --- a/tests/integration/test_v2_catalog_publication.py +++ b/tests/integration/test_v2_catalog_publication.py @@ -506,6 +506,7 @@ def test_republish_preserves_existing_run_and_dataset_version_records( ) report = Report( country="us", + type="economy", tax_benefit_model_id=model.id, dataset_id=input_dataset.id, region_id=region.id, diff --git a/tests/integration/test_v2_household_reports.py b/tests/integration/test_v2_household_reports.py index c4f4a95f8..038729946 100644 --- a/tests/integration/test_v2_household_reports.py +++ b/tests/integration/test_v2_household_reports.py @@ -306,6 +306,7 @@ def store_household_report( add_row( session, Report, + type="household", id=report_id, country=catalog.country, tax_benefit_model_id=catalog.model_id, diff --git a/tests/integration/test_v2_saved_detailed_save_records.py b/tests/integration/test_v2_saved_detailed_save_records.py index ad1827bba..04a9aacf7 100644 --- a/tests/integration/test_v2_saved_detailed_save_records.py +++ b/tests/integration/test_v2_saved_detailed_save_records.py @@ -30,6 +30,7 @@ ) from policyengine_api.services.v2.user_reports.services import V2UserReportService from policyengine_api.services.v2.user_reports.types import ( + NamedReport, UserReportCreateFields, UserReportUpdateInput, ) @@ -260,6 +261,14 @@ def test_a_saved_report_is_repointed_only_to_a_stored_report( assert repointed.report_id == second.report_id +def _an_economy_report( + _session: Session, *, country_id: str, report_id: UUID +) -> NamedReport: + """Answer the saved-report write's read as if the report were stored.""" + del country_id + return NamedReport(id=report_id, type="economy", budget_window_size=None) + + def test_a_report_gone_after_the_check_is_refused_by_its_foreign_key( monkeypatch: pytest.MonkeyPatch, catalogs: dict[str, CatalogRows], @@ -267,9 +276,7 @@ def test_a_report_gone_after_the_check_is_refused_by_its_foreign_key( runtime_sessions: sessionmaker, ) -> None: # As if the report were deleted between the check and the insert. - monkeypatch.setattr( - report_services, "read_report_exists", lambda *_args, **_kwargs: True - ) + monkeypatch.setattr(report_services, "read_named_report", _an_economy_report) missing_report_id = uuid4() with pytest.raises(AssociationReportNotFoundError, match=str(missing_report_id)): @@ -299,9 +306,7 @@ def test_a_report_gone_before_a_repoint_is_refused_by_its_foreign_key( ), ) # As if the new report were deleted between the check and the update. - monkeypatch.setattr( - report_services, "read_report_exists", lambda *_args, **_kwargs: True - ) + monkeypatch.setattr(report_services, "read_named_report", _an_economy_report) missing_report_id = uuid4() with pytest.raises( diff --git a/tests/integration/test_v2_shared_report_rows.py b/tests/integration/test_v2_shared_report_rows.py index 278483ccb..e66f26e61 100644 --- a/tests/integration/test_v2_shared_report_rows.py +++ b/tests/integration/test_v2_shared_report_rows.py @@ -111,6 +111,7 @@ def _find_or_create_report(public_api_rows: PublicApiRows, key: str) -> Executab .values( id=uuid4(), country="us", + type="economy", tax_benefit_model_id=public_api_rows.model_id, year=2026, inputs={}, @@ -323,6 +324,7 @@ def _report(session: Session, public_api_rows: PublicApiRows) -> UUID: add_row( session, Report, + type="economy", id=report_id, country="us", tax_benefit_model_id=public_api_rows.model_id, @@ -697,6 +699,7 @@ def test_the_simulation_service_writes_shared_rows_without_per_user_columns( add_row( session, Report, + type="economy", id=report_id, country="us", tax_benefit_model_id=public_api_rows.model_id, diff --git a/tests/integration/test_v2_simulation_role_privileges.py b/tests/integration/test_v2_simulation_role_privileges.py index 5b7df5d61..26c5f7b63 100644 --- a/tests/integration/test_v2_simulation_role_privileges.py +++ b/tests/integration/test_v2_simulation_role_privileges.py @@ -182,6 +182,7 @@ def _create_simulation_rows( add_row( session, Report, + type="budget_window", id=ids["report"], country="us", tax_benefit_model_id=public_api_rows.model_id, diff --git a/tests/integration/test_v2_user_identity_persistence.py b/tests/integration/test_v2_user_identity_persistence.py index d94646cea..e7f57c9f2 100644 --- a/tests/integration/test_v2_user_identity_persistence.py +++ b/tests/integration/test_v2_user_identity_persistence.py @@ -783,6 +783,7 @@ def delete_user(self, subject: str) -> None: add_row( session, Report, + type="economy", id=report_id, country="us", tax_benefit_model_id=public_api_rows.model_id, diff --git a/tests/unit/v2/published_report_support.py b/tests/unit/v2/published_report_support.py index 10f4dd473..4d68f013b 100644 --- a/tests/unit/v2/published_report_support.py +++ b/tests/unit/v2/published_report_support.py @@ -96,6 +96,7 @@ def store_report(session: Session, *, budget_window_size: int | None = None) -> """Store a US economy report, or a budget window, and return its ID.""" report = Report( country="us", + type="economy" if budget_window_size is None else "budget_window", tax_benefit_model_id=uuid4(), year=2026, budget_window_size=budget_window_size, diff --git a/tests/unit/v2/sqlite_report_rows.py b/tests/unit/v2/sqlite_report_rows.py index 32de7ef13..6abf0ec16 100644 --- a/tests/unit/v2/sqlite_report_rows.py +++ b/tests/unit/v2/sqlite_report_rows.py @@ -103,6 +103,7 @@ def store_economy_report( stored = Report( id=uuid4() if report.report_id is None else report.report_id, country=place.country, + type="economy" if report.budget_window_size is None else "budget_window", tax_benefit_model_id=place.model_id, baseline_simulation_id=simulations[0].id, reform_simulation_id=simulations[1].id, diff --git a/tests/unit/v2/test_alembic_v2_report_revisions.py b/tests/unit/v2/test_alembic_v2_report_revisions.py index 155ba6ca1..90ddbe24d 100644 --- a/tests/unit/v2/test_alembic_v2_report_revisions.py +++ b/tests/unit/v2/test_alembic_v2_report_revisions.py @@ -292,7 +292,7 @@ def test_report_types_revision_is_generated_with_one_approved_data_step() -> Non "op.f", ] assert re.search( - r"""op\.alter_column\(\s*["']reports["'],\s*["']type["'][^)]*nullable=False""", + r"""op\.alter_column\(\s*["']reports["'],\s*["']type["'],\s*existing_type=sa\.VARCHAR\(length=128\),\s*nullable=False\)""", upgrade, ) assert re.search( @@ -308,7 +308,7 @@ def test_report_types_revision_is_generated_with_one_approved_data_step() -> Non "op.f", ] assert re.search( - r"""op\.alter_column\(\s*["']reports["'],\s*["']type["'][^)]*nullable=True""", + r"""op\.alter_column\(\s*["']reports["'],\s*["']type["'],\s*existing_type=sa\.VARCHAR\(length=128\),\s*nullable=True\)""", downgrade, ) assert "op.bulk_insert(" not in revision diff --git a/tests/unit/v2/test_budget_window_year_checks.py b/tests/unit/v2/test_budget_window_year_checks.py index 3c2c554d6..a1f34749d 100644 --- a/tests/unit/v2/test_budget_window_year_checks.py +++ b/tests/unit/v2/test_budget_window_year_checks.py @@ -6,6 +6,7 @@ from __future__ import annotations +from typing import TYPE_CHECKING from uuid import uuid4 import pytest @@ -21,11 +22,15 @@ require_window_year_run, ) +if TYPE_CHECKING: + from policyengine_api.data.v2.models.reports import ReportType + def stored_report(*, year: int | None, budget_window_size: int | None) -> Report: return Report( id=uuid4(), country="us", + type="economy" if budget_window_size is None else "budget_window", tax_benefit_model_id=uuid4(), year=year, budget_window_size=budget_window_size, @@ -36,7 +41,7 @@ def stored_report(*, year: int | None, budget_window_size: int | None) -> Report def test_each_year_of_the_window_may_be_read(year: int) -> None: window = stored_report(year=2026, budget_window_size=3) - assert require_budget_window_year(window, kind="budget_window", year=year) is None + assert require_budget_window_year(window, year=year) is None @pytest.mark.parametrize("year", [2025, 2029]) @@ -44,7 +49,7 @@ def test_a_year_outside_the_window_is_not_found(year: int) -> None: window = stored_report(year=2026, budget_window_size=3) with pytest.raises(BudgetWindowYearNotFoundError) as raised: - require_budget_window_year(window, kind="budget_window", year=year) + require_budget_window_year(window, year=year) assert str(raised.value) == ( f"Report {window.id}'s budget window covers 2026 to 2028, not {year}" @@ -55,7 +60,7 @@ def test_a_window_with_no_first_year_has_no_year() -> None: window = stored_report(year=None, budget_window_size=3) with pytest.raises(BudgetWindowYearNotFoundError) as raised: - require_budget_window_year(window, kind="budget_window", year=2026) + require_budget_window_year(window, year=2026) assert str(raised.value) == ( f"Report {window.id}'s budget window names no first year, so it has no " @@ -64,14 +69,17 @@ def test_a_window_with_no_first_year_has_no_year() -> None: @pytest.mark.parametrize( - ("kind", "described"), + ("report_type", "described"), [("economy", "an economy report"), ("household", "a household report")], ) -def test_a_report_that_is_not_a_window_has_no_year(kind: str, described: str) -> None: +def test_a_report_that_is_not_a_window_has_no_year( + report_type: ReportType, described: str +) -> None: report = stored_report(year=2026, budget_window_size=None) + report.type = report_type with pytest.raises(NotABudgetWindowError) as raised: - require_budget_window_year(report, kind=kind, year=2026) + require_budget_window_year(report, year=2026) assert str(raised.value) == ( f"Report {report.id} is {described}, not a budget window, so it has no " diff --git a/tests/unit/v2/test_household_report_reads.py b/tests/unit/v2/test_household_report_reads.py index 2ff124c87..556c70825 100644 --- a/tests/unit/v2/test_household_report_reads.py +++ b/tests/unit/v2/test_household_report_reads.py @@ -212,6 +212,7 @@ def simulation(policy_id: UUID | None) -> Simulation: session.flush() report = Report( country=country, + type="household", tax_benefit_model_id=model.id, baseline_simulation_id=baseline.id, reform_simulation_id=None if reform is None else reform.id, @@ -519,6 +520,7 @@ def store_economy_report(session: Session) -> UUID: session.flush() report = Report( country="us", + type="economy", tax_benefit_model_id=model.id, year=2026, inputs={"include_cliffs": False}, diff --git a/tests/unit/v2/test_report_dataset_independent_keys.py b/tests/unit/v2/test_report_dataset_independent_keys.py index 5f49158b7..45c065537 100644 --- a/tests/unit/v2/test_report_dataset_independent_keys.py +++ b/tests/unit/v2/test_report_dataset_independent_keys.py @@ -122,6 +122,7 @@ def store_household_report( session.flush() report = Report( country=catalog.country, + type="household", tax_benefit_model_id=catalog.model_id, baseline_simulation_id=simulations[0].id, reform_simulation_id=simulations[1].id, diff --git a/tests/unit/v2/test_report_rerun_service.py b/tests/unit/v2/test_report_rerun_service.py index 34a58fd5d..11ba704ff 100644 --- a/tests/unit/v2/test_report_rerun_service.py +++ b/tests/unit/v2/test_report_rerun_service.py @@ -71,12 +71,18 @@ def rerun_report(self, rerun: ReportRerunInput) -> StartedReportRun: def stored_rows(**report_columns: object) -> StoredReportRows: + report_type = ( + "economy" + if report_columns.get("budget_window_size") is None + else "budget_window" + ) report = Report( id=REPORT_ID, country="us", tax_benefit_model_id=uuid4(), year=2026, inputs={}, + type=report_type, **report_columns, ) return StoredReportRows( diff --git a/tests/unit/v2/test_report_run_creation.py b/tests/unit/v2/test_report_run_creation.py index 36d450d36..576094d91 100644 --- a/tests/unit/v2/test_report_run_creation.py +++ b/tests/unit/v2/test_report_run_creation.py @@ -49,6 +49,7 @@ def _create_report(session: Session) -> Report: session.flush() report = Report( country="us", + type="economy", tax_benefit_model_id=model.id, inputs={}, ) diff --git a/tests/unit/v2/test_report_runs.py b/tests/unit/v2/test_report_runs.py index e2ffeae55..ae84aa882 100644 --- a/tests/unit/v2/test_report_runs.py +++ b/tests/unit/v2/test_report_runs.py @@ -29,13 +29,11 @@ ReportRunPackageVersions, ReportRunSimulationRuns, ReportRunStateError, - ReportTypeImmutableError, begin_report_run, complete_report_run, create_report_run, fail_report_run, select_current_report_run, - set_report_type, ) from tests.fixtures.database_sessions import ( sqlite_v2_file_sessions, @@ -59,13 +57,13 @@ def sessions() -> Iterator[sessionmaker[Session]]: yield session_factory -def _create_report(session: Session, *, report_type: str | None = None) -> Report: +def _create_report(session: Session) -> Report: model = TaxBenefitModel(name=f"model-{uuid4()}") session.add(model) session.flush() report = Report( country="us", - type=report_type, + type="economy", tax_benefit_model_id=model.id, inputs={"reform": {"gov.example": 1}}, ) @@ -116,43 +114,17 @@ def _create_forced_run(session: Session, report: Report) -> ReportRun: return run -def test_untyped_and_typed_report_definitions_store_no_execution_versions( +def test_report_definitions_store_their_type_and_no_execution_versions( sessions, ) -> None: with sessions(expire_on_commit=True) as session: - untyped = _create_report(session) - typed = _create_report(session, report_type="marginal_tax_rate") + report = _create_report(session) - assert untyped.type is None - assert typed.type == "marginal_tax_rate" + assert report.type == "economy" assert "country_package_version" not in model_columns(Report) assert "policyengine_version" not in model_columns(Report) -def test_report_type_can_change_before_first_run_but_not_after(sessions) -> None: - with sessions(expire_on_commit=True) as session: - report = _create_report(session) - set_report_type( - session, - report_id=report.id, - report_type="marginal_tax_rate", - ) - _create_run(session, report) - - unchanged = set_report_type( - session, - report_id=report.id, - report_type="marginal_tax_rate", - ) - assert unchanged.id == report.id - with pytest.raises(ReportTypeImmutableError): - set_report_type( - session, - report_id=report.id, - report_type="economy_comparison", - ) - - def test_new_keys_create_a_same_version_run_once_the_last_one_failed( sessions, ) -> None: From 8a9df7b1b4bb6b4b8b2e92745e45cc2891bae8af Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:29:36 +0400 Subject: [PATCH 5/7] Test that the Alembic v2 check runs the report revision tests Review round 1 found that the Alembic v2 check's script runs neither the report types revision's integration tests nor the report revision unit tests, so a regression in the data step or ck_reports_type could merge unnoticed. The workflow test now asserts the script lists both. Co-Authored-By: Claude Opus 5.5 --- tests/unit/test_alembic_workflows.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/unit/test_alembic_workflows.py b/tests/unit/test_alembic_workflows.py index 7f2cab69d..08fe48c0a 100644 --- a/tests/unit/test_alembic_workflows.py +++ b/tests/unit/test_alembic_workflows.py @@ -226,6 +226,8 @@ def test_reusable_v2_alembic_check_uses_only_disposable_postgres(): assert "test_alembic_v2_inline_household_jobs.py" in lifecycle_script assert "test_alembic_v2_published_report_images.py" in lifecycle_script assert "test_alembic_v2_saved_report_current_runs.py" in lifecycle_script + assert "test_alembic_v2_report_revisions.py" in lifecycle_script + assert "test_alembic_v2_report_types.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 From 682c2b0400a69a08eb0fc76ab25e750be3bdc6e8 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:31:48 +0400 Subject: [PATCH 6/7] Expect the report types revision as head and run its tests in the Alembic v2 check MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review round 1 found two unit tests still expecting the old schema: the revision chain test named 7dcd2cd14330 as head, and the model test expected reports.type to be nullable. They now expect 24b571d7d079 and a required type. The Alembic v2 check's script now runs the report types revision's integration tests and the report revision unit tests. The Alembic guide gains a section for the revision (its data step, the order D1 · 7a and D1 · 9 deploy in), and names the module that now checks the earlier report revision files; the testing guide lists that module; the user-login document says when a saved report's write reads its report. The two test docstrings name the user's migration decision, as the revision does. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/test_alembic_v2_lifecycle.sh | 4 +- docs/engineering/skills/alembic-migrations.md | 64 +++++++++++++++++-- docs/engineering/skills/testing.md | 4 +- docs/migration/stage-12a-user-login.md | 7 +- .../test_alembic_v2_report_types.py | 6 +- .../v2/test_alembic_v2_report_revisions.py | 4 +- tests/unit/v2/test_alembic_v2_revisions.py | 3 +- tests/unit/v2/test_models.py | 2 +- 8 files changed, 79 insertions(+), 15 deletions(-) diff --git a/.github/scripts/test_alembic_v2_lifecycle.sh b/.github/scripts/test_alembic_v2_lifecycle.sh index dc67fed63..1085ad988 100755 --- a/.github/scripts/test_alembic_v2_lifecycle.sh +++ b/.github/scripts/test_alembic_v2_lifecycle.sh @@ -7,6 +7,7 @@ uv run --frozen --extra dev pytest -q \ tests/unit/v2/test_alembic_v2_revisions.py \ tests/unit/v2/test_alembic_v2_dynamic_revisions.py \ tests/unit/v2/test_alembic_v2_household_job_revisions.py \ + tests/unit/v2/test_alembic_v2_report_revisions.py \ tests/integration/test_alembic_v2_lifecycle.py \ tests/integration/test_alembic_v2_catalog_tables.py \ tests/integration/test_alembic_v2_simulation_runs.py \ @@ -23,4 +24,5 @@ uv run --frozen --extra dev pytest -q \ tests/integration/test_alembic_v2_published_reports.py \ tests/integration/test_alembic_v2_inline_household_jobs.py \ tests/integration/test_alembic_v2_published_report_images.py \ - tests/integration/test_alembic_v2_saved_report_current_runs.py + tests/integration/test_alembic_v2_saved_report_current_runs.py \ + tests/integration/test_alembic_v2_report_types.py diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 90d30dd7b..634086698 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -1832,8 +1832,8 @@ Alembic generated `uq_user_report_associations_id_report_id` after refuses a foreign key to columns without a unique constraint. The upgrade creates the constraint first, and the downgrade drops it after the tables. The operations are otherwise as generated. The downgrade drops both tables -with their rows. `tests/unit/v2/test_alembic_v2_revisions.py` checks the -revision file and its one correction, and +with their rows. `tests/unit/v2/test_alembic_v2_report_revisions.py` checks +the revision file and its one correction, and `tests/integration/test_alembic_v2_published_reports.py`, which the Alembic v2 check runs, downgrades to the parent and upgrades again. `tests/integration/test_v2_published_reports.py`, which the cross-database @@ -1937,7 +1937,7 @@ research page's listing shows: - `created_at` and `updated_at`. The operations are exactly as generated. The downgrade drops the table with -its rows. `tests/unit/v2/test_alembic_v2_revisions.py` checks the +its rows. `tests/unit/v2/test_alembic_v2_report_revisions.py` checks the revision file, and `tests/integration/test_alembic_v2_published_report_images.py`, which the Alembic v2 check runs, downgrades to the parent and upgrades again. `tests/integration/test_v2_published_reports.py`, which the cross-database @@ -1990,10 +1990,64 @@ Deploying it: 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 +`tests/unit/v2/test_alembic_v2_report_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. + +### API v2 report types + +Revision `24b571d7d079` (parent `7dcd2cd14330`, ID chosen with `--rev-id`) +was autogenerated after `Report.type` +(`policyengine_api/data/v2/models/reports.py`) became required. Every report +names its type (D1 · 8): `economy`, `household` or `budget_window`, and API v1 +reads `reports.type` to tell them apart. The generated part: + +- makes `reports.type` NOT NULL; +- adds `ck_reports_type`: the type is one of the three, it is `household` + exactly when `household_id` is set, and `budget_window` exactly when + `budget_window_size` is set. `ck_reports_budget_window_size` already + refuses a report with both. + +It has one hand-written data step, before the generated operations: **the +user's explicit migration decision (D1 · 8, 2026-12-03)**, which "Mandatory +generation rule" and "V2 application-data migrations" require. Until D1 · 7a +the simulation service stored a budget window's type as `economy`, and some +reports have no type, so the step sets every report whose type differs from +the one its columns give: `household` with a `household_id`, `budget_window` +with a `budget_window_size`, `economy` otherwise. Any other stored type is +replaced. The operations are otherwise exactly as generated. The downgrade +drops the check and makes the column nullable again; the types the step set +stay, since the earlier schema allows them. + +The step's `UPDATE` and the generated `SET NOT NULL` and `ADD CONSTRAINT` each +read the whole of `reports`, which stays locked until the migration +transaction commits, so the simulation service's writes and API v1's reads of +the table wait for them. + +Deploying it: + +- **The simulation service must write `budget_window` first.** + PolicyEngine/policyengine-sim-api writes every `reports` row. D1 · 7a makes + it store a budget window's type as `budget_window`; that change must be + deployed in an environment before this revision runs there, or the check + refuses the service's next budget window. +- **The simulation service's models.** Its `Report` in + `policyengine-simulation-persistence` keeps `type` nullable and has no + `ck_reports_type` until D1 · 9, which also moves its pinned commit of this + repository. Until then its weekly comparison with the tables this + repository's `master` builds (`public-api-schema-drift.yml`) reports both. +- **Releases from before the revision** work out a report's type from + `household_id` and `budget_window_size`, which the check keeps in agreement + with `type`, so one still serving during a deploy's traffic shift, or + restored by a rollback, answers the same. + +`tests/unit/v2/test_alembic_v2_report_revisions.py` checks the revision file +and its one data step. `tests/integration/test_alembic_v2_report_types.py`, +which the Alembic v2 check runs, stores reports at the parent as the +simulation service stored them, checks the types the upgrade sets, compares +the revision and its downgrade with the parent schema, and checks each +refusal as the database's owner. diff --git a/docs/engineering/skills/testing.md b/docs/engineering/skills/testing.md index dbfda8006..0b7a726b8 100644 --- a/docs/engineering/skills/testing.md +++ b/docs/engineering/skills/testing.md @@ -304,7 +304,8 @@ The generated-only v2 Alembic chain and disposable Postgres lifecycle: ```bash uv run pytest tests/unit/v2/test_alembic_v2.py tests/unit/v2/test_alembic_v2_revisions.py \ tests/unit/v2/test_alembic_v2_dynamic_revisions.py \ - tests/unit/v2/test_alembic_v2_household_job_revisions.py tests/unit/test_alembic_workflows.py -q + tests/unit/v2/test_alembic_v2_household_job_revisions.py \ + tests/unit/v2/test_alembic_v2_report_revisions.py tests/unit/test_alembic_workflows.py -q V2_ALEMBIC_DISPOSABLE_TEST=1 V2_MIGRATION_DATABASE_URL="postgresql+psycopg://.../policyengine_v2_alembic_test" \ uv run pytest tests/integration/test_alembic_v2_lifecycle.py tests/integration/test_alembic_v2_catalog_tables.py -q ``` @@ -645,6 +646,7 @@ uv run --frozen pytest \ tests/unit/v2/test_alembic_v2_revisions.py \ tests/unit/v2/test_alembic_v2_dynamic_revisions.py \ tests/unit/v2/test_alembic_v2_household_job_revisions.py \ + tests/unit/v2/test_alembic_v2_report_revisions.py \ tests/unit/test_readiness.py \ tests/unit/test_cloud_run_deploy_scripts.py \ tests/unit/test_migration_contract_artifacts.py \ diff --git a/docs/migration/stage-12a-user-login.md b/docs/migration/stage-12a-user-login.md index 7d9f6e3be..0335d085d 100644 --- a/docs/migration/stage-12a-user-login.md +++ b/docs/migration/stage-12a-user-login.md @@ -727,7 +727,12 @@ detailed-save `simulation_id` or `report_id` beside the v1 `budget_window_years`, or null for a report without a window of two or more years (a saved report stores a one-year window as null). Anything else is 400, on create and on any update naming `report_id` or - `budget_window_years`; it is read in the write's transaction. A saved v1 + `budget_window_years`. The write reads the report it names once, in its + transaction, and checks the window and any `current_run_id` against that + read: on create when it names one, and on an update that supplies + `report_id`, `budget_window_years` or `current_run_id`. An update that + supplies one of the last two without `report_id` reads the report the saved + report already names, and answers 404 if the country has none. A saved v1 report keeps the `budget_window_years` it is given. `MeItem` is `{id, user_type, primary_country, first_name, last_name, email, diff --git a/tests/integration/test_alembic_v2_report_types.py b/tests/integration/test_alembic_v2_report_types.py index 2762e04bf..a1ab2823e 100644 --- a/tests/integration/test_alembic_v2_report_types.py +++ b/tests/integration/test_alembic_v2_report_types.py @@ -6,9 +6,9 @@ report, and it has a budget window exactly when it is a budget window. Before it, the simulation service stored a budget window as ``economy`` and some reports had no type, so the revision first sets each report's type from its -``household_id`` and ``budget_window_size``, the one data step Anthony -approved for it (D1 · 8). The downgrade removes the check and makes the -column optional again; the types it set stay. +``household_id`` and ``budget_window_size``: its one data step, the user's +explicit migration decision (D1 · 8). The downgrade removes the check and +makes the column optional again; the types it set stay. """ from __future__ import annotations diff --git a/tests/unit/v2/test_alembic_v2_report_revisions.py b/tests/unit/v2/test_alembic_v2_report_revisions.py index 90ddbe24d..f567981c3 100644 --- a/tests/unit/v2/test_alembic_v2_report_revisions.py +++ b/tests/unit/v2/test_alembic_v2_report_revisions.py @@ -259,8 +259,8 @@ def test_report_types_revision_is_generated_with_one_approved_data_step() -> Non It is generated, with its ID chosen through ``--rev-id``, after ``Report.type`` became required and ``ck_reports_type`` was added. Its one - hand-written step, which Anthony approved for it (D1 · 8), runs first and - sets each report's type from its ``household_id`` and + hand-written step, the user's explicit migration decision (D1 · 8), runs + first and sets each report's type from its ``household_id`` and ``budget_window_size``, since the simulation service stored a budget window as ``economy`` and some reports have none. The generated downgrade drops the check and makes the column optional again. diff --git a/tests/unit/v2/test_alembic_v2_revisions.py b/tests/unit/v2/test_alembic_v2_revisions.py index e399cb9f3..12c32ad32 100644 --- a/tests/unit/v2/test_alembic_v2_revisions.py +++ b/tests/unit/v2/test_alembic_v2_revisions.py @@ -113,8 +113,9 @@ def test_v2_revision_chain_has_generated_policy_and_user_identity_changes() -> N config = Config(str(REPO / "alembic-v2.ini")) script = ScriptDirectory.from_config(config) assert script.get_heads() == [V2_ALEMBIC_HEAD_REVISION] - assert V2_ALEMBIC_HEAD_REVISION == SAVED_REPORT_CURRENT_RUNS_REVISION + assert V2_ALEMBIC_HEAD_REVISION == REPORT_TYPES_REVISION assert [revision.revision for revision in script.walk_revisions()] == [ + REPORT_TYPES_REVISION, SAVED_REPORT_CURRENT_RUNS_REVISION, PUBLISHED_REPORT_IMAGES_REVISION, INLINE_HOUSEHOLD_JOBS_REVISION, diff --git a/tests/unit/v2/test_models.py b/tests/unit/v2/test_models.py index f8cec40b7..b5577c539 100644 --- a/tests/unit/v2/test_models.py +++ b/tests/unit/v2/test_models.py @@ -301,7 +301,7 @@ def test_report_definition_and_run_columns_are_separated() -> None: report = model_columns("reports") report_run = model_columns("report_runs") - assert report.type.nullable + assert not report.type.nullable assert { "country", "type", From 675e20f477df4f05c434658df322aa5c681dbc8f Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:10:26 +0400 Subject: [PATCH 7/7] Give the malformed-key test's reports a type The cross-database integration check failed three cases of test_a_malformed_or_incomplete_key_is_refused: their reports had no type, so the database refused them for the required type before the key checks the test expects. The reports are now economy reports. Co-Authored-By: Claude Opus 5.5 --- tests/integration/test_v2_shared_report_rows.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/integration/test_v2_shared_report_rows.py b/tests/integration/test_v2_shared_report_rows.py index e66f26e61..9b59deab5 100644 --- a/tests/integration/test_v2_shared_report_rows.py +++ b/tests/integration/test_v2_shared_report_rows.py @@ -535,6 +535,7 @@ def test_a_malformed_or_incomplete_key_is_refused( if table == "simulations" else { "country": "us", + "type": "economy", "tax_benefit_model_id": public_api_rows.model_id, "inputs": {}, }