From 2467d9c802a60bbe98a6a10fe6633cb4aef5276f Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 4 Dec 2026 01:15:36 +0400 Subject: [PATCH 1/6] Test that saved reports stop storing and returning the reform copy (failing) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Saved reports no longer keep a copy of their reform's changes (`provisions`): pages read the report's policy and dynamic records. The tests expect: - `UserReportAssociation` to leave the `provisions` column unmapped, while the table keeps it, JSONB and nullable, until D1 · 10's revision drops it. - A save or an update to take the copy, which app v3 builds from before D1 · 5 still send, store none and leave a copy stored before untouched. - No read to return a copy: the owner's read and list, the shared read, the account export and the published report's saved-report fields. - OpenAPI to keep the request field, marked deprecated, and drop the response field. Rows saved before keep their copies; the tests store and read them through a class of their own that maps only the saved report's ID and the column. Co-Authored-By: Claude Opus 5.5 --- .../test_v2_user_identity_persistence.py | 7 +- tests/unit/v2/published_report_support.py | 4 +- tests/unit/v2/saved_report_reform_copies.py | 49 ++++++ tests/unit/v2/test_me_routes.py | 5 +- tests/unit/v2/test_models.py | 25 ++- tests/unit/v2/test_published_report_routes.py | 1 - .../unit/v2/test_published_report_service.py | 5 +- .../unit/v2/test_saved_report_reform_copy.py | 154 ++++++++++++++++++ tests/unit/v2/test_shared_report_routes.py | 1 - tests/unit/v2/test_user_account_service.py | 8 +- .../v2/test_user_simulation_report_routes.py | 56 ++----- tests/unit/v2/v2_schema_reading.py | 16 ++ 12 files changed, 270 insertions(+), 61 deletions(-) create mode 100644 tests/unit/v2/saved_report_reform_copies.py create mode 100644 tests/unit/v2/test_saved_report_reform_copy.py diff --git a/tests/integration/test_v2_user_identity_persistence.py b/tests/integration/test_v2_user_identity_persistence.py index d94646cea..eefb4090f 100644 --- a/tests/integration/test_v2_user_identity_persistence.py +++ b/tests/integration/test_v2_user_identity_persistence.py @@ -100,6 +100,7 @@ delete_public_api_rows, insert_public_api_rows, ) +from tests.unit.v2.saved_report_reform_copies import stored_reform_copy from tests.unit.v2.user_service_support import default_legacy_references if TYPE_CHECKING: @@ -663,10 +664,10 @@ def test_non_finite_numbers_never_reach_jsonb(sessions) -> None: } ) + # A saved report keeps no copy of its reform's changes: the copy is + # checked, then discarded. with sessions() as session: - row = session.get(UserReportAssociation, stored.id) - assert row is not None - assert row.provisions == [provision] + assert stored_reform_copy(session, stored.id) is None def test_report_budget_windows_persist_within_the_api_window_limit(sessions) -> None: diff --git a/tests/unit/v2/published_report_support.py b/tests/unit/v2/published_report_support.py index 10f4dd473..a2d950f36 100644 --- a/tests/unit/v2/published_report_support.py +++ b/tests/unit/v2/published_report_support.py @@ -30,6 +30,7 @@ from policyengine_api.services.v2.published_reports.services import ( V2PublishedReportService, ) +from tests.unit.v2.saved_report_reform_copies import store_reform_copy from tests.unit.v2.stored_report_support import report_read, report_run_read if TYPE_CHECKING: @@ -145,13 +146,14 @@ def store_saved_report( # noqa: PLR0913 # the session, then each column a test name=name, description="My own notes", source_note="From the chat", - provisions=PROVISIONS, user_policy_id=uuid4(), baseline_user_policy_id=baseline_user_policy_id, last_run_at=FINISHED_AT, ) session.add(saved) session.flush() + # A copy of the reform's changes, as saves before D1 · 5a stored. + store_reform_copy(session, saved.id, PROVISIONS) return SavedReportRows( principal=owner, user_id=user_id, diff --git a/tests/unit/v2/saved_report_reform_copies.py b/tests/unit/v2/saved_report_reform_copies.py new file mode 100644 index 000000000..4340d1b2c --- /dev/null +++ b/tests/unit/v2/saved_report_reform_copies.py @@ -0,0 +1,49 @@ +"""``user_report_associations.provisions``, the copy of a saved report's reform. + +Saved reports used to keep a copy of their reform's changes in this column. +Pages read the report's policy and dynamic records instead, so +``UserReportAssociation`` no longer maps the column, and D1 · 10's revision +drops it. Until then the rows saved before keep their copies, and tests store +and read the column through this class, on a registry of its own. No code +creates a table from it: the v2 schema creates the table. +""" + +# No ``from __future__ import annotations``: SQLAlchemy reads the class's +# ``Mapped`` annotations when it maps it, so their names stay imported at +# runtime. +from typing import Any +from uuid import UUID + +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql +from sqlalchemy.orm import Mapped, Session, mapped_column, registry + +saved_report_reform_copies = registry() + + +@saved_report_reform_copies.mapped +class SavedReportReformCopy: + """A saved report's ID and the copy of its reform's changes it holds, if any.""" + + __tablename__ = "user_report_associations" + + id: Mapped[UUID] = mapped_column(primary_key=True) + provisions: Mapped[Any] = mapped_column( + sa.JSON().with_variant(postgresql.JSONB(), "postgresql"), nullable=True + ) + + +def stored_reform_copy(session: Session, user_report_id: UUID) -> Any: + """Return the copy the saved report's row holds, or None.""" + row = session.get(SavedReportReformCopy, user_report_id) + assert row is not None + return row.provisions + + +def store_reform_copy(session: Session, user_report_id: UUID, copy: Any) -> None: + """Store ``copy`` in the saved report's row, as saves before D1 · 5a did.""" + session.execute( + sa.update(SavedReportReformCopy) + .where(SavedReportReformCopy.id == user_report_id) + .values(provisions=copy) + ) diff --git a/tests/unit/v2/test_me_routes.py b/tests/unit/v2/test_me_routes.py index f74fb2a7a..63af76ab2 100644 --- a/tests/unit/v2/test_me_routes.py +++ b/tests/unit/v2/test_me_routes.py @@ -325,8 +325,9 @@ def result(name: str, kwargs: dict): "ref": long_text, "confidence": None, } - assert body["reports"][0]["provisions"][0]["path"] == long_text - assert "retired_key" not in body["reports"][0]["provisions"][0] + assert body["reports"][0]["source_note"] == long_text + # A saved report returns no copy of its reform's changes. + assert "provisions" not in body["reports"][0] def test_unauthenticated_principals_reach_every_account_operation() -> None: diff --git a/tests/unit/v2/test_models.py b/tests/unit/v2/test_models.py index f8cec40b7..67761a132 100644 --- a/tests/unit/v2/test_models.py +++ b/tests/unit/v2/test_models.py @@ -41,6 +41,7 @@ ) from tests.fixtures.database_sessions import v2_schema_statements from tests.unit.v2.v2_schema_reading import ( + declared_column, declared_index, model_columns, stored_v2_schema, @@ -666,15 +667,31 @@ def test_saved_simulations_and_reports_name_stored_v2_rows() -> None: assert (run_key.target, run_key.ondelete) == (f"{run_table}.id", "RESTRICT") user_policy_key = reports.foreign_keys_of("user_policy_id")[0] assert user_policy_key.ondelete == "SET NULL" - for column_name in ("provisions", "validation"): - column_type = report_columns[column_name].type - postgres_type = column_type.dialect_impl(postgresql.dialect()) - assert isinstance(postgres_type, postgresql.JSONB) + validation_type = report_columns.validation.type + postgres_type = validation_type.dialect_impl(postgresql.dialect()) + assert isinstance(postgres_type, postgresql.JSONB) assert set(sa.inspect(UserSimulationAssociation).relationships.keys()) == {"user"} assert set(sa.inspect(UserReportAssociation).relationships.keys()) == {"user"} assert "user_associations" not in sa.inspect(Simulation).relationships +def test_saved_reports_keep_the_reform_copy_column_unmapped() -> None: + """The table keeps ``provisions``, the copy of the reform's changes, unmapped. + + Saved reports no longer keep the copy, so API v1 neither loads nor writes + the column, and a release of this code keeps serving while D1 · 10's + revision drops it. Until then the column stays as it was, JSONB on + PostgreSQL and nullable, and rows saved before keep their copies. + """ + assert "provisions" not in model_columns("user_report_associations") + assert stored_v2_table("user_report_associations").columns["provisions"].nullable + declared = declared_column(UserReportAssociation, "provisions") + assert declared is not None + assert isinstance( + declared.type.dialect_impl(postgresql.dialect()), postgresql.JSONB + ) + + def test_user_policy_records_v3_reform_fields() -> None: policies = model_columns("user_policies") diff --git a/tests/unit/v2/test_published_report_routes.py b/tests/unit/v2/test_published_report_routes.py index 53ca3980b..8962c14fb 100644 --- a/tests/unit/v2/test_published_report_routes.py +++ b/tests/unit/v2/test_published_report_routes.py @@ -483,7 +483,6 @@ def test_anyone_reads_a_published_report_without_its_owner() -> None: "show_past_versions": False, "saved_report": { "source_note": "From the chat", - "provisions": [{**PROVISIONS[0], "intervals": None}], "validation": None, "budget_window_years": None, "baseline_reform": {"name": "Plan A"}, diff --git a/tests/unit/v2/test_published_report_service.py b/tests/unit/v2/test_published_report_service.py index a55283a89..04aa6ec3c 100644 --- a/tests/unit/v2/test_published_report_service.py +++ b/tests/unit/v2/test_published_report_service.py @@ -49,7 +49,6 @@ ) from tests.fixtures.database_sessions import sqlite_v2_sessions from tests.unit.v2.published_report_support import ( - PROVISIONS, RecordingReportReader, author_principal, publication_body, @@ -407,7 +406,9 @@ def test_anyone_reads_the_page_with_its_newest_run_and_no_owner(sessions) -> Non assert page.content == published.content assert page.show_past_versions is False assert page.saved_report.source_note == "From the chat" - assert page.saved_report.provisions == PROVISIONS + # The saved report's row holds a copy of its reform's changes, which no + # read returns. + assert not hasattr(page.saved_report, "provisions") assert page.saved_report.budget_window_years is None assert page.saved_report.baseline_reform is not None assert page.saved_report.baseline_reform.name == "Plan A" diff --git a/tests/unit/v2/test_saved_report_reform_copy.py b/tests/unit/v2/test_saved_report_reform_copy.py new file mode 100644 index 000000000..d124161ba --- /dev/null +++ b/tests/unit/v2/test_saved_report_reform_copy.py @@ -0,0 +1,154 @@ +"""Saved reports keep no copy of their reform's changes (D1 · 5a). + +Report pages read the report's policy and dynamic records, so a saved report +stores no copy of the reform's changes (``provisions``) and no read returns +one. App v3 builds from before D1 · 5 still send the copy, so a save or an +update takes it and discards it. Rows saved before keep their copies, which +nothing reads, until D1 · 10's revision drops the column. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import pytest + +from policyengine_api.services.v2.user_accounts.database_session import ( + AccountDatabaseSession, +) +from policyengine_api.services.v2.user_accounts.services import V2AccountService +from policyengine_api.services.v2.user_reports.database_session import ( + UserReportDatabaseSession, +) +from policyengine_api.services.v2.user_reports.services import V2UserReportService +from policyengine_api.services.v2.user_reports.types import ( + UserReportCreateFields, + UserReportUpdateInput, +) +from tests.unit.v2.saved_report_reform_copies import ( + store_reform_copy, + stored_reform_copy, +) +from tests.unit.v2.user_service_support import ( + ALICE, + V2Store, + default_legacy_references, + v2_store, +) + +if TYPE_CHECKING: + from collections.abc import Iterator + from uuid import UUID + +REFORM_COPY = [ + { + "path": "gov.irs.credits.ctc.amount", + "breadcrumb": "Child Tax Credit amount", + "baseline_value": 2000, + "value": 3000, + } +] + + +@pytest.fixture +def store() -> Iterator[V2Store]: + with v2_store() as selected: + yield selected + + +def _reports(store: V2Store) -> V2UserReportService: + return V2UserReportService( + UserReportDatabaseSession(store.sessions), default_legacy_references() + ) + + +def _save_report(store: V2Store, **fields: object) -> UUID: + return ( + _reports(store) + .create_user_report( + principal=ALICE, + association_input=UserReportCreateFields.model_validate( + {"country_id": "us", "legacy_report_id": 615, **fields} + ), + ) + .id + ) + + +def _saved_report_holding_a_copy(store: V2Store) -> UUID: + """Save a report, then store a copy in its row, as saves before D1 · 5a did.""" + user_report_id = _save_report(store, name="CTC report") + with store.sessions.begin() as session: + store_reform_copy(session, user_report_id, REFORM_COPY) + return user_report_id + + +def _stored_copy(store: V2Store, user_report_id: UUID) -> object: + with store.sessions() as session: + return stored_reform_copy(session, user_report_id) + + +def test_a_save_takes_the_copy_and_stores_none(store: V2Store) -> None: + reports = _reports(store) + + saved = reports.create_user_report( + principal=ALICE, + association_input=UserReportCreateFields.model_validate( + {"country_id": "us", "legacy_report_id": 615, "provisions": REFORM_COPY} + ), + ) + + assert _stored_copy(store, saved.id) is None + assert not hasattr(saved, "provisions") + + +@pytest.mark.parametrize( + ("changes", "expected_name"), + [ + ({"provisions": [{**REFORM_COPY[0], "value": 4000}]}, "CTC report"), + ({"provisions": None}, "CTC report"), + ({"provisions": [], "name": "Renamed"}, "Renamed"), + ], +) +def test_an_update_takes_the_copy_and_leaves_the_stored_one( + store: V2Store, changes: dict[str, object], expected_name: str +) -> None: + user_report_id = _saved_report_holding_a_copy(store) + + updated = _reports(store).patch_user_report( + principal=ALICE, + country_id="us", + association_id=user_report_id, + association_input=UserReportUpdateInput.model_validate(changes), + ) + + assert updated.name == expected_name + assert not hasattr(updated, "provisions") + assert _stored_copy(store, user_report_id) == REFORM_COPY + + +def test_no_read_returns_a_stored_copy(store: V2Store) -> None: + user_report_id = _saved_report_holding_a_copy(store) + reports = _reports(store) + accounts = V2AccountService(AccountDatabaseSession(store.sessions)) + + reads = { + "owner's read": reports.get_user_report( + principal=ALICE, country_id="us", association_id=user_report_id + ), + "owner's list": reports.list_user_reports( + principal=ALICE, country_id="us" + ).items[0], + "shared read": reports.get_shared_user_report( + country_id="us", association_id=user_report_id + ), + "account export": accounts.export_account( + principal=ALICE, country_id="us" + ).reports[0], + } + + assert {name: read.id for name, read in reads.items()} == dict.fromkeys( + reads, user_report_id + ) + assert [name for name, read in reads.items() if hasattr(read, "provisions")] == [] + assert _stored_copy(store, user_report_id) == REFORM_COPY diff --git a/tests/unit/v2/test_shared_report_routes.py b/tests/unit/v2/test_shared_report_routes.py index e63789549..48f9ffbcc 100644 --- a/tests/unit/v2/test_shared_report_routes.py +++ b/tests/unit/v2/test_shared_report_routes.py @@ -82,7 +82,6 @@ def test_anyone_reads_a_saved_report_by_its_link_without_the_owner() -> None: "legacy_report_id": 615, "name": "CTC report", "source_note": "from chat", - "provisions": [{**PROVISIONS[0], "intervals": None}], "validation": None, "budget_window_years": 10, "baseline_reform": {"name": "Current plan"}, diff --git a/tests/unit/v2/test_user_account_service.py b/tests/unit/v2/test_user_account_service.py index 3e5dfd034..d6718170f 100644 --- a/tests/unit/v2/test_user_account_service.py +++ b/tests/unit/v2/test_user_account_service.py @@ -331,9 +331,8 @@ def test_report_policy_links_require_the_same_owner_and_survive_deletion( assert compared.baseline_user_policy_id == alice_policy.id assert report.user_policy_id == alice_policy.id - assert report.provisions == [ - {"path": "gov.x", "breadcrumb": "X", "baseline_value": 1, "value": 2} - ] + # The request's copy of the reform's changes is taken and never returned. + assert not hasattr(report, "provisions") policies.delete_user_policy( principal=ALICE, country_id="us", association_id=alice_policy.id ) @@ -383,11 +382,12 @@ def test_anyone_reads_a_saved_report_by_its_link_without_the_owner(store) -> Non "CTC report", "from chat", ) - assert shared.provisions == report.provisions assert shared.budget_window_years == 10 assert shared.baseline_reform == SharedBaselineReformRead(name="Current plan") for private_field in ("user_id", "user_policy_id", "baseline_user_policy_id"): assert not hasattr(shared, private_field) + # Nor does a shared read return a copy of the reform's changes. + assert not hasattr(shared, "provisions") with pytest.raises(UserReportNotFoundError): reports.get_shared_user_report(country_id="uk", association_id=report.id) diff --git a/tests/unit/v2/test_user_simulation_report_routes.py b/tests/unit/v2/test_user_simulation_report_routes.py index b848d43f7..797bd9d14 100644 --- a/tests/unit/v2/test_user_simulation_report_routes.py +++ b/tests/unit/v2/test_user_simulation_report_routes.py @@ -234,10 +234,13 @@ def test_report_routes_round_trip_v3_fields() -> None: assert item["report_id"] is None assert item["user_policy_id"] == str(USER_POLICY_ID) assert item["baseline_user_policy_id"] == str(BASELINE_USER_POLICY_ID) - assert item["provisions"] == PROVISIONS assert item["validation"] == VALIDATION assert item["budget_window_years"] == 10 assert item["last_run_at"] == "2026-02-01T12:00:00Z" + # A saved report keeps no copy of its reform's changes, so it returns + # none. Builds from before D1 · 5 still send one; the request takes it + # as before, and the service discards it. + assert "provisions" not in item fields = reports.calls[0][1]["association_input"] assert fields.provisions[0].intervals[0].value == 3000 assert fields.baseline_user_policy_id == BASELINE_USER_POLICY_ID @@ -335,23 +338,10 @@ def test_report_patch_accepts_only_contract_fields() -> None: } -def test_report_snapshots_echo_stored_keys_with_contract_nulls() -> None: - sparse_provision = { - "path": "gov.irs.credits.ctc.amount", - "breadcrumb": "Child Tax Credit amount", - "baseline_value": 2000, - "value": 3000, - "intervals": [ - {"start_date": "2026-01-01", "end_date": "2026-12-31", "value": 3000} - ], - } +def test_report_validation_echoes_stored_keys_with_contract_nulls() -> None: sparse_validation = {"matched_at": "2026-02-01T12:00:00Z", "map_model_version": "1"} reports = RecordingService( - lambda _name, _kwargs: replace( - _report_read(), - provisions=[sparse_provision], - validation=sparse_validation, - ) + lambda _name, _kwargs: replace(_report_read(), validation=sparse_validation) ) client, _flask_calls = user_route_client( v2_user_report_service_factory=lambda: reports @@ -361,10 +351,7 @@ def test_report_snapshots_echo_stored_keys_with_contract_nulls() -> None: "result" ]["item"] - # Nullable contract keys are present; the optional interval parameter - # stays absent rather than null. - assert item["provisions"] == [{**sparse_provision, "unit": None}] - assert "parameter" not in item["provisions"][0]["intervals"][0] + # Nullable contract keys are present. assert item["validation"] == { **sparse_validation, "calibration": None, @@ -372,26 +359,6 @@ def test_report_snapshots_echo_stored_keys_with_contract_nulls() -> None: } -def test_report_provisions_echo_growth_only_when_stored() -> None: - reports = RecordingService( - lambda _name, _kwargs: replace( - _report_read(), provisions=[*PROVISIONS, GROWING_PROVISION] - ) - ) - client, _flask_calls = user_route_client( - v2_user_report_service_factory=lambda: reports - ) - - item = client.get(f"/v2/user-reports/{REPORT_ASSOCIATION_ID}?country_id=us").json()[ - "result" - ]["item"] - - fixed_provision, growing_provision = item["provisions"] - assert growing_provision == {**GROWING_PROVISION, "intervals": None} - # The growth keys are optional, not nullable: a fixed value has none. - assert not any(key.startswith("growth") for key in fixed_provision) - - def test_openapi_types_report_and_policy_snapshots() -> None: client, _simulations, _reports = _clients() @@ -409,9 +376,12 @@ def property_refs(schema_name: str, field_name: str) -> set[str]: report_item = next(name for name in schemas if name.startswith("UserReportItem")) policy_item = next(name for name in schemas if name.startswith("UserPolicyItem")) - assert { - name.split("-")[0] for name in property_refs(report_item, "provisions") - } == {"ReportProvisionItem"} + # A saved report returns no copy of its reform's changes. Requests still + # take one, from builds before D1 · 5, and say that it is ignored. + assert "provisions" not in schemas[report_item]["properties"] + assert not any(name.startswith("ReportProvisionItem") for name in schemas) + for request in ("UserReportCreateRequest", "UserReportPatchRequest"): + assert schemas[request]["properties"]["provisions"]["deprecated"] is True assert { name.split("-")[0] for name in property_refs(report_item, "validation") } == {"ReportValidationItem"} diff --git a/tests/unit/v2/v2_schema_reading.py b/tests/unit/v2/v2_schema_reading.py index 6026ef88a..3617c1c8b 100644 --- a/tests/unit/v2/v2_schema_reading.py +++ b/tests/unit/v2/v2_schema_reading.py @@ -289,3 +289,19 @@ def declared_index(model: type[Any], index_name: str) -> sa.Index: for argument in model.__table_args__ if isinstance(argument, sa.Index) and argument.name == index_name ) + + +def declared_column(model: type[Any], column_name: str) -> sa.Column[Any] | None: + """Return the column called ``column_name`` in the model's ``__table_args__``. + + A model declares there a column its mapper leaves out (``exclude_properties``) + until a revision drops it. None when it declares no such column. + """ + return next( + ( + argument + for argument in model.__table_args__ + if isinstance(argument, sa.Column) and argument.name == column_name + ), + None, + ) From b9de873022b495ae8ec63f429b9e8754b95c44e9 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 4 Dec 2026 01:20:26 +0400 Subject: [PATCH 2/6] Stop storing and returning saved reports' copy of the reform's changes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Report pages read the report's policy and dynamic records, so a saved report keeps no copy of its reform's changes (`provisions`): - `UserReportAssociation` leaves the `provisions` column out of its mapper (`exclude_properties`), declared in `__table_args__` so the table keeps it. There is no revision: a release of this code keeps serving while D1 · 10's revision drops the column, and rows saved before keep their copies until then. - `/v2/user-reports` saves and updates still take `provisions`, checked as before, because app v3 builds from before D1 · 5 send it, and discard it; OpenAPI marks the field deprecated. An update that sends only that changes nothing. - The owner's read and list, `/v2/shared-reports/{id}`, `/v2/me/export` and published reports no longer return it. The test fixtures stop building read records with the field, the contract registry drops it from the response fields, and the generated contract files are regenerated. Co-Authored-By: Claude Opus 5.5 --- .../saved-reports-drop-reform-copy.removed.md | 1 + docs/engineering/migration-contracts.md | 14 +++--- docs/engineering/skills/alembic-migrations.md | 7 +-- docs/generated/migration_contracts.json | 7 --- docs/migration/stage-12a-user-login.md | 20 ++++---- .../data/v2/models/associations.py | 13 ++++- .../v2/published_reports/response_models.py | 2 - .../v2/published_reports/routes.py | 4 +- .../v2/user_reports/response_models.py | 47 ++----------------- .../v2/published_reports/transformations.py | 1 - .../services/v2/published_reports/types.py | 1 - .../v2/user_reports/transformations.py | 15 +++--- .../services/v2/user_reports/types.py | 41 ++++++++++------ tests/contract/registry.py | 3 -- tests/unit/v2/test_admin_user_routes.py | 1 - tests/unit/v2/test_me_routes.py | 9 ---- tests/unit/v2/test_published_report_routes.py | 2 - tests/unit/v2/test_shared_report_routes.py | 10 ---- .../v2/test_user_simulation_report_routes.py | 1 - 19 files changed, 71 insertions(+), 128 deletions(-) create mode 100644 changelog.d/saved-reports-drop-reform-copy.removed.md diff --git a/changelog.d/saved-reports-drop-reform-copy.removed.md b/changelog.d/saved-reports-drop-reform-copy.removed.md new file mode 100644 index 000000000..9315fdacc --- /dev/null +++ b/changelog.d/saved-reports-drop-reform-copy.removed.md @@ -0,0 +1 @@ +Saved reports no longer keep a copy of their reform's changes: `/v2/user-reports`, `/v2/shared-reports/{id}`, `/v2/me/export` and published reports no longer return `provisions`, and API v1 stops mapping `user_report_associations.provisions`, which a later revision drops. Saves and updates still accept `provisions` from older app builds and discard it. diff --git a/docs/engineering/migration-contracts.md b/docs/engineering/migration-contracts.md index 3884be55f..2ee65f063 100644 --- a/docs/engineering/migration-contracts.md +++ b/docs/engineering/migration-contracts.md @@ -169,17 +169,17 @@ Generated from `policyengine_api/migration_registry.py` and `tests/contract/regi | Method | Path | Status | Route group | Required headers | Stable response fields | | --- | --- | ---: | --- | --- | --- | -| `POST` | `/v2/user-reports?country_id=us` | 201 | `report` | `Authorization` | `status`, `message`, `result.item.id`, `result.item.country_id`, `result.item.user_id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.description`, `result.item.user_policy_id`, `result.item.baseline_user_policy_id`, `result.item.source_note`, `result.item.provisions`, `result.item.validation`, `result.item.budget_window_years`, `result.item.last_run_at`, `result.item.current_run_id`, `result.item.created_at`, `result.item.updated_at` | -| `GET` | `/v2/user-reports/{association_id}?country_id=us` | 200 | `report` | `Authorization` | `status`, `message`, `result.item.id`, `result.item.country_id`, `result.item.user_id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.description`, `result.item.user_policy_id`, `result.item.baseline_user_policy_id`, `result.item.source_note`, `result.item.provisions`, `result.item.validation`, `result.item.budget_window_years`, `result.item.last_run_at`, `result.item.current_run_id`, `result.item.created_at`, `result.item.updated_at` | +| `POST` | `/v2/user-reports?country_id=us` | 201 | `report` | `Authorization` | `status`, `message`, `result.item.id`, `result.item.country_id`, `result.item.user_id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.description`, `result.item.user_policy_id`, `result.item.baseline_user_policy_id`, `result.item.source_note`, `result.item.validation`, `result.item.budget_window_years`, `result.item.last_run_at`, `result.item.current_run_id`, `result.item.created_at`, `result.item.updated_at` | +| `GET` | `/v2/user-reports/{association_id}?country_id=us` | 200 | `report` | `Authorization` | `status`, `message`, `result.item.id`, `result.item.country_id`, `result.item.user_id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.description`, `result.item.user_policy_id`, `result.item.baseline_user_policy_id`, `result.item.source_note`, `result.item.validation`, `result.item.budget_window_years`, `result.item.last_run_at`, `result.item.current_run_id`, `result.item.created_at`, `result.item.updated_at` | | `GET` | `/v2/user-reports?country_id=us` | 200 | `report` | `Authorization` | `status`, `message`, `result.items`, `result.offset`, `result.limit`, `result.has_more` | -| `PATCH` | `/v2/user-reports/{association_id}?country_id=us` | 200 | `report` | `Authorization` | `status`, `message`, `result.item.id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.description`, `result.item.user_policy_id`, `result.item.baseline_user_policy_id`, `result.item.source_note`, `result.item.provisions`, `result.item.validation`, `result.item.budget_window_years`, `result.item.last_run_at`, `result.item.current_run_id`, `result.item.updated_at` | +| `PATCH` | `/v2/user-reports/{association_id}?country_id=us` | 200 | `report` | `Authorization` | `status`, `message`, `result.item.id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.description`, `result.item.user_policy_id`, `result.item.baseline_user_policy_id`, `result.item.source_note`, `result.item.validation`, `result.item.budget_window_years`, `result.item.last_run_at`, `result.item.current_run_id`, `result.item.updated_at` | | `DELETE` | `/v2/user-reports/{association_id}?country_id=us` | 204 | `report` | `Authorization` | | -| `POST` | `/v2/user-reports?country_id=us` | 201 | `report` | `PolicyEngine-Unauthenticated-User` | `status`, `message`, `result.item.id`, `result.item.country_id`, `result.item.user_id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.description`, `result.item.user_policy_id`, `result.item.baseline_user_policy_id`, `result.item.source_note`, `result.item.provisions`, `result.item.validation`, `result.item.budget_window_years`, `result.item.last_run_at`, `result.item.current_run_id`, `result.item.created_at`, `result.item.updated_at` | -| `GET` | `/v2/user-reports/{association_id}?country_id=us` | 200 | `report` | `PolicyEngine-Unauthenticated-User` | `status`, `message`, `result.item.id`, `result.item.country_id`, `result.item.user_id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.description`, `result.item.user_policy_id`, `result.item.baseline_user_policy_id`, `result.item.source_note`, `result.item.provisions`, `result.item.validation`, `result.item.budget_window_years`, `result.item.last_run_at`, `result.item.current_run_id`, `result.item.created_at`, `result.item.updated_at` | +| `POST` | `/v2/user-reports?country_id=us` | 201 | `report` | `PolicyEngine-Unauthenticated-User` | `status`, `message`, `result.item.id`, `result.item.country_id`, `result.item.user_id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.description`, `result.item.user_policy_id`, `result.item.baseline_user_policy_id`, `result.item.source_note`, `result.item.validation`, `result.item.budget_window_years`, `result.item.last_run_at`, `result.item.current_run_id`, `result.item.created_at`, `result.item.updated_at` | +| `GET` | `/v2/user-reports/{association_id}?country_id=us` | 200 | `report` | `PolicyEngine-Unauthenticated-User` | `status`, `message`, `result.item.id`, `result.item.country_id`, `result.item.user_id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.description`, `result.item.user_policy_id`, `result.item.baseline_user_policy_id`, `result.item.source_note`, `result.item.validation`, `result.item.budget_window_years`, `result.item.last_run_at`, `result.item.current_run_id`, `result.item.created_at`, `result.item.updated_at` | | `GET` | `/v2/user-reports?country_id=us` | 200 | `report` | `PolicyEngine-Unauthenticated-User` | `status`, `message`, `result.items`, `result.offset`, `result.limit`, `result.has_more` | -| `PATCH` | `/v2/user-reports/{association_id}?country_id=us` | 200 | `report` | `PolicyEngine-Unauthenticated-User` | `status`, `message`, `result.item.id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.description`, `result.item.user_policy_id`, `result.item.baseline_user_policy_id`, `result.item.source_note`, `result.item.provisions`, `result.item.validation`, `result.item.budget_window_years`, `result.item.last_run_at`, `result.item.current_run_id`, `result.item.updated_at` | +| `PATCH` | `/v2/user-reports/{association_id}?country_id=us` | 200 | `report` | `PolicyEngine-Unauthenticated-User` | `status`, `message`, `result.item.id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.description`, `result.item.user_policy_id`, `result.item.baseline_user_policy_id`, `result.item.source_note`, `result.item.validation`, `result.item.budget_window_years`, `result.item.last_run_at`, `result.item.current_run_id`, `result.item.updated_at` | | `DELETE` | `/v2/user-reports/{association_id}?country_id=us` | 204 | `report` | `PolicyEngine-Unauthenticated-User` | | -| `GET` | `/v2/shared-reports/{association_id}?country_id=us` | 200 | `report` | none | `status`, `message`, `result.item.id`, `result.item.country_id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.source_note`, `result.item.provisions`, `result.item.validation`, `result.item.budget_window_years`, `result.item.baseline_reform`, `result.item.last_run_at`, `result.item.current_run_id`, `result.item.created_at`, `result.item.updated_at` | +| `GET` | `/v2/shared-reports/{association_id}?country_id=us` | 200 | `report` | none | `status`, `message`, `result.item.id`, `result.item.country_id`, `result.item.report_id`, `result.item.legacy_report_id`, `result.item.name`, `result.item.source_note`, `result.item.validation`, `result.item.budget_window_years`, `result.item.baseline_reform`, `result.item.last_run_at`, `result.item.current_run_id`, `result.item.created_at`, `result.item.updated_at` | ### `user_account_v2` diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 90d30dd7b..2e3742e4a 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -310,10 +310,11 @@ and `refused(session, ...)`. 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`) until a revision drops it, as - `parameter_values.dynamic_id` was until revision `1c651058fac5`, and the + `parameter_values.dynamic_id` was until revision `1c651058fac5`, the per-user and cliff columns of `reports`, `report_runs` and - `budget_window_runs` were until revision `4e30076d4b9f`, has no statement - through the model: `update(Model).values(column=...)` raises + `budget_window_runs` were until revision `4e30076d4b9f`, and + `user_report_associations.provisions` is until D1 · 10's revision drops it, + 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 column-only class of a registry diff --git a/docs/generated/migration_contracts.json b/docs/generated/migration_contracts.json index 503b92e3b..b2b4c0902 100644 --- a/docs/generated/migration_contracts.json +++ b/docs/generated/migration_contracts.json @@ -1167,7 +1167,6 @@ "result.item.user_policy_id", "result.item.baseline_user_policy_id", "result.item.source_note", - "result.item.provisions", "result.item.validation", "result.item.budget_window_years", "result.item.last_run_at", @@ -1197,7 +1196,6 @@ "result.item.user_policy_id", "result.item.baseline_user_policy_id", "result.item.source_note", - "result.item.provisions", "result.item.validation", "result.item.budget_window_years", "result.item.last_run_at", @@ -1242,7 +1240,6 @@ "result.item.user_policy_id", "result.item.baseline_user_policy_id", "result.item.source_note", - "result.item.provisions", "result.item.validation", "result.item.budget_window_years", "result.item.last_run_at", @@ -1281,7 +1278,6 @@ "result.item.user_policy_id", "result.item.baseline_user_policy_id", "result.item.source_note", - "result.item.provisions", "result.item.validation", "result.item.budget_window_years", "result.item.last_run_at", @@ -1311,7 +1307,6 @@ "result.item.user_policy_id", "result.item.baseline_user_policy_id", "result.item.source_note", - "result.item.provisions", "result.item.validation", "result.item.budget_window_years", "result.item.last_run_at", @@ -1356,7 +1351,6 @@ "result.item.user_policy_id", "result.item.baseline_user_policy_id", "result.item.source_note", - "result.item.provisions", "result.item.validation", "result.item.budget_window_years", "result.item.last_run_at", @@ -1389,7 +1383,6 @@ "result.item.legacy_report_id", "result.item.name", "result.item.source_note", - "result.item.provisions", "result.item.validation", "result.item.budget_window_years", "result.item.baseline_reform", diff --git a/docs/migration/stage-12a-user-login.md b/docs/migration/stage-12a-user-login.md index 7d9f6e3be..b85aee8fe 100644 --- a/docs/migration/stage-12a-user-login.md +++ b/docs/migration/stage-12a-user-login.md @@ -540,7 +540,8 @@ Concurrency on Postgres: body-validation error is reported and before any service or database work, which bounds what can be stored. Caller fields are also bounded: `description` and `source_note` at 10,000 characters, report `provisions` at - 64 KiB serialized, and the report `validation` snapshot at 500 calibration + 64 KiB serialized (checked, then discarded, since D1 · 5a), and the report + `validation` snapshot at 500 calibration matches and 200 scorecard programs, with bounded strings (64 to 1,024 characters). `provenance` was already bounded (enumerated fields and a 2,048-character `ref`). Every user-route float and JSON value also rejects @@ -595,9 +596,8 @@ contract shared with `policyengine-app-v2`. The generated route inventory is in A saved report's ID is its shareable link, so `GET /v2/shared-reports/{id}` takes no credential and sits outside the authenticated user-report router. It never provisions a user. Its item is `{id, country_id, report_id, -legacy_report_id, name, source_note, provisions, validation, -budget_window_years, baseline_reform, last_run_at, current_run_id, -created_at, updated_at}`: +legacy_report_id, name, source_note, validation, budget_window_years, +baseline_reform, last_run_at, current_run_id, created_at, updated_at}`: - `user_id`, `user_policy_id`, and `baseline_user_policy_id` are left out; the owner and the owner's saved reforms stay private. @@ -609,9 +609,8 @@ created_at, updated_at}`: budget window's budget-window run, as `GET /v2/reports/{id}?run_id=` takes it. Only the owner sets it, saving the report or with `PATCH`; there is no re-run from a shared link. -- Anyone holding the ID can read the report's name, source note, and - provisions. There is no shared list or search, and the owner routes stay - owner-scoped. +- Anyone holding the ID can read the report's name and source note. There is + no shared list or search, and the owner routes stay owner-scoped. ### Published reports @@ -655,8 +654,8 @@ report the saved report names. Every route takes `country_id`. can't be published (409). An edit sends at least one field, none as null. - **The public read** answers the page's title (the saved report's name), summary, author IDs, tags and content; the saved report's source note, - provisions, validation, budget window and the name of the reform it was - compared with; the version read and the versions a reader may open, each + validation, budget window and the name of the reform it was compared with; + the version read and the versions a reader may open, each with its run's versions and when the page moved to it; and the report with that version's run, as `GET /v2/reports/{id}?run_id=` answers it, labelled with the title. The owner, the saved report's `description` (the @@ -780,7 +779,8 @@ from the final SQLModel metadata. It has no post-generation corrections. with, when not current law; the baseline's name is that reform's name, so no label is stored), `source_note`, `provisions jsonb` (each provision may carry optional `growth`, `growth_start`, `growth_base`, `growth_round_to` and - `growth_round` settings), `validation jsonb`, and `budget_window_years smallint` + `growth_round` settings; since D1 · 5a nothing reads or writes it, and D1 · 10 + drops it), `validation jsonb`, and `budget_window_years smallint` (the years of the budget window run with the report, from its year; NULL for none, otherwise 2 to 75 by `ck_user_report_associations_budget_window_years`, matching the economy route's limit). diff --git a/policyengine_api/data/v2/models/associations.py b/policyengine_api/data/v2/models/associations.py index 5db4d34a6..6922a7c72 100644 --- a/policyengine_api/data/v2/models/associations.py +++ b/policyengine_api/data/v2/models/associations.py @@ -14,7 +14,7 @@ """ from datetime import datetime -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any, ClassVar, Optional from uuid import UUID import sqlalchemy as sa @@ -314,10 +314,20 @@ class UserReportAssociation(TimestampedModel, table=True): report, not its kind: a budget window's years are report runs of the window, so only API v2's write check refuses one as its current run. Both are null for a saved report with no current run yet. + + A saved report keeps no copy of its reform's changes: its pages read the + report's policy and dynamic records. The table's ``provisions`` column, + where saved reports used to keep that copy, is left out of this model, so + API v1 neither loads nor writes it, and a release keeps working while a + later revision (D1 · 10) drops it. """ __tablename__ = "user_report_associations" + __mapper_args__: ClassVar[dict[str, Any]] = {"exclude_properties": ("provisions",)} __table_args__ = ( + # Kept in the table, unmapped, until a revision drops it: rows saved + # before keep their copy of the reform's changes, which nothing reads. + sa.Column("provisions", _jsonb_type()), sa.UniqueConstraint( "id", "country_id", @@ -408,7 +418,6 @@ class UserReportAssociation(TimestampedModel, table=True): index=True, ) source_note: str | None = Field(default=None, sa_type=sa.Text) - provisions: list[Any] | None = Field(default=None, sa_type=_jsonb_type()) validation: dict[str, Any] | None = Field(default=None, sa_type=_jsonb_type()) # Years in the budget window run with the report, from the report's year. budget_window_years: int | None = Field(default=None, sa_type=sa.SmallInteger) diff --git a/policyengine_api/fastapi_routes/v2/published_reports/response_models.py b/policyengine_api/fastapi_routes/v2/published_reports/response_models.py index b5c73dfea..8ba12d78a 100644 --- a/policyengine_api/fastapi_routes/v2/published_reports/response_models.py +++ b/policyengine_api/fastapi_routes/v2/published_reports/response_models.py @@ -18,7 +18,6 @@ report_item, ) from policyengine_api.fastapi_routes.v2.user_reports.response_models import ( - ReportProvisionItem, ReportValidationItem, SharedBaselineReformItem, ) @@ -133,7 +132,6 @@ class PublishedSavedReportItem(StrictPublishedReportAPIModel): """The saved report's presentation: as a shared report shows it, without IDs.""" source_note: str | None - provisions: list[ReportProvisionItem] | None validation: ReportValidationItem | None budget_window_years: int | None baseline_reform: SharedBaselineReformItem | None diff --git a/policyengine_api/fastapi_routes/v2/published_reports/routes.py b/policyengine_api/fastapi_routes/v2/published_reports/routes.py index f8b300e16..af7919cc1 100644 --- a/policyengine_api/fastapi_routes/v2/published_reports/routes.py +++ b/policyengine_api/fastapi_routes/v2/published_reports/routes.py @@ -419,8 +419,8 @@ def build_v2_published_report_router( "Needs no credential and never provisions a user. Returns the " "published report by its saved report's ID: its title (the saved " "report's name), summary, author IDs, tags and content; the saved " - "report's source note, provisions, validation, budget window and " - "the name of the reform it was compared with; the version read " + "report's source note, validation, budget window and the name of " + "the reform it was compared with; the version read " "and the versions a reader may open (every version while " "show_past_versions, else only the newest), each with its run's " "versions and when the page moved to it; and the report with that " diff --git a/policyengine_api/fastapi_routes/v2/user_reports/response_models.py b/policyengine_api/fastapi_routes/v2/user_reports/response_models.py index 3d2f68b58..0fd3090a8 100644 --- a/policyengine_api/fastapi_routes/v2/user_reports/response_models.py +++ b/policyengine_api/fastapi_routes/v2/user_reports/response_models.py @@ -6,7 +6,7 @@ from typing import TYPE_CHECKING, Generic, Literal, TypeVar from uuid import UUID -from pydantic import BaseModel, ConfigDict, Field, JsonValue +from pydantic import BaseModel, ConfigDict from policyengine_api.query_parameters import CountryId @@ -36,46 +36,6 @@ class StoredSnapshotItem(BaseModel): model_config = ConfigDict(extra="ignore", from_attributes=True) -class ReportProvisionIntervalItem(StoredSnapshotItem): - """A provision's value for the dates from ``start_date`` to ``end_date``.""" - - # The contract makes this key optional rather than nullable. - parameter: str | None = Field(default=None, exclude_if=lambda value: value is None) - start_date: str - end_date: str - value: JsonValue - - -class ReportProvisionItem(StoredSnapshotItem): - """One parameter the report's reform changes, with its baseline and reform values. - - ``intervals`` gives the reform's dated values when they vary over time. The - ``growth`` keys, present only when set, say how a value set from one year on - moves in later years and how grown values round. - """ - - path: str - breadcrumb: str - unit: str | None = None - baseline_value: JsonValue - value: JsonValue - intervals: list[ReportProvisionIntervalItem] | None = None - # Optional rather than nullable: absent unless the provision grows. - growth: str | None = Field(default=None, exclude_if=lambda value: value is None) - growth_start: int | None = Field( - default=None, exclude_if=lambda value: value is None - ) - growth_base: int | None = Field( - default=None, exclude_if=lambda value: value is None - ) - growth_round_to: float | None = Field( - default=None, exclude_if=lambda value: value is None - ) - growth_round: str | None = Field( - default=None, exclude_if=lambda value: value is None - ) - - class ReportCalibrationWorstItem(StoredSnapshotItem): """The calibration target that one match fits worst, with its relative error.""" @@ -127,6 +87,9 @@ class ReportValidationItem(StoredSnapshotItem): class UserReportItem(StrictUserReportAPIModel): """A report saved by a user, with the user's name, notes and saved presentation. + It has no copy of the reform's changes: pages read the report's policy and + dynamic records. + ``report_id`` is the detailed-save report it shows, and ``legacy_report_id`` the v1 report output; one of them is set, and only saved reports the production migration wrote hold both. ``user_policy_id`` is @@ -150,7 +113,6 @@ class UserReportItem(StrictUserReportAPIModel): user_policy_id: UUID | None baseline_user_policy_id: UUID | None source_note: str | None - provisions: list[ReportProvisionItem] | None validation: ReportValidationItem | None budget_window_years: int | None last_run_at: datetime | None @@ -185,7 +147,6 @@ class SharedUserReportItem(StrictUserReportAPIModel): legacy_report_id: int | None name: str | None source_note: str | None - provisions: list[ReportProvisionItem] | None validation: ReportValidationItem | None budget_window_years: int | None baseline_reform: SharedBaselineReformItem | None diff --git a/policyengine_api/services/v2/published_reports/transformations.py b/policyengine_api/services/v2/published_reports/transformations.py index 4a08397b4..675b7bba8 100644 --- a/policyengine_api/services/v2/published_reports/transformations.py +++ b/policyengine_api/services/v2/published_reports/transformations.py @@ -202,7 +202,6 @@ def published_saved_report_read( """Return the shared view's presentation fields a published report shows.""" return PublishedSavedReportRead( source_note=shared.source_note, - provisions=shared.provisions, validation=shared.validation, budget_window_years=shared.budget_window_years, baseline_reform=shared.baseline_reform, diff --git a/policyengine_api/services/v2/published_reports/types.py b/policyengine_api/services/v2/published_reports/types.py index 3df5fbb42..f494396cb 100644 --- a/policyengine_api/services/v2/published_reports/types.py +++ b/policyengine_api/services/v2/published_reports/types.py @@ -348,7 +348,6 @@ class PublishedSavedReportRead: """ source_note: str | None - provisions: list[StoredJSONObject] | None validation: StoredJSONObject | None budget_window_years: int | None baseline_reform: SharedBaselineReformRead | None diff --git a/policyengine_api/services/v2/user_reports/transformations.py b/policyengine_api/services/v2/user_reports/transformations.py index 7535cd054..317380511 100644 --- a/policyengine_api/services/v2/user_reports/transformations.py +++ b/policyengine_api/services/v2/user_reports/transformations.py @@ -12,7 +12,6 @@ UserReportPage, UserReportRead, UserReportUpdateInput, - stored_provisions, stored_validation, ) @@ -56,7 +55,6 @@ def user_report_read(association: UserReportAssociation) -> UserReportRead: user_policy_id=association.user_policy_id, baseline_user_policy_id=association.baseline_user_policy_id, source_note=association.source_note, - provisions=association.provisions, validation=association.validation, budget_window_years=association.budget_window_years, last_run_at=association.last_run_at, @@ -84,7 +82,6 @@ def shared_user_report_read( legacy_report_id=association.legacy_report_id, name=association.name, source_note=association.source_note, - provisions=association.provisions, validation=association.validation, budget_window_years=association.budget_window_years, baseline_reform=( @@ -122,14 +119,14 @@ def owned_user_report_input( *, user_id: UUID, ) -> UserReportCreationInput: - """Add the resolved owner and serialize the provision and validation snapshots. + """Add the resolved owner and serialize the validation snapshot. The current run is left out: the service stores it in the column for its - report's kind (``current_run_columns``). + report's kind (``current_run_columns``). So is a copy of the reform's + changes (``provisions``), which a saved report doesn't keep. """ return UserReportCreationInput( **fields.model_dump(exclude={"provisions", "validation", "current_run_id"}), - provisions=stored_provisions(fields.provisions), validation=stored_validation(fields.validation), user_id=user_id, ) @@ -141,14 +138,14 @@ def user_report_update_values( """Return explicitly supplied fields with JSON documents normalized. The current run is left out: the service stores it in the column for its - report's kind (``current_run_columns``). + report's kind (``current_run_columns``). So is a copy of the reform's + changes (``provisions``), which a saved report doesn't keep: a copy stored + before stays as it is. """ values = association_input.model_dump( exclude_unset=True, exclude={"provisions", "validation", "current_run_id"}, ) - if "provisions" in association_input.model_fields_set: - values["provisions"] = stored_provisions(association_input.provisions) if "validation" in association_input.model_fields_set: values["validation"] = stored_validation(association_input.validation) return values diff --git a/policyengine_api/services/v2/user_reports/types.py b/policyengine_api/services/v2/user_reports/types.py index e2ce7bec9..8c24dbbe2 100644 --- a/policyengine_api/services/v2/user_reports/types.py +++ b/policyengine_api/services/v2/user_reports/types.py @@ -51,7 +51,7 @@ class ReportProvisionInterval(StrictUserReportModel): """One dated value in a provision's schedule, from ``start_date`` to ``end_date``. Dates are ``YYYY-MM-DD`` strings and ``value`` is any finite JSON value. - ``parameter`` is optional, and is left out of the stored report when unset. + ``parameter`` is optional. """ # The contract makes this key optional rather than nullable. @@ -64,6 +64,10 @@ class ReportProvisionInterval(StrictUserReportModel): class ReportProvision(StrictUserReportModel): """One provision of the report's reform: a parameter's baseline and reform values. + App v3 builds from before D1 · 5 still send these as a copy of the reform's + changes. A saved report keeps no such copy, so a request's provisions are + checked and discarded, until D1 · 10 stops taking them. + ``path`` is the parameter path and ``breadcrumb`` its readable label, and ``intervals`` optionally gives a dated schedule. ``growth`` says how a value set from one year on moves in later years (``fixed``, ``current_law`` or an @@ -146,21 +150,18 @@ class ReportValidation(StrictUserReportModel): StoredJSONObject = dict[str, JsonValue] -def stored_provisions( - provisions: list[ReportProvision] | None, -) -> list[StoredJSONObject] | None: - """Serialize provisions exactly as supplied, enforcing the 64 KiB cap.""" +def require_provisions_within_cap(provisions: list[ReportProvision] | None) -> None: + """Refuse provisions over 64 KiB serialized, as saves always have.""" if provisions is None: - return None - stored = [ + return + supplied = [ provision.model_dump(mode="json", exclude_unset=True) for provision in provisions ] - encoded = json.dumps(stored, separators=(",", ":"), ensure_ascii=False) + encoded = json.dumps(supplied, separators=(",", ":"), ensure_ascii=False) if len(encoded.encode("utf-8")) > MAXIMUM_PROVISIONS_BYTES: msg = "provisions must not exceed 64 KiB when serialized" raise ValueError(msg) - return stored def stored_validation( @@ -176,14 +177,23 @@ class _ReportPresentationFields(StrictUserReportModel): name: AssociationName | None = None description: AssociationDescription | None = None source_note: ReportSourceNote | None = None - provisions: list[ReportProvision] | None = None + # App v3 builds from before D1 · 5 still send a copy of the reform's + # changes. It is checked as before and discarded; D1 · 10 removes it. + provisions: list[ReportProvision] | None = Field( + default=None, + description=( + "Ignored: a saved report keeps no copy of its reform's changes. " + "Accepted only from app builds that still send it." + ), + json_schema_extra={"deprecated": True}, + ) validation: ReportValidation | None = None budget_window_years: BudgetWindowYears | None = None last_run_at: AwareDatetime | None = None @model_validator(mode="after") def bound_provisions(self) -> _ReportPresentationFields: - stored_provisions(self.provisions) + require_provisions_within_cap(self.provisions) return self @@ -232,7 +242,6 @@ class UserReportCreationInput(StrictUserReportModel): user_policy_id: ResourceId | None = None baseline_user_policy_id: ResourceId | None = None source_note: str | None = None - provisions: list[StoredJSONObject] | None = None validation: StoredJSONObject | None = None budget_window_years: int | None = None last_run_at: AwareDatetime | None = None @@ -248,6 +257,8 @@ class UserReportUpdateInput(_ReportPresentationFields): v1 report output; neither can be cleared, and a saved report never comes to name both. The saved-reform links are cleared with null, and so is ``current_run_id``, the run of the detailed-save report the page shows. + ``provisions`` counts as a supplied field, so an update from an app build + that sends only that succeeds, but it changes nothing. """ report_id: ResourceId | None = None @@ -290,7 +301,9 @@ class UserReportRead: Unlike SharedUserReportRead, it includes the owner, the description and the owner's saved-reform links. ``current_run_id`` is the run of the - detailed-save report the saved report's page shows, or None. + detailed-save report the saved report's page shows, or None. It has no + copy of the reform's changes: pages read the report's policy and dynamic + records. """ id: UUID @@ -303,7 +316,6 @@ class UserReportRead: user_policy_id: UUID | None baseline_user_policy_id: UUID | None source_note: str | None - provisions: list[StoredJSONObject] | None validation: StoredJSONObject | None budget_window_years: int | None last_run_at: datetime | None @@ -334,7 +346,6 @@ class SharedUserReportRead: legacy_report_id: int | None name: str | None source_note: str | None - provisions: list[StoredJSONObject] | None validation: StoredJSONObject | None budget_window_years: int | None baseline_reform: SharedBaselineReformRead | None diff --git a/tests/contract/registry.py b/tests/contract/registry.py index 2df942a4a..801975704 100644 --- a/tests/contract/registry.py +++ b/tests/contract/registry.py @@ -469,7 +469,6 @@ class WorkflowContract: "user_policy_id", "baseline_user_policy_id", "source_note", - "provisions", "validation", "budget_window_years", "last_run_at", @@ -483,7 +482,6 @@ class WorkflowContract: "user_policy_id", "baseline_user_policy_id", "source_note", - "provisions", "validation", "budget_window_years", "last_run_at", @@ -505,7 +503,6 @@ class WorkflowContract: "result.item.legacy_report_id", "result.item.name", "result.item.source_note", - "result.item.provisions", "result.item.validation", "result.item.budget_window_years", "result.item.baseline_reform", diff --git a/tests/unit/v2/test_admin_user_routes.py b/tests/unit/v2/test_admin_user_routes.py index 78abf6750..8b830a7ac 100644 --- a/tests/unit/v2/test_admin_user_routes.py +++ b/tests/unit/v2/test_admin_user_routes.py @@ -173,7 +173,6 @@ def _saved_items() -> AccountExport: user_policy_id=SAVED_POLICY_ID, baseline_user_policy_id=None, source_note=None, - provisions=None, validation=None, budget_window_years=None, last_run_at=None, diff --git a/tests/unit/v2/test_me_routes.py b/tests/unit/v2/test_me_routes.py index 63af76ab2..a230d45e0 100644 --- a/tests/unit/v2/test_me_routes.py +++ b/tests/unit/v2/test_me_routes.py @@ -285,15 +285,6 @@ def test_export_serializes_stored_rows_outside_current_input_bounds() -> None: user_policy_id=None, baseline_user_policy_id=None, source_note=long_text, - provisions=[ - { - "path": long_text, - "breadcrumb": "b", - "baseline_value": 1, - "value": 2, - "retired_key": True, - } - ], validation={"matched_at": long_text, "map_model_version": "1"}, budget_window_years=None, last_run_at=None, diff --git a/tests/unit/v2/test_published_report_routes.py b/tests/unit/v2/test_published_report_routes.py index 8962c14fb..e5c32ebc4 100644 --- a/tests/unit/v2/test_published_report_routes.py +++ b/tests/unit/v2/test_published_report_routes.py @@ -54,7 +54,6 @@ UserTypeBelowMinimumError, ) from tests.unit.v2.published_report_support import ( - PROVISIONS, publication_body, without_run, ) @@ -145,7 +144,6 @@ def _published_report() -> PublishedReportRead: show_past_versions=False, saved_report=PublishedSavedReportRead( source_note="From the chat", - provisions=PROVISIONS, validation=None, budget_window_years=None, baseline_reform=SharedBaselineReformRead(name="Plan A"), diff --git a/tests/unit/v2/test_shared_report_routes.py b/tests/unit/v2/test_shared_report_routes.py index 48f9ffbcc..6f6213a03 100644 --- a/tests/unit/v2/test_shared_report_routes.py +++ b/tests/unit/v2/test_shared_report_routes.py @@ -24,15 +24,6 @@ REPORT_ASSOCIATION_ID = UUID("00000000-0000-0000-0000-000000000063") SHARED_PATH = f"/v2/shared-reports/{REPORT_ASSOCIATION_ID}" LAST_RUN_AT = datetime(2026, 2, 1, 12, tzinfo=UTC) -PROVISIONS = [ - { - "path": "gov.irs.credits.ctc.amount", - "breadcrumb": "Child Tax Credit amount", - "unit": "currency-USD", - "baseline_value": 2000, - "value": 3000, - } -] def _shared_report_read() -> SharedUserReportRead: @@ -43,7 +34,6 @@ def _shared_report_read() -> SharedUserReportRead: legacy_report_id=615, name="CTC report", source_note="from chat", - provisions=PROVISIONS, validation=None, budget_window_years=10, baseline_reform=SharedBaselineReformRead(name="Current plan"), diff --git a/tests/unit/v2/test_user_simulation_report_routes.py b/tests/unit/v2/test_user_simulation_report_routes.py index 797bd9d14..de2d698e4 100644 --- a/tests/unit/v2/test_user_simulation_report_routes.py +++ b/tests/unit/v2/test_user_simulation_report_routes.py @@ -116,7 +116,6 @@ def _report_read() -> UserReportRead: user_policy_id=USER_POLICY_ID, baseline_user_policy_id=BASELINE_USER_POLICY_ID, source_note="from chat", - provisions=PROVISIONS, validation=VALIDATION, budget_window_years=10, last_run_at=LAST_RUN_AT, From 73836ce37fec984d87cfc1ca6b1870ae59463e75 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 4 Dec 2026 01:45:49 +0400 Subject: [PATCH 3/6] Declare the unmapped provisions column as an ORM-only rule exception MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit UserReportAssociation declares user_report_associations.provisions as a Core column in __table_args__, which the api.data.orm-only rule reports. The ORM has no form for a column a table keeps but its class doesn't map, so the rule registry names it as a no-orm-form exception until D1 · 10's revision drops the column. The Alembic guide now says such a column needs the exception, and the update docstring, the request field's OpenAPI description and the changelog fragment describe what the code does. Co-Authored-By: Claude Opus 5.5 --- .../saved-reports-drop-reform-copy.removed.md | 2 +- docs/engineering/skills/alembic-migrations.md | 31 ++++++++++++++----- docs/generated/rules.md | 1 + .../services/v2/user_reports/types.py | 6 ++-- rules/registry.toml | 7 +++++ tests/unit/v2/v2_schema_reading.py | 5 +-- 6 files changed, 39 insertions(+), 13 deletions(-) diff --git a/changelog.d/saved-reports-drop-reform-copy.removed.md b/changelog.d/saved-reports-drop-reform-copy.removed.md index 9315fdacc..b2a6778d8 100644 --- a/changelog.d/saved-reports-drop-reform-copy.removed.md +++ b/changelog.d/saved-reports-drop-reform-copy.removed.md @@ -1 +1 @@ -Saved reports no longer keep a copy of their reform's changes: `/v2/user-reports`, `/v2/shared-reports/{id}`, `/v2/me/export` and published reports no longer return `provisions`, and API v1 stops mapping `user_report_associations.provisions`, which a later revision drops. Saves and updates still accept `provisions` from older app builds and discard it. +Saved reports no longer store a copy of their reform's changes: `/v2/user-reports`, `/v2/shared-reports/{id}`, `/v2/me/export`, `/v2/admin/users/{user_id}/saved-items` and published reports no longer return `provisions`, and API v1 stops mapping `user_report_associations.provisions`. Rows saved before keep their copies, which nothing reads, until a later revision drops the column. Saves and updates still accept `provisions` from older app builds and discard it. diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 2e3742e4a..2f236b2c8 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -316,11 +316,17 @@ and `refused(session, ...)`. `user_report_associations.provisions` is until D1 · 10's revision drops it, 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 column-only class of a registry - of its own, of the kind `tests.integration.privilege_statements` holds, 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`. + is the table's Core column, which the rule rules out even in a `select`. + The model declares the column as a Core `sa.Column` in `__table_args__`, so + the v2 metadata keeps it and Alembic finds no difference. The rule's check + reports that declaration, so it takes a `no-orm-form` exception (see + [ORM-only exceptions](#orm-only-exceptions)), which the revision that drops + the column removes. A test that sets or selects one maps it on a column-only + class of a registry of its own, of the kind + `tests.integration.privilege_statements` holds, and reads its declaration + from SQLite's copy of the schema (`StoredTable.columns` in + `tests.unit.v2.v2_schema_reading`), from the database's `Inspector`, or, for + its PostgreSQL type, from the model's `__table_args__` (`declared_column`). - **Postgres functions**: `func`, as in `session.execute(select(func.current_database(), func.current_user()))`, `func.pg_backend_pid()` and `func.has_table_privilege(...)`. @@ -395,9 +401,10 @@ and `REVOKE`, `ALTER DEFAULT PRIVILEGES`, `CREATE`, `ALTER` and `DROP ROLE` (with `DROP OWNED BY`), `CREATE VIEW` and `CREATE MATERIALIZED VIEW`, `DROP TABLE`, `TRUNCATE`, `COPY`, `EXPLAIN`, `ANALYZE`, Alembic's need for a Connection, and connection settings no SQL function sets, such as SQLite's -`foreign_keys` and `BEGIN IMMEDIATE`. Roles and Postgres settings inside a -transaction need none: `set_config` sets them. Keep the entries in as few -modules as possible. The entries: +`foreign_keys` and `BEGIN IMMEDIATE`. So does the Core declaration of a +column a mapper leaves out until a revision drops it. Roles and Postgres +settings inside a transaction need none: `set_config` sets them. Keep the +entries in as few modules as possible. The entries: 1. **Alembic environments and revisions** (`migration-revision`), `migrations/**/*.py`. The environments run Alembic's migration context on @@ -453,6 +460,14 @@ modules as possible. The entries: `CREATE VIEW` and `CREATE MATERIALIZED VIEW` in `create_view`, which SQLAlchemy has no construct for. The reconciliation's catalog reads are tested on those grants. +9. **A column a mapper leaves out** (`no-orm-form`), in + `policyengine_api/data/v2/models/associations.py`'s + `UserReportAssociation`: `user_report_associations.provisions`, a copy of + a saved report's reform changes that nothing reads or writes. The ORM has + no form for a column a table keeps but its class doesn't map, so the class + declares it as a Core column in `__table_args__` (see "Columns a mapper + leaves out" above). D1 · 10's revision drops the column and removes this + entry. A new exception is a rule change: add a `[[rule.exception]]` entry to the rule in `rules/registry.toml`, explain here why the ORM can't express the diff --git a/docs/generated/rules.md b/docs/generated/rules.md index fd65f8141..bb145e288 100644 --- a/docs/generated/rules.md +++ b/docs/generated/rules.md @@ -76,6 +76,7 @@ Every rule that governs `policyengine-api` is listed here with how it is enforce - `api.data.orm-only`: exception for `policyengine_api/data/v2/catalog/publication_staging.py` (`session.connection()` in `copy_rows`) allowed as a no-orm-form (Catalog publication streams rows with COPY ... FROM STDIN through the psycopg connection beneath the Connection the publishing Session holds, in its transaction.) - `api.data.orm-only`: exception for `policyengine_api/data/v2/catalog/publication_staging.py` (`session.connection()` in `create_staging_tables`) allowed as a no-orm-form (Catalog publication creates its TEMPORARY staging tables with MetaData.create_all, which takes a Connection: the Connection the publishing Session holds, in its transaction.) - `api.data.orm-only`: exception for `policyengine_api/data/v2/catalog/publication_statistics.py` (`sa.text(f'ANALYZE {tables}')` in `analyze_catalog_tables`) allowed as a no-orm-form (ANALYZE has no ORM form. After a publication commits, one ANALYZE refreshes the planner statistics of the catalog tables it wrote.) +- `api.data.orm-only`: exception for `policyengine_api/data/v2/models/associations.py` (`sa.Column('provisions', ...)` in `UserReportAssociation`) allowed as a no-orm-form (A saved report keeps no copy of its reform's changes, so UserReportAssociation leaves user_report_associations.provisions out of its mapper (exclude_properties), and no statement reads or writes it. The ORM has no form for a column a table keeps but its class doesn't map, so the class declares it as a Core column in __table_args__, which keeps it in the v2 metadata: Alembic then finds no difference from the database, and the test databases built from the metadata keep it. D1 · 10's revision drops the column, and with it this entry.) - `api.data.orm-only`: exception for `policyengine_api/data/v2/pending_revisions.py` (`session.connection()` in `v2_revision_is_pending`) allowed as a no-orm-form (Alembic's MigrationContext reads the database's current heads from its version table through a Connection. The migration qualification commands give it the Connection their Session holds, so the read runs inside the Session's READ ONLY transaction.) - `api.data.orm-only`: exception for `policyengine_api/data/v2/privilege_reconciliation.py` (`text(f'CREATE ROLE {quote(safe_identifier(role))} NOLOGIN')` in `create_missing_roles`) allowed as a no-orm-form (CREATE ROLE has no SQLAlchemy form. reconcile_v2_privileges.py apply --create-missing-roles creates each missing managed role as NOLOGIN, only in the disposable test database, in the reconciliation's one transaction. The role name is checked by safe_identifier and quoted by the session's dialect.) - `api.data.orm-only`: exception for `policyengine_api/data/v2/privilege_reconciliation.py` (`text(statement)` in `apply_declared_privileges`) allowed as a no-orm-form (GRANT and REVOKE have no SQLAlchemy form. apply runs the REVOKEs and GRANTs that privilege_plans' revoke_statements and grant_statements build from the declared privileges, with identifiers checked by safe_identifier and quoted by the session's dialect, in the reconciliation's one transaction.) diff --git a/policyengine_api/services/v2/user_reports/types.py b/policyengine_api/services/v2/user_reports/types.py index 8c24dbbe2..c3563e0db 100644 --- a/policyengine_api/services/v2/user_reports/types.py +++ b/policyengine_api/services/v2/user_reports/types.py @@ -183,7 +183,8 @@ class _ReportPresentationFields(StrictUserReportModel): default=None, description=( "Ignored: a saved report keeps no copy of its reform's changes. " - "Accepted only from app builds that still send it." + "Older app builds still send it, so a request may include it, " + "and it is checked and discarded." ), json_schema_extra={"deprecated": True}, ) @@ -258,7 +259,8 @@ class UserReportUpdateInput(_ReportPresentationFields): to name both. The saved-reform links are cleared with null, and so is ``current_run_id``, the run of the detailed-save report the page shows. ``provisions`` counts as a supplied field, so an update from an app build - that sends only that succeeds, but it changes nothing. + that sends only that succeeds, but it changes no stored field except + ``updated_at``, as every update sets. """ report_id: ResourceId | None = None diff --git a/rules/registry.toml b/rules/registry.toml index efa174f99..cc742d99b 100644 --- a/rules/registry.toml +++ b/rules/registry.toml @@ -749,6 +749,13 @@ function = "acquire_user_type_change_lock" category = "no-orm-form" reason = "Reads the dialect's name, to skip PostgreSQL's advisory lock on the SQLite test databases, which have none. It runs no statement on the engine." +[[rule.exception]] +path = "policyengine_api/data/v2/models/associations.py" +match = "sa.Column('provisions', ...)" +function = "UserReportAssociation" +category = "no-orm-form" +reason = "A saved report keeps no copy of its reform's changes, so UserReportAssociation leaves user_report_associations.provisions out of its mapper (exclude_properties), and no statement reads or writes it. The ORM has no form for a column a table keeps but its class doesn't map, so the class declares it as a Core column in __table_args__, which keeps it in the v2 metadata: Alembic then finds no difference from the database, and the test databases built from the metadata keep it. D1 · 10's revision drops the column, and with it this entry." + [[rule.exception]] path = "tests/fixtures/database_sessions.py" match = "sqlite_connection.execute('PRAGMA foreign_keys = ON')" diff --git a/tests/unit/v2/v2_schema_reading.py b/tests/unit/v2/v2_schema_reading.py index 3617c1c8b..e8e97c523 100644 --- a/tests/unit/v2/v2_schema_reading.py +++ b/tests/unit/v2/v2_schema_reading.py @@ -11,8 +11,9 @@ rule, check condition and index the models declare. Its columns also hold any a mapper leaves out (``exclude_properties``) until a revision drops it. -What only PostgreSQL receives, such as a partial index's PostgreSQL condition, -is read from the model's ``__table_args__`` (``declared_index``). +What only PostgreSQL receives is read from the model's ``__table_args__``: a +partial index's PostgreSQL condition (``declared_index``), and the PostgreSQL +type of a column the mapper leaves out (``declared_column``). """ from __future__ import annotations From 040d430234395b0dd2fc4f628b39a563862eb07b Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 4 Dec 2026 02:06:09 +0400 Subject: [PATCH 4/6] Describe how statements treat a column a mapper leaves out The Alembic guide said an update through the model naming such a column raises AttributeError. A Session refuses it under its default synchronization but writes the column with synchronize_session=False, so the guide now says that what keeps the column unwritten is that no code names it. The simulation-role privilege tests' notes that no model leaves a column out now speak only of the simulation tables, and the request field's OpenAPI description says the value is checked, then discarded. Co-Authored-By: Claude Opus 5.5 --- docs/engineering/skills/alembic-migrations.md | 9 ++++++--- policyengine_api/services/v2/user_reports/types.py | 6 +++--- tests/integration/test_v2_simulation_role_privileges.py | 8 ++++---- 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 2f236b2c8..3f1af588f 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -314,9 +314,12 @@ and `refused(session, ...)`. per-user and cliff columns of `reports`, `report_runs` and `budget_window_runs` were until revision `4e30076d4b9f`, and `user_report_associations.provisions` is until D1 · 10's revision drops it, - 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`. + has no attribute on the model: 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 Session running `update(Model).values(column=...)` refuses it + with `InvalidRequestError` under its default synchronization, but writes the + column with `synchronize_session=False`, so what keeps the column unwritten + is that no code names it. The model declares the column as a Core `sa.Column` in `__table_args__`, so the v2 metadata keeps it and Alembic finds no difference. The rule's check reports that declaration, so it takes a `no-orm-form` exception (see diff --git a/policyengine_api/services/v2/user_reports/types.py b/policyengine_api/services/v2/user_reports/types.py index c3563e0db..21e3f7b17 100644 --- a/policyengine_api/services/v2/user_reports/types.py +++ b/policyengine_api/services/v2/user_reports/types.py @@ -182,9 +182,9 @@ class _ReportPresentationFields(StrictUserReportModel): provisions: list[ReportProvision] | None = Field( default=None, description=( - "Ignored: a saved report keeps no copy of its reform's changes. " - "Older app builds still send it, so a request may include it, " - "and it is checked and discarded." + "Checked, then discarded: a saved report keeps no copy of its " + "reform's changes. Older app builds still send it, so a request " + "may include it." ), json_schema_extra={"deprecated": True}, ) diff --git a/tests/integration/test_v2_simulation_role_privileges.py b/tests/integration/test_v2_simulation_role_privileges.py index 5b7df5d61..fd00e586e 100644 --- a/tests/integration/test_v2_simulation_role_privileges.py +++ b/tests/integration/test_v2_simulation_role_privileges.py @@ -19,9 +19,9 @@ 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 -(``exclude_properties``) would have no statement through the model, so its -writes and refusals would go through a class that maps it; since revision -``4e30076d4b9f`` no model leaves a column out. +(``exclude_properties``) has no attribute on the model, so its writes and +refusals would go through a class that maps it; since revision +``4e30076d4b9f`` no model of the simulation tables leaves a column out. """ from __future__ import annotations @@ -613,7 +613,7 @@ def test_the_public_api_reads_runs_and_results_but_writes_neither( # The class that maps the columns each model's mapper leaves out. Since -# revision 4e30076d4b9f no model leaves a column out. +# revision 4e30076d4b9f no model of the simulation tables leaves a column out. UNMAPPED_COLUMN_CLASSES: dict[type[Any], type[Any]] = {} From 5882f4b52cb2b188ecab78cc4282b21e29ee64fa Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 4 Dec 2026 02:22:05 +0400 Subject: [PATCH 5/6] Test that provisions stays a SQLModel field left out of the mapper (failing) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review round 3: the decision of 2026-11-24 keeps a column awaiting removal as a SQLModel field that exclude_properties leaves out of the mapper, not as a Core column in __table_args__. In that form no update or insert through UserReportAssociation can name provisions, whatever its synchronization; the model test reads the column's PostgreSQL type from the field; and DIRECT_SQLALCHEMY_EXCEPTIONS lists columns_left_out_of_the_mapper again, as it did for C1 · 51a. All four runs fail on assertions against the Core-column form. Co-Authored-By: Claude Opus 5.5 --- tests/unit/v2/test_model_persistence.py | 1 + tests/unit/v2/test_models.py | 8 +-- .../unit/v2/test_saved_report_reform_copy.py | 52 ++++++++++++++++++- 3 files changed, 56 insertions(+), 5 deletions(-) diff --git a/tests/unit/v2/test_model_persistence.py b/tests/unit/v2/test_model_persistence.py index 1ab9cec8f..01b432e0e 100644 --- a/tests/unit/v2/test_model_persistence.py +++ b/tests/unit/v2/test_model_persistence.py @@ -94,6 +94,7 @@ def test_direct_sqlalchemy_categories_are_complete_and_documented() -> None: "named_constraints_and_indexes", "ambiguous_foreign_key_relationships", "transaction_conflict_recovery", + "columns_left_out_of_the_mapper", } assert all(DIRECT_SQLALCHEMY_EXCEPTIONS.values()) diff --git a/tests/unit/v2/test_models.py b/tests/unit/v2/test_models.py index 67761a132..81ce9c257 100644 --- a/tests/unit/v2/test_models.py +++ b/tests/unit/v2/test_models.py @@ -41,7 +41,6 @@ ) from tests.fixtures.database_sessions import v2_schema_statements from tests.unit.v2.v2_schema_reading import ( - declared_column, declared_index, model_columns, stored_v2_schema, @@ -685,10 +684,11 @@ def test_saved_reports_keep_the_reform_copy_column_unmapped() -> None: """ assert "provisions" not in model_columns("user_report_associations") assert stored_v2_table("user_report_associations").columns["provisions"].nullable - declared = declared_column(UserReportAssociation, "provisions") - assert declared is not None + # The column stays a SQLModel field, which declares its PostgreSQL type. + field = UserReportAssociation.model_fields.get("provisions") + assert field is not None assert isinstance( - declared.type.dialect_impl(postgresql.dialect()), postgresql.JSONB + field.sa_type.dialect_impl(postgresql.dialect()), postgresql.JSONB ) diff --git a/tests/unit/v2/test_saved_report_reform_copy.py b/tests/unit/v2/test_saved_report_reform_copy.py index d124161ba..09e84da86 100644 --- a/tests/unit/v2/test_saved_report_reform_copy.py +++ b/tests/unit/v2/test_saved_report_reform_copy.py @@ -10,9 +10,12 @@ from __future__ import annotations from typing import TYPE_CHECKING +from uuid import uuid4 import pytest +import sqlalchemy as sa +from policyengine_api.data.v2.models import UserReportAssociation from policyengine_api.services.v2.user_accounts.database_session import ( AccountDatabaseSession, ) @@ -37,9 +40,11 @@ ) if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterator from uuid import UUID + from sqlalchemy.sql.dml import Insert, Update + REFORM_COPY = [ { "path": "gov.irs.credits.ctc.amount", @@ -152,3 +157,48 @@ def test_no_read_returns_a_stored_copy(store: V2Store) -> None: ) assert [name for name, read in reads.items() if hasattr(read, "provisions")] == [] assert _stored_copy(store, user_report_id) == REFORM_COPY + + +def _update_naming_the_copy(user_report_id: UUID, owner_id: UUID) -> Update: + del owner_id + return ( + sa.update(UserReportAssociation) + .where(UserReportAssociation.id == user_report_id) + .values(provisions=REFORM_COPY) + .execution_options(synchronize_session=False) + ) + + +def _insert_naming_the_copy(user_report_id: UUID, owner_id: UUID) -> Insert: + del user_report_id + return sa.insert(UserReportAssociation).values( + id=uuid4(), + country_id="us", + user_id=owner_id, + legacy_report_id=615, + provisions=REFORM_COPY, + ) + + +@pytest.mark.parametrize( + "statement_naming_the_copy", + [_update_naming_the_copy, _insert_naming_the_copy], + ids=["update", "insert"], +) +def test_no_statement_through_the_model_writes_a_copy( + store: V2Store, statement_naming_the_copy: Callable[[UUID, UUID], Update | Insert] +) -> None: + """No update or insert through the model can name ``provisions``. + + Its mapper leaves the column out, so a statement naming it fails before it + reaches the database, whatever its synchronization. Only the column-only + test class reaches the copies that rows saved before still hold. + """ + user_report_id = _save_report(store, name="CTC report") + + with store.sessions() as session: + saved = session.get(UserReportAssociation, user_report_id) + assert saved is not None + owner_id = saved.user_id + with pytest.raises(AttributeError): + session.execute(statement_naming_the_copy(user_report_id, owner_id)) From 400102be6abe058b3a0f1504d203de1fe16dacc3 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 4 Dec 2026 02:24:02 +0400 Subject: [PATCH 6/6] Keep provisions as a SQLModel field left out of the mapper MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review round 3: the decision of 2026-11-24 (93e3be3b) and C1 · 51a keep a column awaiting removal as a SQLModel field that exclude_properties leaves out of the mapper. UserReportAssociation now does so for provisions, with the declaration it had before, instead of a Core column in __table_args__. So no update or insert through the model can name the column, the rule api.data.orm-only needs no exception (removed from the registry, and rules.md regenerated), and DIRECT_SQLALCHEMY_EXCEPTIONS lists columns_left_out_of_the_mapper again. The Alembic guide's "Columns a mapper leaves out" is as before, naming this column and that inserts are refused too; the schema-reading helper loses declared_column; and the simulation-role privilege tests' docstring says again that such a column has no statement through the model. Co-Authored-By: Claude Opus 5.5 --- docs/engineering/skills/alembic-migrations.md | 39 ++++++------------- docs/generated/rules.md | 1 - .../data/v2/models/associations.py | 16 +++++--- policyengine_api/data/v2/models/base.py | 6 +++ rules/registry.toml | 7 ---- .../test_v2_simulation_role_privileges.py | 4 +- tests/unit/v2/v2_schema_reading.py | 21 +--------- 7 files changed, 31 insertions(+), 63 deletions(-) diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 3f1af588f..93f9ff764 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -314,22 +314,14 @@ and `refused(session, ...)`. per-user and cliff columns of `reports`, `report_runs` and `budget_window_runs` were until revision `4e30076d4b9f`, and `user_report_associations.provisions` is until D1 · 10's revision drops it, - has no attribute on the model: 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 Session running `update(Model).values(column=...)` refuses it - with `InvalidRequestError` under its default synchronization, but writes the - column with `synchronize_session=False`, so what keeps the column unwritten - is that no code names it. - The model declares the column as a Core `sa.Column` in `__table_args__`, so - the v2 metadata keeps it and Alembic finds no difference. The rule's check - reports that declaration, so it takes a `no-orm-form` exception (see - [ORM-only exceptions](#orm-only-exceptions)), which the revision that drops - the column removes. A test that sets or selects one maps it on a column-only - class of a registry of its own, of the kind - `tests.integration.privilege_statements` holds, and reads its declaration - from SQLite's copy of the schema (`StoredTable.columns` in - `tests.unit.v2.v2_schema_reading`), from the database's `Inspector`, or, for - its PostgreSQL type, from the model's `__table_args__` (`declared_column`). + has no statement through the model: `update(Model).values(column=...)` and + `insert(Model).values(column=...)` raise `AttributeError` whatever their + synchronization, 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 column-only class of a registry + of its own, of the kind `tests.integration.privilege_statements` holds, 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(...)`. @@ -404,10 +396,9 @@ and `REVOKE`, `ALTER DEFAULT PRIVILEGES`, `CREATE`, `ALTER` and `DROP ROLE` (with `DROP OWNED BY`), `CREATE VIEW` and `CREATE MATERIALIZED VIEW`, `DROP TABLE`, `TRUNCATE`, `COPY`, `EXPLAIN`, `ANALYZE`, Alembic's need for a Connection, and connection settings no SQL function sets, such as SQLite's -`foreign_keys` and `BEGIN IMMEDIATE`. So does the Core declaration of a -column a mapper leaves out until a revision drops it. Roles and Postgres -settings inside a transaction need none: `set_config` sets them. Keep the -entries in as few modules as possible. The entries: +`foreign_keys` and `BEGIN IMMEDIATE`. Roles and Postgres settings inside a +transaction need none: `set_config` sets them. Keep the entries in as few +modules as possible. The entries: 1. **Alembic environments and revisions** (`migration-revision`), `migrations/**/*.py`. The environments run Alembic's migration context on @@ -463,14 +454,6 @@ entries in as few modules as possible. The entries: `CREATE VIEW` and `CREATE MATERIALIZED VIEW` in `create_view`, which SQLAlchemy has no construct for. The reconciliation's catalog reads are tested on those grants. -9. **A column a mapper leaves out** (`no-orm-form`), in - `policyengine_api/data/v2/models/associations.py`'s - `UserReportAssociation`: `user_report_associations.provisions`, a copy of - a saved report's reform changes that nothing reads or writes. The ORM has - no form for a column a table keeps but its class doesn't map, so the class - declares it as a Core column in `__table_args__` (see "Columns a mapper - leaves out" above). D1 · 10's revision drops the column and removes this - entry. A new exception is a rule change: add a `[[rule.exception]]` entry to the rule in `rules/registry.toml`, explain here why the ORM can't express the diff --git a/docs/generated/rules.md b/docs/generated/rules.md index bb145e288..fd65f8141 100644 --- a/docs/generated/rules.md +++ b/docs/generated/rules.md @@ -76,7 +76,6 @@ Every rule that governs `policyengine-api` is listed here with how it is enforce - `api.data.orm-only`: exception for `policyengine_api/data/v2/catalog/publication_staging.py` (`session.connection()` in `copy_rows`) allowed as a no-orm-form (Catalog publication streams rows with COPY ... FROM STDIN through the psycopg connection beneath the Connection the publishing Session holds, in its transaction.) - `api.data.orm-only`: exception for `policyengine_api/data/v2/catalog/publication_staging.py` (`session.connection()` in `create_staging_tables`) allowed as a no-orm-form (Catalog publication creates its TEMPORARY staging tables with MetaData.create_all, which takes a Connection: the Connection the publishing Session holds, in its transaction.) - `api.data.orm-only`: exception for `policyengine_api/data/v2/catalog/publication_statistics.py` (`sa.text(f'ANALYZE {tables}')` in `analyze_catalog_tables`) allowed as a no-orm-form (ANALYZE has no ORM form. After a publication commits, one ANALYZE refreshes the planner statistics of the catalog tables it wrote.) -- `api.data.orm-only`: exception for `policyengine_api/data/v2/models/associations.py` (`sa.Column('provisions', ...)` in `UserReportAssociation`) allowed as a no-orm-form (A saved report keeps no copy of its reform's changes, so UserReportAssociation leaves user_report_associations.provisions out of its mapper (exclude_properties), and no statement reads or writes it. The ORM has no form for a column a table keeps but its class doesn't map, so the class declares it as a Core column in __table_args__, which keeps it in the v2 metadata: Alembic then finds no difference from the database, and the test databases built from the metadata keep it. D1 · 10's revision drops the column, and with it this entry.) - `api.data.orm-only`: exception for `policyengine_api/data/v2/pending_revisions.py` (`session.connection()` in `v2_revision_is_pending`) allowed as a no-orm-form (Alembic's MigrationContext reads the database's current heads from its version table through a Connection. The migration qualification commands give it the Connection their Session holds, so the read runs inside the Session's READ ONLY transaction.) - `api.data.orm-only`: exception for `policyengine_api/data/v2/privilege_reconciliation.py` (`text(f'CREATE ROLE {quote(safe_identifier(role))} NOLOGIN')` in `create_missing_roles`) allowed as a no-orm-form (CREATE ROLE has no SQLAlchemy form. reconcile_v2_privileges.py apply --create-missing-roles creates each missing managed role as NOLOGIN, only in the disposable test database, in the reconciliation's one transaction. The role name is checked by safe_identifier and quoted by the session's dialect.) - `api.data.orm-only`: exception for `policyengine_api/data/v2/privilege_reconciliation.py` (`text(statement)` in `apply_declared_privileges`) allowed as a no-orm-form (GRANT and REVOKE have no SQLAlchemy form. apply runs the REVOKEs and GRANTs that privilege_plans' revoke_statements and grant_statements build from the declared privileges, with identifiers checked by safe_identifier and quoted by the session's dialect, in the reconciliation's one transaction.) diff --git a/policyengine_api/data/v2/models/associations.py b/policyengine_api/data/v2/models/associations.py index 6922a7c72..eb91c9bc8 100644 --- a/policyengine_api/data/v2/models/associations.py +++ b/policyengine_api/data/v2/models/associations.py @@ -317,17 +317,17 @@ class UserReportAssociation(TimestampedModel, table=True): A saved report keeps no copy of its reform's changes: its pages read the report's policy and dynamic records. The table's ``provisions`` column, - where saved reports used to keep that copy, is left out of this model, so - API v1 neither loads nor writes it, and a release keeps working while a - later revision (D1 · 10) drops it. + where saved reports used to keep that copy, stays a SQLModel field, as rule + ``api.data.orm-only`` requires of every column, and ``exclude_properties`` + leaves it out of the mapper, so API v1 neither loads nor writes it: a value + given to the constructor is never stored, and the class attribute is the + table's column, not a value to read. A release keeps working while a later + revision (D1 · 10) drops it. """ __tablename__ = "user_report_associations" __mapper_args__: ClassVar[dict[str, Any]] = {"exclude_properties": ("provisions",)} __table_args__ = ( - # Kept in the table, unmapped, until a revision drops it: rows saved - # before keep their copy of the reform's changes, which nothing reads. - sa.Column("provisions", _jsonb_type()), sa.UniqueConstraint( "id", "country_id", @@ -418,6 +418,10 @@ class UserReportAssociation(TimestampedModel, table=True): index=True, ) source_note: str | None = Field(default=None, sa_type=sa.Text) + # In the table but left out of the mapper (``exclude_properties``) until a + # revision drops it: rows saved before keep their copy of the reform's + # changes, which nothing reads. + provisions: list[Any] | None = Field(default=None, sa_type=_jsonb_type()) validation: dict[str, Any] | None = Field(default=None, sa_type=_jsonb_type()) # Years in the budget window run with the report, from the report's year. budget_window_years: int | None = Field(default=None, sa_type=sa.SmallInteger) diff --git a/policyengine_api/data/v2/models/base.py b/policyengine_api/data/v2/models/base.py index 82e171a54..3ea81a366 100644 --- a/policyengine_api/data/v2/models/base.py +++ b/policyengine_api/data/v2/models/base.py @@ -39,6 +39,12 @@ "Concurrent report idempotency requires a savepoint and bounded " "IntegrityError recovery around the database uniqueness constraint." ), + "columns_left_out_of_the_mapper": ( + "A column API v1 no longer uses stays a SQLModel field of its " + "table, left out of the mapper by exclude_properties, until other " + "writers have stopped and a later revision drops it; API v1 neither " + "loads nor writes it meanwhile." + ), } ) diff --git a/rules/registry.toml b/rules/registry.toml index cc742d99b..efa174f99 100644 --- a/rules/registry.toml +++ b/rules/registry.toml @@ -749,13 +749,6 @@ function = "acquire_user_type_change_lock" category = "no-orm-form" reason = "Reads the dialect's name, to skip PostgreSQL's advisory lock on the SQLite test databases, which have none. It runs no statement on the engine." -[[rule.exception]] -path = "policyengine_api/data/v2/models/associations.py" -match = "sa.Column('provisions', ...)" -function = "UserReportAssociation" -category = "no-orm-form" -reason = "A saved report keeps no copy of its reform's changes, so UserReportAssociation leaves user_report_associations.provisions out of its mapper (exclude_properties), and no statement reads or writes it. The ORM has no form for a column a table keeps but its class doesn't map, so the class declares it as a Core column in __table_args__, which keeps it in the v2 metadata: Alembic then finds no difference from the database, and the test databases built from the metadata keep it. D1 · 10's revision drops the column, and with it this entry." - [[rule.exception]] path = "tests/fixtures/database_sessions.py" match = "sqlite_connection.execute('PRAGMA foreign_keys = ON')" diff --git a/tests/integration/test_v2_simulation_role_privileges.py b/tests/integration/test_v2_simulation_role_privileges.py index fd00e586e..9f6e7683e 100644 --- a/tests/integration/test_v2_simulation_role_privileges.py +++ b/tests/integration/test_v2_simulation_role_privileges.py @@ -19,8 +19,8 @@ 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 -(``exclude_properties``) has no attribute on the model, so its writes and -refusals would go through a class that maps it; since revision +(``exclude_properties``) has no statement through the model, so its writes +and refusals would go through a class that maps it; since revision ``4e30076d4b9f`` no model of the simulation tables leaves a column out. """ diff --git a/tests/unit/v2/v2_schema_reading.py b/tests/unit/v2/v2_schema_reading.py index e8e97c523..6026ef88a 100644 --- a/tests/unit/v2/v2_schema_reading.py +++ b/tests/unit/v2/v2_schema_reading.py @@ -11,9 +11,8 @@ rule, check condition and index the models declare. Its columns also hold any a mapper leaves out (``exclude_properties``) until a revision drops it. -What only PostgreSQL receives is read from the model's ``__table_args__``: a -partial index's PostgreSQL condition (``declared_index``), and the PostgreSQL -type of a column the mapper leaves out (``declared_column``). +What only PostgreSQL receives, such as a partial index's PostgreSQL condition, +is read from the model's ``__table_args__`` (``declared_index``). """ from __future__ import annotations @@ -290,19 +289,3 @@ def declared_index(model: type[Any], index_name: str) -> sa.Index: for argument in model.__table_args__ if isinstance(argument, sa.Index) and argument.name == index_name ) - - -def declared_column(model: type[Any], column_name: str) -> sa.Column[Any] | None: - """Return the column called ``column_name`` in the model's ``__table_args__``. - - A model declares there a column its mapper leaves out (``exclude_properties``) - until a revision drops it. None when it declares no such column. - """ - return next( - ( - argument - for argument in model.__table_args__ - if isinstance(argument, sa.Column) and argument.name == column_name - ), - None, - )