From 8ea891b6a6df7f86b3f59480f0b6cc340049f17f Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:58:21 +0400 Subject: [PATCH 1/7] Test that report rows stop being mapped with per-user columns (failing) Whole-row reads of reports, report runs and budget-window runs name none of the per-user columns a later revision drops, the tables keep them, run reads no longer answer a trigger, and create_report_run takes none. The report fixtures stop storing those columns, so the reads are tested on rows that hold none. Co-Authored-By: Claude Opus 5.5 --- tests/integration/stored_report_rows.py | 13 ++-- .../test_v2_budget_window_report_creation.py | 2 +- .../test_v2_budget_window_report_reads.py | 7 +- .../integration/test_v2_household_reports.py | 2 - tests/integration/test_v2_report_creation.py | 2 +- tests/integration/test_v2_report_runs.py | 54 ++++++--------- tests/unit/v2/budget_window_report_support.py | 2 - tests/unit/v2/report_run_support.py | 3 - tests/unit/v2/sqlite_report_rows.py | 1 - tests/unit/v2/stored_report_support.py | 1 - .../test_budget_window_report_read_routes.py | 23 ++----- tests/unit/v2/test_household_report_reads.py | 5 -- tests/unit/v2/test_report_column_mapping.py | 67 +++++++++++++++++++ .../test_report_dataset_independent_keys.py | 1 - tests/unit/v2/test_report_read_routes.py | 8 +-- tests/unit/v2/test_report_rerun_service.py | 5 +- tests/unit/v2/test_report_run_creation.py | 28 -------- tests/unit/v2/test_report_run_routes.py | 9 +-- tests/unit/v2/test_report_runs.py | 24 ------- tests/unit/v2/test_shared_report_models.py | 13 ++-- 20 files changed, 115 insertions(+), 155 deletions(-) create mode 100644 tests/unit/v2/test_report_column_mapping.py diff --git a/tests/integration/stored_report_rows.py b/tests/integration/stored_report_rows.py index 59756f1c2..e952d612a 100644 --- a/tests/integration/stored_report_rows.py +++ b/tests/integration/stored_report_rows.py @@ -299,12 +299,12 @@ def store_report( # noqa: PLR0913 # the connection and catalog, then each colu ) connection.execute( text( - "INSERT INTO reports (id, label, description, country, type, " + "INSERT INTO reports (id, country, type, " "tax_benefit_model_id, policy_id, baseline_simulation_id, " "reform_simulation_id, household_id, dataset_id, region_id, year, " "budget_window_size, inputs, key_version, definition_key, " - "dataset_independent_key, created_at) VALUES (:id, :label, " - ":description, :country, :type, :model_id, :policy_id, :baseline, " + "dataset_independent_key, created_at) VALUES (:id, " + ":country, :type, :model_id, :policy_id, :baseline, " ":reform, :household_id, :dataset_id, :region_id, :year, " ":budget_window_size, CAST(:inputs AS JSON), :key_version, " ":definition_key, :dataset_independent_key, " @@ -312,8 +312,6 @@ def store_report( # noqa: PLR0913 # the connection and catalog, then each colu ), { "id": report.report_id, - "label": f"{catalog.country} reform", - "description": "A stored report", "country": catalog.country, "type": "economy", "model_id": catalog.model_id, @@ -387,13 +385,13 @@ def store_report_run( "INSERT INTO report_runs (id, created_at, report_id, " "baseline_simulation_run_id, reform_simulation_run_id, " "budget_window_run_id, year, " - "country_package_version, policyengine_version, status, trigger, " + "country_package_version, policyengine_version, status, " "started_at, completed_at, error_message, spm_provenance, forced" + "".join(f", {column}" for column in result_columns) + ") VALUES (:id, :created_at, :report_id, :baseline_run, " ":reform_run, :budget_window_run_id, :year, " ":country_package_version, :policyengine_version, " - ":status, 'initial', :started_at, :completed_at, :error_message, " + ":status, :started_at, :completed_at, :error_message, " ":spm_provenance, :forced" + "".join(f", :{column}" for column in result_columns) + ")" @@ -485,7 +483,6 @@ def store_budget_window_run( created_at=created_at, report_id=report.report_id, tax_benefit_model_version_id=catalog.version_id, - trigger="initial", recalculate=False, status=settings.status, error_message=settings.error_message, diff --git a/tests/integration/test_v2_budget_window_report_creation.py b/tests/integration/test_v2_budget_window_report_creation.py index f1913b40f..28898c933 100644 --- a/tests/integration/test_v2_budget_window_report_creation.py +++ b/tests/integration/test_v2_budget_window_report_creation.py @@ -208,7 +208,7 @@ def test_a_created_budget_window_is_answered_as_the_tables_hold_it( assert (item["id"], item["kind"]) == (str(catalog.report_ids[0]), "budget_window") assert (item["year"], item["budget_window_size"]) == (2026, 3) assert item["status"] == "pending" - assert item["run"]["trigger"] == "initial" + assert "trigger" not in item["run"] assert item["run"]["policyengine_version"] == "4.2.0" assert [(year["year"], year["status"]) for year in item["run"]["years"]] == [ (2026, "pending"), diff --git a/tests/integration/test_v2_budget_window_report_reads.py b/tests/integration/test_v2_budget_window_report_reads.py index 71548db1e..5cf0b2d87 100644 --- a/tests/integration/test_v2_budget_window_report_reads.py +++ b/tests/integration/test_v2_budget_window_report_reads.py @@ -220,11 +220,8 @@ def test_a_budget_window_reads_its_newest_run_years_and_result( assert item["status"] == "succeeded" run = item["run"] assert run["id"] == str(window_run_id) - assert (run["status"], run["trigger"], run["recalculate"]) == ( - "succeeded", - "initial", - False, - ) + assert (run["status"], run["recalculate"]) == ("succeeded", False) + assert "trigger" not in run assert (run["country_package_version"], run["policyengine_version"]) == ( "1.4.0", "4.1.0", diff --git a/tests/integration/test_v2_household_reports.py b/tests/integration/test_v2_household_reports.py index 4d72c15c6..356720dd6 100644 --- a/tests/integration/test_v2_household_reports.py +++ b/tests/integration/test_v2_household_reports.py @@ -255,7 +255,6 @@ def store_household_report( connection, "reports", id=report_id, - label="My household under the reform", country=catalog.country, tax_benefit_model_id=catalog.model_id, policy_id=catalog.policy_id if with_reform else None, @@ -275,7 +274,6 @@ def store_household_report( baseline_simulation_run_id=baseline_run_id, reform_simulation_run_id=reform_run_id, status=status, - trigger="initial", started_at=STARTED_AT, completed_at=( STARTED_AT + timedelta(minutes=1) diff --git a/tests/integration/test_v2_report_creation.py b/tests/integration/test_v2_report_creation.py index 5dd5466d6..8da6b9d79 100644 --- a/tests/integration/test_v2_report_creation.py +++ b/tests/integration/test_v2_report_creation.py @@ -246,7 +246,7 @@ def test_a_created_report_is_answered_as_the_tables_hold_it( item = response.json()["result"]["item"] assert item["id"] == str(catalog.report_ids[0]) assert item["status"] == "pending" - assert item["run"]["trigger"] == "initial" + assert "trigger" not in item["run"] assert item["run"]["policyengine_version"] == "4.2.0" assert item["result"] is None assert item["current_versions"] == CURRENT_VERSIONS diff --git a/tests/integration/test_v2_report_runs.py b/tests/integration/test_v2_report_runs.py index a05ef7b8b..2e3e8fd73 100644 --- a/tests/integration/test_v2_report_runs.py +++ b/tests/integration/test_v2_report_runs.py @@ -99,23 +99,12 @@ def current_versions(country_id: str) -> PackageVersions: return PackageVersions(**CURRENT_VERSIONS) -def mark_manual(connection: Connection, run_id: UUID) -> None: - """Record the report run as a re-run, as the simulation service creates one.""" - connection.execute( - text("UPDATE report_runs SET trigger = 'manual' WHERE id = :id"), - {"id": run_id}, - ) - - -def mark_window_manual( +def set_window_recalculate( connection: Connection, window_run_id: UUID, *, recalculate: bool ) -> None: - """Record the window run as a re-run, as the simulation service creates one.""" + """Record whether the window run is forced, as the simulation service does.""" connection.execute( - text( - "UPDATE budget_window_runs SET trigger = 'manual', recalculate = " - ":recalculate WHERE id = :id" - ), + text("UPDATE budget_window_runs SET recalculate = :recalculate WHERE id = :id"), {"id": window_run_id, "recalculate": recalculate}, ) @@ -197,7 +186,9 @@ def rerun_report(self, rerun: ReportRerunInput) -> StartedReportRun: window_run_id = store_window_run( connection, self.catalog, report, settings, self.window_years ) - mark_window_manual(connection, window_run_id, recalculate=rerun.force) + set_window_recalculate( + connection, window_run_id, recalculate=rerun.force + ) self.new_run_ids.append(window_run_id) started = StartedReportRun( report_run_id=connection.execute( @@ -211,7 +202,6 @@ def rerun_report(self, rerun: ReportRerunInput) -> StartedReportRun: ) else: run_ids = store_report_run(connection, self.catalog, report, settings) - mark_manual(connection, run_ids.report_run_id) if rerun.include_cliffs: for simulation_run_id in ( run_ids.baseline_simulation_run_id, @@ -350,7 +340,6 @@ def test_a_reports_runs_are_listed_newest_first_with_their_versions( error_message="The reform simulation failed", ), ) - mark_manual(connection, failed.report_run_id) newest = store_report_run( connection, catalog, @@ -361,7 +350,6 @@ def test_a_reports_runs_are_listed_newest_first_with_their_versions( created_at=STARTED_AT + timedelta(days=2), ), ) - mark_manual(connection, newest.report_run_id) other_report = store_report(connection, catalog) store_report_run( connection, @@ -386,11 +374,8 @@ def test_a_reports_runs_are_listed_newest_first_with_their_versions( str(failed.report_run_id), str(first.report_run_id), ] - assert [(item["status"], item["trigger"]) for item in items] == [ - ("running", "manual"), - ("failed", "manual"), - ("succeeded", "initial"), - ] + assert [item["status"] for item in items] == ["running", "failed", "succeeded"] + assert all("trigger" not in item for item in items) assert [item["policyengine_version"] for item in items] == [ "4.2.0", "4.2.0", @@ -485,7 +470,6 @@ def test_a_household_reports_runs_are_listed_newest_first_with_their_versions( created_at=STARTED_AT + timedelta(days=1), ), ) - mark_manual(connection, newest.report_run_id) client = client_for( runtime_sessions, RerunningSimulationService(owner_engine, catalog) ) @@ -502,10 +486,8 @@ def test_a_household_reports_runs_are_listed_newest_first_with_their_versions( str(newest.report_run_id), str(first.report_run_id), ] - assert [(item["status"], item["trigger"]) for item in items] == [ - ("pending", "manual"), - ("succeeded", "initial"), - ] + assert [item["status"] for item in items] == ["pending", "succeeded"] + assert all("trigger" not in item for item in items) assert [item["policyengine_version"] for item in items] == ["4.2.0", "4.1.0"] @@ -544,7 +526,7 @@ def test_a_household_report_runs_again_where_households_are_calculated( assert item["kind"] == "household" assert item["status"] == "pending" assert item["run"]["id"] == str(new_run_id) - assert item["run"]["trigger"] == "manual" + assert "trigger" not in item["run"] assert item["run"]["policyengine_version"] == "4.2.0" assert item["result"] is None runs = client.get(f"/v2/reports/{report.report_id}/runs?country_id=uk").json() @@ -592,7 +574,7 @@ def test_running_a_report_again_answers_it_with_its_new_run( assert item["id"] == str(report.report_id) assert item["status"] == "pending" assert item["run"]["id"] == str(new_run_id) - assert item["run"]["trigger"] == "manual" + assert "trigger" not in item["run"] assert item["run"]["policyengine_version"] == "4.2.0" assert item["current_versions"] == CURRENT_VERSIONS assert item["result"] is None @@ -792,7 +774,7 @@ def test_a_budget_windows_runs_are_listed_newest_first_with_their_years( ), (2026, 2027), ) - mark_window_manual(connection, newest_run_id, recalculate=True) + set_window_recalculate(connection, newest_run_id, recalculate=True) client = client_for( runtime_sessions, RerunningSimulationService(owner_engine, catalog) ) @@ -806,9 +788,11 @@ def test_a_budget_windows_runs_are_listed_newest_first_with_their_years( assert result["current_versions"] == CURRENT_VERSIONS items = result["items"] assert [item["id"] for item in items] == [str(newest_run_id), str(first_run_id)] - assert [ - (item["status"], item["trigger"], item["recalculate"]) for item in items - ] == [("running", "manual", True), ("succeeded", "initial", False)] + assert [(item["status"], item["recalculate"]) for item in items] == [ + ("running", True), + ("succeeded", False), + ] + assert all("trigger" not in item for item in items) assert [item["policyengine_version"] for item in items] == ["4.2.0", "4.1.0"] assert [[year["year"] for year in item["years"]] for item in items] == [ [2026, 2027], @@ -860,7 +844,7 @@ def test_running_a_budget_window_again_answers_it_with_its_new_run( assert item["kind"] == "budget_window" assert item["status"] == "pending" assert item["run"]["id"] == str(new_run_id) - assert item["run"]["trigger"] == "manual" + assert "trigger" not in item["run"] assert item["run"]["recalculate"] is force assert item["run"]["policyengine_version"] == "4.2.0" assert item["result"] is None diff --git a/tests/unit/v2/budget_window_report_support.py b/tests/unit/v2/budget_window_report_support.py index b364168c4..4817290b1 100644 --- a/tests/unit/v2/budget_window_report_support.py +++ b/tests/unit/v2/budget_window_report_support.py @@ -62,7 +62,6 @@ def budget_window_year_read(year: int, **changes: Any) -> BudgetWindowYearRead: "year": year, "id": YEAR_RUN_IDS[year], "status": "succeeded", - "trigger": "initial", "country_package_version": "1.4.0", "policyengine_version": "4.1.0", "baseline_simulation_run_id": UUID(int=year * 2), @@ -79,7 +78,6 @@ def budget_window_run_read(**changes: Any) -> BudgetWindowRunRead: values: dict[str, Any] = { "id": BUDGET_WINDOW_RUN_ID, "status": "succeeded", - "trigger": "initial", "recalculate": False, "country_package_version": "1.4.0", "policyengine_version": "4.1.0", diff --git a/tests/unit/v2/report_run_support.py b/tests/unit/v2/report_run_support.py index 83c4317e0..efe1beee3 100644 --- a/tests/unit/v2/report_run_support.py +++ b/tests/unit/v2/report_run_support.py @@ -44,7 +44,6 @@ def report_runs_read() -> ReportRunsRead: report_run_read( id=NEW_RUN_ID, status="pending", - trigger="manual", country_package_version=CURRENT_VERSIONS.country_package_version, policyengine_version=CURRENT_VERSIONS.policyengine_version, created_at=CREATED_AT + timedelta(days=3), @@ -75,7 +74,6 @@ def budget_window_runs_read() -> BudgetWindowRunsRead: budget_window_run_read( id=NEW_WINDOW_RUN_ID, status="pending", - trigger="manual", recalculate=True, created_at=rerun_at, started_at=None, @@ -87,7 +85,6 @@ def budget_window_runs_read() -> BudgetWindowRunsRead: baseline_simulation_run_id=UUID(int=year * 2 + 10_000), reform_simulation_run_id=UUID(int=year * 2 + 10_001), status="pending", - trigger="manual", created_at=rerun_at, started_at=None, completed_at=None, diff --git a/tests/unit/v2/sqlite_report_rows.py b/tests/unit/v2/sqlite_report_rows.py index 6a3efa5e8..c96aac0d3 100644 --- a/tests/unit/v2/sqlite_report_rows.py +++ b/tests/unit/v2/sqlite_report_rows.py @@ -111,7 +111,6 @@ def store_economy_report( ) stored = Report( id=uuid4() if report.report_id is None else report.report_id, - label="A stored report", country=place.country, tax_benefit_model_id=place.model_id, baseline_simulation_id=simulations[0].id, diff --git a/tests/unit/v2/stored_report_support.py b/tests/unit/v2/stored_report_support.py index bb3c89757..8f191bfdd 100644 --- a/tests/unit/v2/stored_report_support.py +++ b/tests/unit/v2/stored_report_support.py @@ -65,7 +65,6 @@ def report_run_read(**changes: Any) -> ReportRunRead: values: dict[str, Any] = { "id": REPORT_RUN_ID, "status": "succeeded", - "trigger": "initial", "country_package_version": "1.4.0", "policyengine_version": "4.1.0", "baseline_simulation_run_id": BASELINE_RUN_ID, diff --git a/tests/unit/v2/test_budget_window_report_read_routes.py b/tests/unit/v2/test_budget_window_report_read_routes.py index e27cc49ba..6d237ffa3 100644 --- a/tests/unit/v2/test_budget_window_report_read_routes.py +++ b/tests/unit/v2/test_budget_window_report_read_routes.py @@ -15,7 +15,6 @@ budget_window_report_read, budget_window_run_read, budget_window_summary_read, - budget_window_year_read, ) from tests.unit.v2.stored_report_support import ( REPORT_ID, @@ -42,11 +41,8 @@ def test_a_budget_window_answers_its_window_newest_run_years_and_result() -> Non assert (item["year"], item["budget_window_size"]) == (2026, 2) run = item["run"] assert run["id"] == str(BUDGET_WINDOW_RUN_ID) - assert (run["status"], run["trigger"], run["recalculate"]) == ( - "succeeded", - "initial", - False, - ) + assert (run["status"], run["recalculate"]) == ("succeeded", False) + assert "trigger" not in run assert (run["country_package_version"], run["policyengine_version"]) == ( "1.4.0", "4.1.0", @@ -58,7 +54,6 @@ def test_a_budget_window_answers_its_window_newest_run_years_and_result() -> Non "year", "id", "status", - "trigger", "country_package_version", "policyengine_version", "baseline_simulation_run_id", @@ -81,20 +76,14 @@ def test_a_budget_window_answers_its_window_newest_run_years_and_result() -> Non ] -def test_a_window_run_and_its_years_without_a_trigger_answer_it_as_null() -> None: - run = budget_window_run_read( - trigger=None, - years=tuple( - budget_window_year_read(year, trigger=None) for year in YEAR_RUN_IDS - ), - ) - service = FakeReportService(report=budget_window_report_read(run=run, label=None)) +def test_a_window_run_and_its_years_answer_no_trigger() -> None: + service = FakeReportService(report=budget_window_report_read(label=None)) item = read_item(service) assert item["label"] is None - assert item["run"]["trigger"] is None - assert {year["trigger"] for year in item["run"]["years"]} == {None} + assert "trigger" not in item["run"] + assert all("trigger" not in year for year in item["run"]["years"]) def test_a_budget_window_without_a_run_answers_no_run_and_no_result() -> None: diff --git a/tests/unit/v2/test_household_report_reads.py b/tests/unit/v2/test_household_report_reads.py index 14ec4b7ef..b9903c377 100644 --- a/tests/unit/v2/test_household_report_reads.py +++ b/tests/unit/v2/test_household_report_reads.py @@ -25,7 +25,6 @@ Report, ReportRun, ReportRunStatus, - ReportRunTrigger, Simulation, SimulationRun, SimulationStatus, @@ -225,8 +224,6 @@ def simulation(policy_id: UUID | None) -> Simulation: session.add_all([side for side in (baseline, reform) if side is not None]) session.flush() report = Report( - label="My household under the reform", - description="Doubles the credit", country=country, tax_benefit_model_id=model.id, baseline_simulation_id=baseline.id, @@ -275,7 +272,6 @@ def simulation_run( baseline_simulation_run_id=baseline_run.id, reform_simulation_run_id=None if reform_run is None else reform_run.id, status=run.status, - trigger=ReportRunTrigger.INITIAL, created_at=STORED_AT, started_at=STORED_AT, completed_at=completed_at, @@ -535,7 +531,6 @@ def store_economy_report(session: Session) -> UUID: session.add(model) session.flush() report = Report( - label="Economy", country="us", tax_benefit_model_id=model.id, year=2026, diff --git a/tests/unit/v2/test_report_column_mapping.py b/tests/unit/v2/test_report_column_mapping.py new file mode 100644 index 000000000..9832ae010 --- /dev/null +++ b/tests/unit/v2/test_report_column_mapping.py @@ -0,0 +1,67 @@ +"""API v1's models leave out the report columns a later revision drops. + +The deploy upgrades the database before new code takes traffic, so the release +serving during that upgrade must not name a column it removes. The tables keep +the columns until then: only the models stop selecting and writing them. +""" + +import pytest +import sqlalchemy as sa +from sqlmodel import select + +from policyengine_api.data.v2.models import ( + V2_METADATA, + BudgetWindowRun, + Report, + ReportRun, + User, +) + +UNMAPPED_COLUMNS = [ + (Report, "label"), + (Report, "description"), + (Report, "user_id"), + (ReportRun, "trigger"), + (BudgetWindowRun, "trigger"), +] + + +@pytest.mark.parametrize(("model", "column_name"), UNMAPPED_COLUMNS) +def test_a_whole_row_read_names_no_unmapped_column( + model: type, column_name: str +) -> None: + selected_names = {column.name for column in select(model).selected_columns} + + assert column_name not in selected_names + + +@pytest.mark.parametrize(("model", "column_name"), UNMAPPED_COLUMNS) +def test_a_model_has_no_attribute_for_an_unmapped_column( + model: type, column_name: str +) -> None: + assert column_name not in sa.inspect(model).column_attrs + assert not hasattr(model, column_name) + + +@pytest.mark.parametrize(("model", "column_name"), UNMAPPED_COLUMNS) +def test_the_table_keeps_an_unmapped_column_until_a_revision_drops_it( + model: type, column_name: str +) -> None: + column = V2_METADATA.tables[model.__tablename__].c[column_name] + + assert column.nullable + assert column.server_default is None + + +def test_the_reports_user_key_and_index_stay_with_the_column() -> None: + reports = V2_METADATA.tables["reports"] + + (user_key,) = reports.c.user_id.foreign_keys + assert user_key.target_fullname == "users.id" + assert user_key.ondelete == "SET NULL" + assert "ix_reports_user_id" in {index.name for index in reports.indexes} + + +def test_reports_and_users_have_no_relationship() -> None: + assert "user" not in Report.__sqlmodel_relationships__ + assert "reports" not in User.__sqlmodel_relationships__ diff --git a/tests/unit/v2/test_report_dataset_independent_keys.py b/tests/unit/v2/test_report_dataset_independent_keys.py index 9cac9c32b..5f49158b7 100644 --- a/tests/unit/v2/test_report_dataset_independent_keys.py +++ b/tests/unit/v2/test_report_dataset_independent_keys.py @@ -121,7 +121,6 @@ def store_household_report( session.add_all(simulations) session.flush() report = Report( - label="My household", country=catalog.country, tax_benefit_model_id=catalog.model_id, baseline_simulation_id=simulations[0].id, diff --git a/tests/unit/v2/test_report_read_routes.py b/tests/unit/v2/test_report_read_routes.py index 7513986be..7270c4acc 100644 --- a/tests/unit/v2/test_report_read_routes.py +++ b/tests/unit/v2/test_report_read_routes.py @@ -73,12 +73,10 @@ def test_a_reports_spm_receipts_are_answered_with_package_names_as_keys() -> Non } -def test_a_report_without_a_label_or_run_trigger_answers_them_as_null() -> None: +def test_a_report_without_a_label_answers_null_and_its_run_no_trigger() -> None: """A shared report holds no caller's label, and its runs no request's trigger.""" service = FakeReportService() - service.report = replace( - service.report, label=None, run=report_run_read(trigger=None) - ) + service.report = replace(service.report, label=None, run=report_run_read()) client = report_route_client(reports=service) response = client.get(f"/v2/reports/{REPORT_ID}?country_id=us") @@ -86,7 +84,7 @@ def test_a_report_without_a_label_or_run_trigger_answers_them_as_null() -> None: assert response.status_code == 200, response.text item = response.json()["result"]["item"] assert item["label"] is None - assert item["run"]["trigger"] is None + assert "trigger" not in item["run"] def test_a_report_without_a_run_answers_with_no_run_and_no_result() -> None: diff --git a/tests/unit/v2/test_report_rerun_service.py b/tests/unit/v2/test_report_rerun_service.py index bd948a040..34a58fd5d 100644 --- a/tests/unit/v2/test_report_rerun_service.py +++ b/tests/unit/v2/test_report_rerun_service.py @@ -14,7 +14,6 @@ BudgetWindowRun, Report, ReportRunStatus, - ReportRunTrigger, ) from policyengine_api.services.v2.simulation_service.types import ( PackageVersions, @@ -74,7 +73,6 @@ def rerun_report(self, rerun: ReportRerunInput) -> StartedReportRun: def stored_rows(**report_columns: object) -> StoredReportRows: report = Report( id=REPORT_ID, - label="Reform", country="us", tax_benefit_model_id=uuid4(), year=2026, @@ -147,7 +145,6 @@ def test_a_window_run_with_no_year_lists_no_years_and_no_versions() -> None: updated_at=STORED_AT, report_id=REPORT_ID, tax_benefit_model_version_id=uuid4(), - trigger=ReportRunTrigger.MANUAL, recalculate=True, status=ReportRunStatus.PENDING, ) @@ -162,7 +159,7 @@ def test_a_window_run_with_no_year_lists_no_years_and_no_versions() -> None: assert runs.kind == "budget_window" (run,) = runs.runs assert run.id == window_run.id - assert (run.trigger, run.recalculate, run.status) == ("manual", True, "pending") + assert (run.recalculate, run.status) == (True, "pending") assert run.years == () assert run.country_package_version is None assert run.policyengine_version is None diff --git a/tests/unit/v2/test_report_run_creation.py b/tests/unit/v2/test_report_run_creation.py index ac0959f9b..21a03297d 100644 --- a/tests/unit/v2/test_report_run_creation.py +++ b/tests/unit/v2/test_report_run_creation.py @@ -15,7 +15,6 @@ Report, ReportRun, ReportRunStatus, - ReportRunTrigger, TaxBenefitModel, ) from policyengine_api.data.v2.report_runs import ( @@ -50,7 +49,6 @@ def _create_report(session: Session) -> Report: session.add(model) session.flush() report = Report( - label="Distributional report", country="us", tax_benefit_model_id=model.id, inputs={}, @@ -75,31 +73,9 @@ def test_unknown_report_is_rejected_before_any_validation(engine) -> None: ), simulation_runs=SIMULATION_RUNS, ), - trigger=ReportRunTrigger.MANUAL, ) -def test_manual_run_without_a_key_is_rejected_before_version_checks(engine) -> None: - with Session(engine) as session: - report = _create_report(session) - - with pytest.raises( - ValueError, match=r"^manual report reruns require an idempotency key$" - ): - create_report_run( - session, - report_id=report.id, - inputs=ReportRunInputs( - versions=ReportRunPackageVersions( - country_package_version="", - policyengine_version="", - ), - simulation_runs=SIMULATION_RUNS, - ), - trigger=ReportRunTrigger.MANUAL, - ) - - @pytest.mark.parametrize( ("country_package_version", "policyengine_version"), [("", "4.5.6"), ("1.2.3", "")], @@ -125,7 +101,6 @@ def test_empty_package_versions_are_rejected( ), simulation_runs=SIMULATION_RUNS, ), - trigger=ReportRunTrigger.SYSTEM, ) @@ -143,7 +118,6 @@ def test_run_without_a_key_is_inserted_without_a_savepoint(engine) -> None: ), simulation_runs=SIMULATION_RUNS, ), - trigger=ReportRunTrigger.INITIAL, ) stored = session.exec(select(ReportRun)).one() @@ -151,7 +125,6 @@ def test_run_without_a_key_is_inserted_without_a_savepoint(engine) -> None: assert run.report_id == report.id assert run.country_package_version == "1.2.3" assert run.policyengine_version == "4.5.6" - assert run.trigger is ReportRunTrigger.INITIAL assert run.idempotency_key is None assert run.status is ReportRunStatus.PENDING assert run.baseline_simulation_run_id == UUID(int=101) @@ -184,7 +157,6 @@ def failing_savepoint(): ), simulation_runs=SIMULATION_RUNS, ), - trigger=ReportRunTrigger.MANUAL, idempotency_key=uuid4(), ) diff --git a/tests/unit/v2/test_report_run_routes.py b/tests/unit/v2/test_report_run_routes.py index 9ce831810..0760fa244 100644 --- a/tests/unit/v2/test_report_run_routes.py +++ b/tests/unit/v2/test_report_run_routes.py @@ -73,7 +73,7 @@ def test_a_reports_runs_are_answered_newest_first_with_versions_and_current_ones str(NEW_RUN_ID), str(REPORT_RUN_ID), ] - assert [run["trigger"] for run in result["items"]] == ["manual", "initial"] + assert all("trigger" not in run for run in result["items"]) assert [ (run["country_package_version"], run["policyengine_version"]) for run in result["items"] @@ -134,7 +134,8 @@ def test_a_budget_windows_runs_are_answered_with_their_years() -> None: assert result["kind"] == "budget_window" newest, first = result["items"] assert newest["id"] == str(NEW_WINDOW_RUN_ID) - assert (newest["trigger"], newest["recalculate"]) == ("manual", True) + assert newest["recalculate"] is True + assert "trigger" not in newest assert newest["policyengine_version"] == "4.2.0" assert [year["year"] for year in first["years"]] == [2026, 2027] assert first["years"][0]["country_package_version"] == "1.4.0" @@ -225,7 +226,7 @@ def test_running_a_report_again_answers_the_report_with_its_new_run( service.report = replace( service.report, status="pending", - run=report_run_read(id=NEW_RUN_ID, status="pending", trigger="manual"), + run=report_run_read(id=NEW_RUN_ID, status="pending"), result=None, ) @@ -236,7 +237,7 @@ def test_running_a_report_again_answers_the_report_with_its_new_run( assert item["id"] == str(REPORT_ID) assert item["status"] == "pending" assert item["run"]["id"] == str(NEW_RUN_ID) - assert item["run"]["trigger"] == "manual" + assert "trigger" not in item["run"] assert item["result"] is None assert item["current_versions"]["policyengine_version"] == "4.2.0" assert service.calls == [ diff --git a/tests/unit/v2/test_report_runs.py b/tests/unit/v2/test_report_runs.py index 44558041b..a4ac72257 100644 --- a/tests/unit/v2/test_report_runs.py +++ b/tests/unit/v2/test_report_runs.py @@ -20,7 +20,6 @@ Report, ReportRun, ReportRunStatus, - ReportRunTrigger, Simulation, SimulationType, TaxBenefitModel, @@ -67,7 +66,6 @@ def _create_report(session: Session, *, report_type: str | None = None) -> Repor session.add(model) session.flush() report = Report( - label="Distributional report", country="us", type=report_type, tax_benefit_model_id=model.id, @@ -96,7 +94,6 @@ def _create_run( ), simulation_runs=SIMULATION_RUNS, ), - trigger=ReportRunTrigger.MANUAL, idempotency_key=key if key is not None else uuid4(), ) @@ -113,7 +110,6 @@ def _create_forced_run(session: Session, report: Report) -> ReportRun: reform_simulation_run_id=SIMULATION_RUNS.reform_simulation_run_id, country_package_version="1.2.3", policyengine_version=DEPLOYED_POLICYENGINE_VERSION, - trigger=ReportRunTrigger.MANUAL, idempotency_key=uuid4(), forced=True, ) @@ -179,25 +175,6 @@ def test_new_manual_keys_create_a_same_version_run_once_the_last_one_failed( assert len(session.exec(select(ReportRun)).all()) == 2 -def test_manual_rerun_requires_an_idempotency_key(engine) -> None: - with Session(engine) as session: - report = _create_report(session) - - with pytest.raises(ValueError, match="require an idempotency key"): - create_report_run( - session, - report_id=report.id, - inputs=ReportRunInputs( - versions=ReportRunPackageVersions( - country_package_version="1.2.3", - policyengine_version=DEPLOYED_POLICYENGINE_VERSION, - ), - simulation_runs=SIMULATION_RUNS, - ), - trigger=ReportRunTrigger.MANUAL, - ) - - def test_idempotency_key_round_trips_as_a_python_uuid(engine) -> None: with Session(engine) as session: report = _create_report(session) @@ -259,7 +236,6 @@ def request_rerun() -> UUID: ), simulation_runs=SIMULATION_RUNS, ), - trigger=ReportRunTrigger.MANUAL, idempotency_key=request_key, ) run_id = run.id diff --git a/tests/unit/v2/test_shared_report_models.py b/tests/unit/v2/test_shared_report_models.py index 3312b02ad..031d6d281 100644 --- a/tests/unit/v2/test_shared_report_models.py +++ b/tests/unit/v2/test_shared_report_models.py @@ -413,8 +413,8 @@ def report_run(*, window_year: int | None) -> ReportRun: sqlite_session.commit() -def test_stored_runs_without_a_trigger_read_as_null() -> None: - """The run lists pass on a missing trigger as null (the route tests a label).""" +def test_stored_runs_are_read_without_a_trigger() -> None: + """A shared run has no one trigger: each user's is on their record of it.""" window_run_id = uuid4() run = ReportRun( report_id=uuid4(), @@ -422,7 +422,6 @@ def test_stored_runs_without_a_trigger_read_as_null() -> None: country_package_version="1.5.0", policyengine_version="4.2.0", status=ReportRunStatus.PENDING, - trigger=None, ) year_run = ReportRun( report_id=run.report_id, @@ -432,19 +431,17 @@ def test_stored_runs_without_a_trigger_read_as_null() -> None: country_package_version="1.5.0", policyengine_version="4.2.0", status=ReportRunStatus.PENDING, - trigger=None, ) window_run = BudgetWindowRun( id=window_run_id, report_id=run.report_id, tax_benefit_model_version_id=uuid4(), status=ReportRunStatus.PENDING, - trigger=None, ) - assert stored_report_transformations.report_run_read(run).trigger is None + assert not hasattr(stored_report_transformations.report_run_read(run), "trigger") window_read = stored_report_transformations.budget_window_run_read( window_run, [year_run] ) - assert window_read.trigger is None - assert [year.trigger for year in window_read.years] == [None] + assert not hasattr(window_read, "trigger") + assert not any(hasattr(year, "trigger") for year in window_read.years) From 2d3ee79a8803984e8242db97554966d0b449c727 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:07:22 +0400 Subject: [PATCH 2/7] Stop mapping the report columns a later revision drops Report leaves out label, description and user_id, and ReportRun and BudgetWindowRun leave out trigger, so API v1 neither selects nor writes them. The tables keep the columns, so there is no revision, and a release of this code keeps serving /v2/reports while a later revision drops them. Run items and budget-window run items no longer have a trigger field, and create_report_run takes none. Co-Authored-By: Claude Opus 5.5 --- ...mapping-report-per-user-columns.removed.md | 1 + docs/engineering/skills/alembic-migrations.md | 7 +- policyengine_api/data/v2/models/reports.py | 68 ++++++++++--------- policyengine_api/data/v2/models/users.py | 6 +- policyengine_api/data/v2/report_runs.py | 6 -- .../v2/reports/response_models.py | 11 +-- .../v2/stored_reports/transformations.py | 6 +- .../services/v2/stored_reports/types.py | 9 +-- 8 files changed, 49 insertions(+), 65 deletions(-) create mode 100644 changelog.d/stop-mapping-report-per-user-columns.removed.md diff --git a/changelog.d/stop-mapping-report-per-user-columns.removed.md b/changelog.d/stop-mapping-report-per-user-columns.removed.md new file mode 100644 index 000000000..579927b93 --- /dev/null +++ b/changelog.d/stop-mapping-report-per-user-columns.removed.md @@ -0,0 +1 @@ +`/v2/reports` run items and budget-window run items no longer have a `trigger` field: a run is shared between requests, and each user's trigger is on their record of it. API v1 no longer selects or writes the per-user columns of reports, report runs and budget-window runs, which a later database revision drops. diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 9e0f86351..912203272 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -928,10 +928,9 @@ from there gives the same operations. - The per-user columns of shared rows become nullable, with no default: `reports.label`, `report_runs.trigger` and `budget_window_runs.trigger` (`reports.description` and `user_id` already were). A shared row describes - no one caller, so the simulation service stops writing them, and a later - revision drops them; until then the report read and run lists answer a - missing label or trigger as null. A user's trigger is on their - `user_report_run_associations` row. + no one caller, so the simulation service stops writing them, API v1's models + leave them out, and a later revision drops them. A user's trigger is on + their `user_report_run_associations` row. - `user_report_run_associations` records each user's request for a report run: the user (`CASCADE`), the run (`RESTRICT`, so a run a user asked for can't be deleted), `requested_at` (required, with no default: the writer diff --git a/policyengine_api/data/v2/models/reports.py b/policyengine_api/data/v2/models/reports.py index 3336b3130..12aab24fe 100644 --- a/policyengine_api/data/v2/models/reports.py +++ b/policyengine_api/data/v2/models/reports.py @@ -7,7 +7,7 @@ from datetime import datetime from enum import StrEnum -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, ClassVar from uuid import UUID import sqlalchemy as sa @@ -28,7 +28,6 @@ ) from policyengine_api.data.v2.models.policies import Policy from policyengine_api.data.v2.models.simulations import Simulation -from policyengine_api.data.v2.models.users import User if TYPE_CHECKING: from policyengine_api.data.v2.models.run_results import ( @@ -61,7 +60,10 @@ class ReportRunStatus(StrEnum): class ReportRunTrigger(StrEnum): - """Why a report run started: the report's first run, a manual or a system rerun.""" + """Why a user asked for a report run: the report's creation or a re-run. + + ``system`` remains in the database type; no user's record may hold it. + """ INITIAL = "initial" MANUAL = "manual" @@ -71,13 +73,18 @@ class ReportRunTrigger(StrEnum): class Report(TimestampedModel, table=True): """Stable report definition; execution state belongs to ReportRun. - The simulation service writes reports, and the Public API the user, model, - policy, household, dataset and region a report names; each service writes - only its own tables, and the foreign keys between them stay. Deleting the - user, policy, dataset or region clears the reference, which for the user - is found through ``user_id``'s index; the model and household can't be + The simulation service writes reports, and API v1 the model, policy, + household, dataset and region a report names; each service writes only its + own tables, and the foreign keys between them stay. Deleting the policy, + dataset or region clears the reference; the model and household can't be deleted while a report names them. + A report is shared by everyone who asks for it, so it describes no one + caller: a report's name and description are on each user's saved report. + The table's ``label``, ``description`` and ``user_id`` are left out of this + model, so API v1 neither loads nor writes them and a release keeps working + while a later revision drops them. + 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, @@ -89,7 +96,19 @@ class Report(TimestampedModel, table=True): """ __tablename__ = "reports" + __mapper_args__: ClassVar[dict[str, Any]] = { + "exclude_properties": ("label", "description", "user_id") + } __table_args__ = ( + # Kept in the table, unmapped, until a revision drops them. + sa.Column("label", sa.String(255)), + sa.Column("description", sa.String), + sa.Column( + "user_id", + sa.Uuid, + sa.ForeignKey("users.id", ondelete="SET NULL"), + index=True, + ), sa.CheckConstraint( "year IS NULL OR year BETWEEN 1900 AND 2200", name="ck_reports_year", @@ -117,18 +136,8 @@ class Report(TimestampedModel, table=True): sa.Index("ix_reports_dataset_independent_key", "dataset_independent_key"), ) - # Per-user: nullable until a later revision drops it, since a shared report - # describes no one caller. - label: str | None = Field(default=None, max_length=255) - description: str | None = None country: str = Field(max_length=16) type: str | None = Field(default=None, max_length=128) - user_id: UUID | None = Field( - default=None, - foreign_key="users.id", - ondelete="SET NULL", - index=True, - ) tax_benefit_model_id: UUID = Field( foreign_key="tax_benefit_models.id", ondelete="RESTRICT", @@ -171,7 +180,6 @@ class Report(TimestampedModel, table=True): definition_key: str | None = Field(default=None, max_length=64) dataset_independent_key: str | None = Field(default=None, max_length=64) - user: User | None = Relationship(back_populates="reports") tax_benefit_model: TaxBenefitModel = Relationship(back_populates="reports") policy: Policy | None = Relationship(back_populates="reports") baseline_simulation: Simulation | None = Relationship( @@ -217,7 +225,12 @@ class BudgetWindowRun(TimestampedModel, table=True): """ __tablename__ = "budget_window_runs" + __mapper_args__: ClassVar[dict[str, Any]] = {"exclude_properties": ("trigger",)} __table_args__ = ( + # Kept in the table, unmapped, until a revision drops it: a shared run + # answers more than one request, and each user's trigger is on their + # record of it. + sa.Column("trigger", enum_type(ReportRunTrigger, "v2_report_run_trigger")), sa.UniqueConstraint("id", "report_id", name="uq_budget_window_runs_id_report"), sa.CheckConstraint( "status NOT IN ('succeeded', 'failed') OR completed_at IS NOT NULL", @@ -247,12 +260,6 @@ class BudgetWindowRun(TimestampedModel, table=True): index=True, ) policyengine_version: str | None = Field(default=None, max_length=128) - # Per-user: nullable until a later revision drops it, since a shared run - # answers more than one request; each user's trigger is on their record. - trigger: ReportRunTrigger | None = Field( - default=None, - sa_type=enum_type(ReportRunTrigger, "v2_report_run_trigger"), - ) recalculate: bool = False status: ReportRunStatus = Field( default=ReportRunStatus.PENDING, @@ -290,7 +297,12 @@ class ReportRun(TimestampedModel, table=True): """ __tablename__ = "report_runs" + __mapper_args__: ClassVar[dict[str, Any]] = {"exclude_properties": ("trigger",)} __table_args__ = ( + # Kept in the table, unmapped, until a revision drops it: a shared run + # answers more than one request, and each user's trigger is on their + # record of it. + sa.Column("trigger", enum_type(ReportRunTrigger, "v2_report_run_trigger")), sa.UniqueConstraint( "report_id", "idempotency_key", @@ -375,12 +387,6 @@ class ReportRun(TimestampedModel, table=True): default=ReportRunStatus.PENDING, sa_type=enum_type(ReportRunStatus, "v2_report_run_status"), ) - # Per-user: nullable until a later revision drops it, since a shared run - # answers more than one request; each user's trigger is on their record. - trigger: ReportRunTrigger | None = Field( - default=None, - sa_type=enum_type(ReportRunTrigger, "v2_report_run_trigger"), - ) idempotency_key: UUID | None = Field(default=None) modal_call_id: str | None = Field(default=None, max_length=255) started_at: datetime | None = Field( diff --git a/policyengine_api/data/v2/models/users.py b/policyengine_api/data/v2/models/users.py index 0a4d55018..ee923cb08 100644 --- a/policyengine_api/data/v2/models/users.py +++ b/policyengine_api/data/v2/models/users.py @@ -27,7 +27,6 @@ UserReportRunAssociation, UserSimulationAssociation, ) - from policyengine_api.data.v2.models.reports import Report class UserType(StrEnum): @@ -79,8 +78,8 @@ class User(IdentifiedModel, table=True): A signed-in user, of any type but ``unauthenticated``, always has a primary country. Deleting a user deletes their sign-in identities, saved - associations and records of the report runs they asked for; reports they - own are kept without an owner. + associations and records of the report runs they asked for; the reports + and runs themselves are shared and stay. """ __tablename__ = "users" @@ -115,7 +114,6 @@ class User(IdentifiedModel, table=True): sa_column_kwargs={"server_default": UserType.STANDARD.value}, ) - reports: list["Report"] = Relationship(back_populates="user") identities: list["UserIdentity"] = Relationship( back_populates="user", cascade_delete=True, diff --git a/policyengine_api/data/v2/report_runs.py b/policyengine_api/data/v2/report_runs.py index f1980aadd..61c14fc07 100644 --- a/policyengine_api/data/v2/report_runs.py +++ b/policyengine_api/data/v2/report_runs.py @@ -20,7 +20,6 @@ Report, ReportRun, ReportRunStatus, - ReportRunTrigger, ) from policyengine_api.data.v2.models.base import utc_now @@ -113,7 +112,6 @@ def create_report_run( *, report_id: UUID, inputs: ReportRunInputs, - trigger: ReportRunTrigger, idempotency_key: UUID | None = None, ) -> ReportRun: """Create one run, or return the run for a retried idempotent request. @@ -122,9 +120,6 @@ def create_report_run( simulation runs that attempt named. """ _locked_report(session, report_id) - if trigger is ReportRunTrigger.MANUAL and idempotency_key is None: - msg = "manual report reruns require an idempotency key" - raise ValueError(msg) versions = inputs.versions if not versions.country_package_version or not versions.policyengine_version: msg = "report run package versions must be non-empty" @@ -136,7 +131,6 @@ def create_report_run( reform_simulation_run_id=inputs.simulation_runs.reform_simulation_run_id, country_package_version=versions.country_package_version, policyengine_version=versions.policyengine_version, - trigger=trigger, idempotency_key=idempotency_key, ) if idempotency_key is None: diff --git a/policyengine_api/fastapi_routes/v2/reports/response_models.py b/policyengine_api/fastapi_routes/v2/reports/response_models.py index 188cfb9de..12de3cf6b 100644 --- a/policyengine_api/fastapi_routes/v2/reports/response_models.py +++ b/policyengine_api/fastapi_routes/v2/reports/response_models.py @@ -56,15 +56,11 @@ class ReportRunItem(StrictReportAPIModel): """One calculation of a report, on one country package and .py version. ``status`` is ``pending``, ``running``, ``succeeded`` or ``failed``, and - ``error_message`` says why a failed run failed. ``trigger`` is - ``initial`` for the run the report's creation started, and null for a run - the simulation service shares between requests, which records no one - request's trigger. + ``error_message`` says why a failed run failed. """ id: UUID status: Literal["pending", "running", "succeeded", "failed"] - trigger: Literal["initial", "manual", "system"] | None country_package_version: str policyengine_version: str baseline_simulation_run_id: UUID @@ -299,9 +295,7 @@ class BudgetWindowRunItem(StrictReportAPIModel): ``status`` is ``pending`` until a year starts running, ``running`` while its years run, ``failed`` once a year has failed, with ``error_message`` - saying which, and ``succeeded`` once every year has. ``trigger`` is - ``initial`` for the run the report's creation started (null for a shared - run, which records no one request's trigger), and ``recalculate`` says + saying which, and ``succeeded`` once every year has. ``recalculate`` says whether its years calculate their simulations again rather than reusing successful runs. ``country_package_version`` and ``policyengine_version`` are the versions @@ -310,7 +304,6 @@ class BudgetWindowRunItem(StrictReportAPIModel): id: UUID status: Literal["pending", "running", "succeeded", "failed"] - trigger: Literal["initial", "manual", "system"] | None recalculate: bool country_package_version: str | None policyengine_version: str | None diff --git a/policyengine_api/services/v2/stored_reports/transformations.py b/policyengine_api/services/v2/stored_reports/transformations.py index 36c9f0033..e67e76911 100644 --- a/policyengine_api/services/v2/stored_reports/transformations.py +++ b/policyengine_api/services/v2/stored_reports/transformations.py @@ -68,11 +68,10 @@ def report_kind(report: Report) -> ReportKind: def report_run_read(run: ReportRun) -> ReportRunRead: - """Return the run's status, trigger, versions and times.""" + """Return the run's status, versions and times.""" return ReportRunRead( id=run.id, status=run.status.value, - trigger=None if run.trigger is None else run.trigger.value, country_package_version=run.country_package_version, policyengine_version=run.policyengine_version, baseline_simulation_run_id=run.baseline_simulation_run_id, @@ -236,7 +235,7 @@ def household_report_read( def budget_window_run_read( window_run: BudgetWindowRun, years: Sequence[ReportRun] ) -> BudgetWindowRunRead: - """Return the window run's status, trigger and times, with its years. + """Return the window run's status and times, with its years. Its versions are its first year's, since the simulation service creates every year on one version; a run with no year has none. @@ -250,7 +249,6 @@ def budget_window_run_read( return BudgetWindowRunRead( id=window_run.id, status=window_run.status.value, - trigger=None if window_run.trigger is None else window_run.trigger.value, recalculate=window_run.recalculate, country_package_version=( None if first_year is None else first_year.country_package_version diff --git a/policyengine_api/services/v2/stored_reports/types.py b/policyengine_api/services/v2/stored_reports/types.py index 96f8f6cea..30765f965 100644 --- a/policyengine_api/services/v2/stored_reports/types.py +++ b/policyengine_api/services/v2/stored_reports/types.py @@ -52,7 +52,6 @@ # The kinds whose runs are their report runs; a budget window's are its # budget-window runs. ReportRunsKind = Literal["economy", "household"] -ReportRunTriggerName = Literal["initial", "manual", "system"] # 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 # newest calculation failed and none is pending, running or succeeded). @@ -65,15 +64,12 @@ class ReportRunRead: """One calculation of a report, and the package versions it ran on. - ``trigger`` is ``initial`` for the run the report's creation started, and - null for a run the simulation service shares between requests. A user's - trigger is on their record of the run. ``error_message`` says why a failed - run failed. + ``error_message`` says why a failed run failed. A run is shared between + requests, so each user's trigger is on their record of the run. """ id: UUID status: Literal["pending", "running", "succeeded", "failed"] - trigger: ReportRunTriggerName | None country_package_version: str policyengine_version: str baseline_simulation_run_id: UUID @@ -237,7 +233,6 @@ class BudgetWindowRunRead: id: UUID status: Literal["pending", "running", "succeeded", "failed"] - trigger: ReportRunTriggerName | None recalculate: bool country_package_version: str | None policyengine_version: str | None From 71932ac6c13a23687ecc055b54b12501e374e01d Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:15:31 +0400 Subject: [PATCH 3/7] Check that unmapped report columns are not model fields Co-Authored-By: Claude Opus 5.5 --- tests/unit/v2/test_report_column_mapping.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/unit/v2/test_report_column_mapping.py b/tests/unit/v2/test_report_column_mapping.py index 9832ae010..e622276e1 100644 --- a/tests/unit/v2/test_report_column_mapping.py +++ b/tests/unit/v2/test_report_column_mapping.py @@ -40,6 +40,7 @@ def test_a_model_has_no_attribute_for_an_unmapped_column( model: type, column_name: str ) -> None: assert column_name not in sa.inspect(model).column_attrs + assert column_name not in model.model_fields assert not hasattr(model, column_name) From 254ae34cacd6c0a7bcce4a71d5ee8a747c6cbae9 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:33:04 +0400 Subject: [PATCH 4/7] Fix review round 1's findings on the unmapped report columns A catalog publication test stops passing a label the model discards, and a report-run test is named for what it now covers. Co-Authored-By: Claude Opus 5.5 --- tests/integration/test_v2_catalog_publication.py | 1 - tests/unit/v2/test_report_runs.py | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/integration/test_v2_catalog_publication.py b/tests/integration/test_v2_catalog_publication.py index c46fa0f6e..e6c0e1814 100644 --- a/tests/integration/test_v2_catalog_publication.py +++ b/tests/integration/test_v2_catalog_publication.py @@ -505,7 +505,6 @@ def test_republish_preserves_existing_run_and_dataset_version_records( region_id=region.id, ) report = Report( - label="Existing report", country="us", tax_benefit_model_id=model.id, dataset_id=input_dataset.id, diff --git a/tests/unit/v2/test_report_runs.py b/tests/unit/v2/test_report_runs.py index a4ac72257..c942dd28a 100644 --- a/tests/unit/v2/test_report_runs.py +++ b/tests/unit/v2/test_report_runs.py @@ -155,7 +155,7 @@ def test_report_type_can_change_before_first_run_but_not_after(engine) -> None: ) -def test_new_manual_keys_create_a_same_version_run_once_the_last_one_failed( +def test_new_keys_create_a_same_version_run_once_the_last_one_failed( engine, ) -> None: with Session(engine) as session: From f6afd59ed593aa4109d3e4b9e25923a4300c5978 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:18:11 +0400 Subject: [PATCH 5/7] Stop reading the unmapped report columns through the models in four tests The model and shared-row tests read trigger and label from the mappers, which leave them out since the base's ORM-only rule made them SQLModel fields under exclude_properties; they now read the stored schema or leave the columns out. The malformed-key test no longer inserts label. Co-Authored-By: Claude Opus 5.5 --- tests/integration/test_v2_shared_report_rows.py | 1 - tests/unit/v2/test_models.py | 1 - tests/unit/v2/test_shared_report_models.py | 10 ++++------ tests/unit/v2/test_simulation_run_models.py | 4 +--- 4 files changed, 5 insertions(+), 11 deletions(-) diff --git a/tests/integration/test_v2_shared_report_rows.py b/tests/integration/test_v2_shared_report_rows.py index 3dfd28d01..918c54487 100644 --- a/tests/integration/test_v2_shared_report_rows.py +++ b/tests/integration/test_v2_shared_report_rows.py @@ -504,7 +504,6 @@ def test_a_malformed_or_incomplete_key_is_refused( } if table == "simulations" else { - "label": "Report", "country": "us", "tax_benefit_model_id": public_api_rows.model_id, "inputs": {}, diff --git a/tests/unit/v2/test_models.py b/tests/unit/v2/test_models.py index d3d9c7c59..a77821c59 100644 --- a/tests/unit/v2/test_models.py +++ b/tests/unit/v2/test_models.py @@ -317,7 +317,6 @@ def test_report_definition_and_run_columns_are_separated() -> None: "country_package_version", "policyengine_version", "status", - "trigger", "idempotency_key", "started_at", "completed_at", diff --git a/tests/unit/v2/test_shared_report_models.py b/tests/unit/v2/test_shared_report_models.py index 4cfdb0dc3..9496a1c05 100644 --- a/tests/unit/v2/test_shared_report_models.py +++ b/tests/unit/v2/test_shared_report_models.py @@ -228,13 +228,11 @@ def test_per_user_columns_of_shared_rows_need_no_value( ) -> None: """A shared row describes no one caller, so the simulation service may omit them. - They go in a later revision; until then they are nullable, with no default, - so a row written without one holds none. + They go in a later revision; until then the table keeps them nullable, and + the models leave them out of their mappers, so no row API v1 writes names + them. """ - column = model_columns(table_name)[column_name] - - assert column.nullable - assert column.server_default is None + assert stored_v2_table(table_name).columns[column_name].nullable def test_user_report_run_associations_record_each_users_request_for_a_run() -> None: diff --git a/tests/unit/v2/test_simulation_run_models.py b/tests/unit/v2/test_simulation_run_models.py index 3a17d6059..228d4b43e 100644 --- a/tests/unit/v2/test_simulation_run_models.py +++ b/tests/unit/v2/test_simulation_run_models.py @@ -519,14 +519,12 @@ def test_budget_window_runs_record_each_calculation_of_a_window() -> None: "started_at", "completed_at", "policyengine_version", - "trigger", } assert set(windows.keys()) == {"id"} | required | optional assert all(not windows[name].nullable for name in required) assert all(windows[name].nullable for name in optional) - # A window run has a report run's states and starts for a report run's reasons. + # A window run has a report run's states. assert windows.status.type.name == "v2_report_run_status" - assert windows.trigger.type.name == "v2_report_run_trigger" report_key = _foreign_key("budget_window_runs", "report_id") assert report_key.target == "reports.id" assert report_key.ondelete == "CASCADE" From 25b3575a0388c65a2e3ff34ac1d1f1e697e972f7 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:26:02 +0400 Subject: [PATCH 6/7] Fix review round 1's findings on the ORM merge The shared-rows test reads label and both triggers through the column classes, as the rule requires (ReportColumns gains label), instead of the models' class attributes, which are the tables' Core columns. The column-mapping tests check again that the five columns have no server default, and that both triggers keep the shared enum type. The guide and docstrings name every column the mappers leave out. Co-Authored-By: Claude Opus 5.5 --- docs/engineering/skills/alembic-migrations.md | 18 +++++++++++------- tests/integration/privilege_statements.py | 14 ++++++++------ .../integration/test_v2_shared_report_rows.py | 19 ++++++++++++++----- .../test_v2_simulation_role_privileges.py | 7 ++++--- tests/unit/v2/test_report_column_mapping.py | 14 +++++++++++++- tests/unit/v2/test_shared_report_models.py | 5 ++--- 6 files changed, 52 insertions(+), 25 deletions(-) diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 5e8d7ea91..e305f1486 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -309,13 +309,17 @@ and `refused(session, ...)`. `add_row(session, Model, **values)`, given a mapped class. A JSON column takes the Python value, such as `[2026]`, not its JSON text. - **Columns a mapper leaves out**: a column kept in its table but left out of - the model's mapper (`exclude_properties`), such as a report run's four older - cliff columns until a revision drops them, has no statement through the - model: `update(Model).values(column=...)` raises `AttributeError`. A test - that sets one maps it on a class of a registry of its own, as - `tests.integration.privilege_statements.ReportRunColumns` does, and reads it - from SQLite's copy of the schema (`StoredTable.columns` in - `tests.unit.v2.v2_schema_reading`) or from the database's `Inspector`. + the model's mapper (`exclude_properties`), such as a report's `label`, + `description` and `user_id`, a report run's `trigger` and four older cliff + columns, and a budget-window run's `trigger` until a revision drops them, + has no statement through the model: `update(Model).values(column=...)` + raises `AttributeError`, a constructor value is never stored, and + `Model.column` is the table's Core column, which the rule rules out even + in a `select`. A test that sets or selects one maps it on a class of a + registry of its own, as `tests.integration.privilege_statements`' + `ReportColumns`, `ReportRunColumns` and `BudgetWindowRunColumns` do, and + reads its declaration from SQLite's copy of the schema (`StoredTable.columns` + in `tests.unit.v2.v2_schema_reading`) or from the database's `Inspector`. - **Postgres functions**: `func`, as in `session.execute(select(func.current_database(), func.current_user()))`, `func.pg_backend_pid()` and `func.has_table_privilege(...)`. diff --git a/tests/integration/privilege_statements.py b/tests/integration/privilege_statements.py index f9737e436..cfa6e9921 100644 --- a/tests/integration/privilege_statements.py +++ b/tests/integration/privilege_statements.py @@ -14,10 +14,11 @@ refuses a statement on it; a statement sends only the columns it sets. No code creates tables from these classes: Alembic creates them from the models. -``ReportRunColumns`` also maps ``trigger`` and the four older cliff columns, -and ``BudgetWindowRunColumns`` its ``trigger``: the models' mappers leave them -out until a revision drops them. No model maps them, so every test that -writes them, or is refused them, sends its statement through these classes. +``ReportColumns`` also maps ``label``, ``ReportRunColumns`` ``trigger`` and the +four older cliff columns, and ``BudgetWindowRunColumns`` its ``trigger``: the +models' mappers leave them out until a revision drops them. No model maps +them, so every test that reads or writes them, or is refused them, sends its +statement through these classes. """ # No ``from __future__ import annotations``: SQLAlchemy reads the classes' @@ -73,12 +74,13 @@ class SimulationColumns: @named_column_tables.mapped class ReportColumns: - """A report's key version.""" + """A report's key version, and its label, which its mapper leaves out.""" __tablename__ = "reports" id: Mapped[UUID] = mapped_column(primary_key=True) key_version: Mapped[int | None] + label: Mapped[str | None] @named_column_tables.mapped @@ -173,7 +175,7 @@ class ReportRunColumns: reform_cliff_share: Mapped[float | None] -# The report run columns ``ReportRun``'s mapper leaves out, which only +# The four older cliff columns ``ReportRun``'s mapper leaves out, which only # ``ReportRunColumns`` maps. REPORT_RUN_CLIFF_COLUMNS = ( "baseline_cliff_gap", diff --git a/tests/integration/test_v2_shared_report_rows.py b/tests/integration/test_v2_shared_report_rows.py index 918c54487..480e58834 100644 --- a/tests/integration/test_v2_shared_report_rows.py +++ b/tests/integration/test_v2_shared_report_rows.py @@ -50,7 +50,9 @@ ) from tests.fixtures.database_sessions import act_as, act_as_owner, query_plan from tests.integration.privilege_statements import ( + BudgetWindowRunColumns, ReportColumns, + ReportRunColumns, SimulationColumns, unfailed, update_row, @@ -694,11 +696,18 @@ def test_the_simulation_service_writes_shared_rows_without_per_user_columns( act_as(session, managed_v2_roles.runtime) stored = session.execute( - select(col(Report.label), col(ReportRun.trigger), col(BudgetWindowRun.trigger)) - .select_from(Report) - .join(ReportRun, col(ReportRun.report_id) == col(Report.id)) - .join(BudgetWindowRun, col(BudgetWindowRun.report_id) == col(Report.id)) - .where(col(Report.id) == report_id) + select( + ReportColumns.label, + ReportRunColumns.trigger, + BudgetWindowRunColumns.trigger, + ) + .select_from(ReportColumns) + .join(ReportRunColumns, ReportRunColumns.report_id == ReportColumns.id) + .join( + BudgetWindowRunColumns, + BudgetWindowRunColumns.report_id == ReportColumns.id, + ) + .where(ReportColumns.id == report_id) ).one() assert tuple(stored) == (None, None, None) diff --git a/tests/integration/test_v2_simulation_role_privileges.py b/tests/integration/test_v2_simulation_role_privileges.py index f55ac7abd..78f6458d7 100644 --- a/tests/integration/test_v2_simulation_role_privileges.py +++ b/tests/integration/test_v2_simulation_role_privileges.py @@ -18,9 +18,10 @@ models: both simulation roles may update ``updated_at`` on the run, budget-window run and cliff calculation tables, and ``poverty`` and ``withheld_area_codes`` have no ``updated_at``. A column a model's mapper leaves out, such as a report -run's four older cliff columns until a revision drops them, has no statement -through the model, so its writes and refusals go through the class that maps -it, ``ReportRunColumns``. +run's ``trigger`` and four older cliff columns, or a budget-window run's +``trigger``, until a revision drops them, has no statement through the model, +so its writes and refusals go through the class that maps it, +``ReportRunColumns`` or ``BudgetWindowRunColumns``. """ from __future__ import annotations diff --git a/tests/unit/v2/test_report_column_mapping.py b/tests/unit/v2/test_report_column_mapping.py index 09a421b4e..80d6dcb64 100644 --- a/tests/unit/v2/test_report_column_mapping.py +++ b/tests/unit/v2/test_report_column_mapping.py @@ -9,6 +9,7 @@ import pytest import sqlalchemy as sa +from pydantic_core import PydanticUndefined from sqlmodel import select from policyengine_api.data.v2.models import ( @@ -52,9 +53,20 @@ def test_the_table_keeps_an_unmapped_column_until_a_revision_drops_it( model: type, column_name: str ) -> None: stored_column = stored_v2_table(model.__tablename__).columns[column_name] + field = model.model_fields[column_name] + column_arguments = getattr(field, "sa_column_kwargs", None) assert stored_column.nullable - assert model.model_fields[column_name].default is None + assert field.default is None + assert column_arguments in (None, PydanticUndefined) + + +@pytest.mark.parametrize("model", [ReportRun, BudgetWindowRun]) +def test_a_runs_trigger_keeps_the_type_users_run_records_share(model: type) -> None: + trigger_type = model.model_fields["trigger"].sa_type + + assert isinstance(trigger_type, sa.Enum) + assert trigger_type.name == "v2_report_run_trigger" def test_the_reports_user_key_and_index_stay_with_the_column() -> None: diff --git a/tests/unit/v2/test_shared_report_models.py b/tests/unit/v2/test_shared_report_models.py index 9496a1c05..4d27c03cb 100644 --- a/tests/unit/v2/test_shared_report_models.py +++ b/tests/unit/v2/test_shared_report_models.py @@ -228,9 +228,8 @@ def test_per_user_columns_of_shared_rows_need_no_value( ) -> None: """A shared row describes no one caller, so the simulation service may omit them. - They go in a later revision; until then the table keeps them nullable, and - the models leave them out of their mappers, so no row API v1 writes names - them. + They go in a later revision; until then the table keeps them nullable, so + a row written without them is stored. """ assert stored_v2_table(table_name).columns[column_name].nullable From 60233c2140c43f3e8f3c92c71a5f58afc6ae461b Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:39:23 +0400 Subject: [PATCH 7/7] Fix review round 2's findings on the ORM merge The column-only classes take trigger's type from the user records' mapper, which holds the same enum, and the trigger type test compares the runs' type with the user records' instead of checking a name alone. Co-Authored-By: Claude Opus 5.5 --- tests/integration/privilege_statements.py | 16 +++++++--------- tests/unit/v2/test_report_column_mapping.py | 7 +++++-- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/tests/integration/privilege_statements.py b/tests/integration/privilege_statements.py index cfa6e9921..ec22fbf02 100644 --- a/tests/integration/privilege_statements.py +++ b/tests/integration/privilege_statements.py @@ -36,11 +36,10 @@ BudgetWindowRun, CliffImpact, ReportRun, - ReportRunTrigger, Simulation, + UserReportRunAssociation, WithheldAreaCode, ) -from policyengine_api.data.v2.models.base import enum_type def _type_of(model: type[SQLModel], column_name: str) -> TypeEngine[Any]: @@ -49,11 +48,6 @@ def _type_of(model: type[SQLModel], column_name: str) -> TypeEngine[Any]: return column_type.copy() -def _trigger_type() -> TypeEngine[Any]: - """Return the runs' ``trigger`` type, which no model's mapper holds any more.""" - return enum_type(ReportRunTrigger, "v2_report_run_trigger") - - named_column_tables = registry() @@ -147,7 +141,9 @@ class BudgetWindowRunColumns: id: Mapped[UUID] = mapped_column(primary_key=True) report_id: Mapped[UUID] tax_benefit_model_version_id: Mapped[UUID] - trigger: Mapped[str | None] = mapped_column(_trigger_type()) + trigger: Mapped[str | None] = mapped_column( + _type_of(UserReportRunAssociation, "trigger") + ) recalculate: Mapped[bool] status: Mapped[str] = mapped_column(_type_of(BudgetWindowRun, "status")) @@ -168,7 +164,9 @@ class ReportRunColumns: country_package_version: Mapped[str] policyengine_version: Mapped[str] status: Mapped[str] = mapped_column(_type_of(ReportRun, "status")) - trigger: Mapped[str | None] = mapped_column(_trigger_type()) + trigger: Mapped[str | None] = mapped_column( + _type_of(UserReportRunAssociation, "trigger") + ) baseline_cliff_gap: Mapped[float | None] baseline_cliff_share: Mapped[float | None] reform_cliff_gap: Mapped[float | None] diff --git a/tests/unit/v2/test_report_column_mapping.py b/tests/unit/v2/test_report_column_mapping.py index 80d6dcb64..3c3f7ee24 100644 --- a/tests/unit/v2/test_report_column_mapping.py +++ b/tests/unit/v2/test_report_column_mapping.py @@ -18,7 +18,7 @@ ReportRun, User, ) -from tests.unit.v2.v2_schema_reading import stored_v2_table +from tests.unit.v2.v2_schema_reading import model_columns, stored_v2_table UNMAPPED_COLUMNS = [ (Report, "label"), @@ -64,9 +64,12 @@ def test_the_table_keeps_an_unmapped_column_until_a_revision_drops_it( @pytest.mark.parametrize("model", [ReportRun, BudgetWindowRun]) def test_a_runs_trigger_keeps_the_type_users_run_records_share(model: type) -> None: trigger_type = model.model_fields["trigger"].sa_type + record_trigger_type = model_columns("user_report_run_associations").trigger.type assert isinstance(trigger_type, sa.Enum) - assert trigger_type.name == "v2_report_run_trigger" + assert isinstance(record_trigger_type, sa.Enum) + assert trigger_type.name == record_trigger_type.name == "v2_report_run_trigger" + assert trigger_type.enums == record_trigger_type.enums def test_the_reports_user_key_and_index_stay_with_the_column() -> None: