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..b2a6778d8 --- /dev/null +++ b/changelog.d/saved-reports-drop-reform-copy.removed.md @@ -0,0 +1 @@ +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/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..93f9ff764 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -310,11 +310,13 @@ 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 - `AttributeError`, a constructor value is never stored, and `Model.column` + `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=...)` 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 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..eb91c9bc8 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,9 +314,19 @@ 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, 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__ = ( sa.UniqueConstraint( "id", @@ -408,6 +418,9 @@ 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. 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/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..21e3f7b17 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,24 @@ 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=( + "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}, + ) 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 +243,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 +258,9 @@ 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 no stored field except + ``updated_at``, as every update sets. """ report_id: ResourceId | None = None @@ -290,7 +303,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 +318,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 +348,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/integration/test_v2_simulation_role_privileges.py b/tests/integration/test_v2_simulation_role_privileges.py index 5b7df5d61..9f6e7683e 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 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. """ 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]] = {} 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_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 f74fb2a7a..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, @@ -325,8 +316,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_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 f8cec40b7..81ce9c257 100644 --- a/tests/unit/v2/test_models.py +++ b/tests/unit/v2/test_models.py @@ -666,15 +666,32 @@ 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 + # The column stays a SQLModel field, which declares its PostgreSQL type. + field = UserReportAssociation.model_fields.get("provisions") + assert field is not None + assert isinstance( + field.sa_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..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"), @@ -483,7 +481,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..09e84da86 --- /dev/null +++ b/tests/unit/v2/test_saved_report_reform_copy.py @@ -0,0 +1,204 @@ +"""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 +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, +) +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 Callable, Iterator + from uuid import UUID + + from sqlalchemy.sql.dml import Insert, Update + +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 + + +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)) diff --git a/tests/unit/v2/test_shared_report_routes.py b/tests/unit/v2/test_shared_report_routes.py index e63789549..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"), @@ -82,7 +72,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..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, @@ -234,10 +233,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 +337,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 +350,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 +358,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 +375,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"}