diff --git a/.github/scripts/test_alembic_v2_lifecycle.sh b/.github/scripts/test_alembic_v2_lifecycle.sh index aa86cfa4e..b01056d07 100755 --- a/.github/scripts/test_alembic_v2_lifecycle.sh +++ b/.github/scripts/test_alembic_v2_lifecycle.sh @@ -13,4 +13,5 @@ uv run --frozen --extra dev pytest -q \ tests/integration/test_alembic_v2_withheld_area_codes.py \ tests/integration/test_alembic_v2_shared_report_keys.py \ tests/integration/test_alembic_v2_cliff_impacts.py \ - tests/integration/test_alembic_v2_dynamics.py + tests/integration/test_alembic_v2_dynamics.py \ + tests/integration/test_alembic_v2_report_column_drops.py diff --git a/changelog.d/drop-report-per-user-columns.removed.md b/changelog.d/drop-report-per-user-columns.removed.md new file mode 100644 index 000000000..701654a0d --- /dev/null +++ b/changelog.d/drop-report-per-user-columns.removed.md @@ -0,0 +1 @@ +The v2 database no longer stores a label, description or user on reports, a trigger on report runs or budget-window runs, or cliff results on report runs. A report's name and description are on each user's saved report, each user's trigger is on their record of the run, and cliffs are each simulation run's cliff results. diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index e305f1486..de646feb3 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -309,15 +309,14 @@ and `refused(session, ...)`. `add_row(session, Model, **values)`, given a mapped class. A JSON column takes the Python value, such as `[2026]`, not its JSON text. - **Columns a mapper leaves out**: a column kept in its table but left out of - the model's mapper (`exclude_properties`), such as a report's `label`, - `description` and `user_id`, a report run's `trigger` and four older cliff - columns, and a budget-window run's `trigger` until a revision drops them, - has no statement through the model: `update(Model).values(column=...)` - raises `AttributeError`, a constructor value is never stored, and - `Model.column` is the table's Core column, which the rule rules out even - in a `select`. A test that sets or selects one maps it on a class of a - registry of its own, as `tests.integration.privilege_statements`' - `ReportColumns`, `ReportRunColumns` and `BudgetWindowRunColumns` do, and + the model's mapper (`exclude_properties`) until a revision drops it, as + 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` + 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 @@ -751,6 +750,8 @@ it publishes that version, with nothing to restore it. Downgrading past the revision is therefore safe only while no version is pruned (no `tax_benefit_model_versions` row has `catalog_values_pruned_at` set). From the head, such a downgrade first runs the later revisions' downgrades: +`4e30076d4b9f`'s adds the dropped report columns back empty (see "API v2 report +column drops"), `bc334f9877b7`'s drops `cliff_impacts` with every simulation run's cliff results (see "API v2 simulation-run cliff impacts"), `9d1d12a7ac58`'s needs `dynamics` empty (see "API v2 dynamics stored like @@ -758,8 +759,9 @@ policies"), `f519a77ba122`'s drops `user_invitations` and needs no recorded change with source `invitation` (see "API v2 user invitations"), `94dc43079186`'s drops every user's report-run record, the simulation and -report keys and the window runs' .py versions, and needs every report to have -a label and every run a trigger (see "API v2 shared reports and user report-run records"), +report keys and the window runs' .py versions, and needs no report or report +run to exist, since `4e30076d4b9f`'s restored their labels and triggers empty +(see "API v2 shared reports and user report-run records"), `970be5d29283`'s drops `user_type_changes` with every recorded change (see "API v2 user type changes"), `617f531f1506`'s needs no user to be an author or an admin (see "API v2 user types"), and `1356f658347d`'s needs @@ -1422,9 +1424,8 @@ them and update their state and result columns, never insert them; the runtime role may read them; neither simulation role may change the run a row names or delete a row. The reconcile step after each schema upgrade grants them. Until the simulation API writes the table, no run has a cliff -calculation, and its cliffs stay refused. `report_runs`' four cliff columns -stay until a later revision drops them, once API v1 reads cliffs from -here. +calculation, and its cliffs stay refused. Revision `4e30076d4b9f` drops +`report_runs`' four cliff columns. It has one post-generation correction, commented in the revision: `status` reuses the baseline's `v2_simulation_status` type @@ -1442,3 +1443,71 @@ else changes, that the downgrade leaves the type and an upgrade works again, and the index, checks and delete rule; `tests/integration/test_v2_simulation_role_privileges.py` runs the writes and reads as the roles that do them. + +### API v2 report column drops + +Revision `4e30076d4b9f` (parent `bc334f9877b7`) was autogenerated, with its ID +given by `--rev-id`, after these columns left the models. Reports, report runs +and budget-window runs are shared by every request that joins them, so they +hold nothing about one caller, and a report run's cliffs are its two simulation +runs' results in `cliff_impacts`. It drops: + +- `reports.label`, `description` and `user_id`, with + `fk_reports_user_id_users` and `ix_reports_user_id`. A report's name and + description are on each user's saved report, and deleting a user no longer + touches `reports`. +- `report_runs.trigger` and `budget_window_runs.trigger`. Each user's trigger + is on their `user_report_run_associations` row, which still uses the + `v2_report_run_trigger` type, and `/v2/reports` run items no longer have a + `trigger` field. +- `report_runs`' `baseline_cliff_gap`, `baseline_cliff_share`, + `reform_cliff_gap` and `reform_cliff_share`, with + `ck_report_runs_cliff_impact_complete`. The Modal worker's column privileges + on them go too. + +It has one post-generation correction, commented in the revision: autogenerate +strips the first and last parenthesis of the reflected check condition, which +leaves the downgrade's `create_check_constraint` with invalid SQL. + +**What must be in production first.** The deploy upgrades the schema before the +new Cloud Run revision takes traffic (see "CI/CD behavior"), so the previous +release serves on this schema, for longer if promotion fails: + +- An API v1 release whose `Report`, `ReportRun` and `BudgetWindowRun` no longer + map these columns. Report reads load whole rows, and a whole-row load names + every mapped column, so otherwise every `/v2/reports` read fails. +- A simulation API release whose v2 Modal runtime no longer writes the four + cliff columns. Otherwise every economy report run's completion fails. + +The simulation API's table models must then lose the same columns. Until they +do, its comparison with API v1's tables fails; requests are not affected. + +**The dropped values are not kept.** Nothing copies them, since these rows name +no user to copy them to, and the downgrade can't restore them. One merge takes +the revision through staging and production in a single release run, so before +merging, an operator exports what those rows hold in both environments with +these read-only queries, and keeps the result outside the repository, because +labels and descriptions are users' text: + +```sql +SELECT id, created_at, label, description, user_id FROM reports +WHERE label IS NOT NULL OR description IS NOT NULL OR user_id IS NOT NULL; +SELECT id, report_id, created_at, trigger, baseline_cliff_gap, + baseline_cliff_share, reform_cliff_gap, reform_cliff_share +FROM report_runs +WHERE trigger IS NOT NULL OR baseline_cliff_gap IS NOT NULL; +SELECT id, report_id, created_at, trigger FROM budget_window_runs +WHERE trigger IS NOT NULL; +``` + +The downgrade adds the columns, key, index and check back with every value +null. The Modal worker's `UPDATE` on the four cliff columns doesn't come back +with them: it returns only when `reconcile_v2_privileges.py apply` runs from a +`privileges.py` that names them. Continuing below `bc334f9877b7` to +`94dc43079186`'s parent fails while any report or run exists, because that +downgrade needs every report to have a label and every run a trigger. + +`tests/integration/test_alembic_v2_report_column_drops.py` compares the revision +and its downgrade with the parent schema built from the base, and checks that +rows survive the upgrade, that the downgrade restores no values, and that the +deploy's privilege steps pass. diff --git a/docs/migration/stage-12a-user-login.md b/docs/migration/stage-12a-user-login.md index 67c4085a5..2f0c9d958 100644 --- a/docs/migration/stage-12a-user-login.md +++ b/docs/migration/stage-12a-user-login.md @@ -770,7 +770,8 @@ admin; `scripts/set_v2_user_type.py` makes another admin afterwards. `users.primary_country`, so it fails while legacy-only rows, any simulation or report associations, or any unauthenticated user exist. Removing them first deletes users' saved work. From the head, the later revisions' - downgrades run first: the cliff impacts revision (`bc334f9877b7`) drops + downgrades run first: the report column drops revision (`4e30076d4b9f`) adds + the dropped report columns back empty, the cliff impacts revision (`bc334f9877b7`) drops every simulation run's cliff results, the dynamics revision (`9d1d12a7ac58`) needs `dynamics` empty, the user invitations revision (`f519a77ba122`) drops @@ -778,7 +779,8 @@ admin; `scripts/set_v2_user_type.py` makes another admin afterwards. `invitation`, the shared reports revision (`94dc43079186`) drops every user's report-run record, every simulation and report key, the runs' `forced` markers, the window runs' .py versions and the one-unfailed-run - indexes, and needs every report to have a label and every run a trigger, the + indexes, and needs no report or report run to exist, since the report column + drops revision restored their labels and triggers empty, the user type changes revision (`970be5d29283`) drops every recorded change, the user types revision (`617f531f1506`) needs no author or admin, and the simulation runs revision (`1356f658347d`) needs diff --git a/docs/migration/stage-9-v2-metadata.md b/docs/migration/stage-9-v2-metadata.md index dddd3d274..0b236f8fe 100644 --- a/docs/migration/stage-9-v2-metadata.md +++ b/docs/migration/stage-9-v2-metadata.md @@ -835,7 +835,8 @@ pruning"). A schema downgrade past revision `334859ef4fec` drops `catalog_last_published_at` and `catalog_values_pruned_at`. From the head, -it first runs the later revisions' downgrades: `bc334f9877b7`'s drops +it first runs the later revisions' downgrades: `4e30076d4b9f`'s adds the +dropped report columns back empty, `bc334f9877b7`'s drops `cliff_impacts` with every simulation run's cliff results, `9d1d12a7ac58`'s needs `dynamics` empty, `f519a77ba122`'s drops `user_invitations` and needs no recorded change with source @@ -843,8 +844,9 @@ drops `user_invitations` and needs no recorded change with source `94dc43079186`'s drops `user_report_run_associations` with every user's report-run record, the simulation and report keys, the runs' `forced` markers, the window runs' .py -versions and the one-unfailed-run indexes, and needs every report to have a -label and every run a trigger, `970be5d29283`'s drops `user_type_changes` with +versions and the one-unfailed-run indexes, and needs no report or report run +to exist, since `4e30076d4b9f`'s restored their labels and triggers empty, +`970be5d29283`'s drops `user_type_changes` with every recorded change, `617f531f1506`'s needs no user to be an author or an admin, and `1356f658347d`'s needs `simulations` empty. A pruned version diff --git a/migrations/v2/versions/4e30076d4b9f_drop_per_user_and_cliff_columns_from_.py b/migrations/v2/versions/4e30076d4b9f_drop_per_user_and_cliff_columns_from_.py new file mode 100644 index 000000000..4b467b07c --- /dev/null +++ b/migrations/v2/versions/4e30076d4b9f_drop_per_user_and_cliff_columns_from_.py @@ -0,0 +1,68 @@ +"""drop per-user and cliff columns from report rows + +Revision ID: 4e30076d4b9f +Revises: bc334f9877b7 +Create Date: 2026-11-19 02:25:37.425693 +Generation: uv run alembic -c alembic-v2.ini revision --autogenerate --rev-id 4e30076d4b9f + +One post-generation correction, commented where it is made: the downgrade's +check condition gets back the first and last parenthesis autogenerate strips. + +Reports, report runs and budget-window runs are shared by every request that +joins them, so they hold nothing about one caller, and a report run's cliffs +are its simulation runs' results in cliff_impacts. This drops reports.label, +description and user_id, report_runs.trigger and its four cliff columns, and +budget_window_runs.trigger, with their foreign key, index and check. + +The dropped values are not recoverable: the downgrade adds the columns back +empty. Export them first if they are wanted. Every release still serving when +this runs must already leave these columns out of its models and statements. +""" + +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +import sqlmodel +from sqlalchemy.dialects import postgresql + +revision: str = '4e30076d4b9f' +down_revision: Union[str, None] = 'bc334f9877b7' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('budget_window_runs', 'trigger') + op.drop_constraint(op.f('ck_report_runs_cliff_impact_complete'), 'report_runs', type_='check') + op.drop_column('report_runs', 'baseline_cliff_share') + op.drop_column('report_runs', 'trigger') + op.drop_column('report_runs', 'reform_cliff_gap') + op.drop_column('report_runs', 'reform_cliff_share') + op.drop_column('report_runs', 'baseline_cliff_gap') + op.drop_index(op.f('ix_reports_user_id'), table_name='reports') + op.drop_constraint(op.f('fk_reports_user_id_users'), 'reports', type_='foreignkey') + op.drop_column('reports', 'description') + op.drop_column('reports', 'label') + op.drop_column('reports', 'user_id') + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('reports', sa.Column('user_id', sa.UUID(), autoincrement=False, nullable=True)) + op.add_column('reports', sa.Column('label', sa.VARCHAR(length=255), autoincrement=False, nullable=True)) + op.add_column('reports', sa.Column('description', sa.VARCHAR(), autoincrement=False, nullable=True)) + op.create_foreign_key(op.f('fk_reports_user_id_users'), 'reports', 'users', ['user_id'], ['id'], ondelete='SET NULL') + op.create_index(op.f('ix_reports_user_id'), 'reports', ['user_id'], unique=False) + op.add_column('report_runs', sa.Column('baseline_cliff_gap', sa.DOUBLE_PRECISION(precision=53), autoincrement=False, nullable=True)) + op.add_column('report_runs', sa.Column('reform_cliff_share', sa.DOUBLE_PRECISION(precision=53), autoincrement=False, nullable=True)) + op.add_column('report_runs', sa.Column('reform_cliff_gap', sa.DOUBLE_PRECISION(precision=53), autoincrement=False, nullable=True)) + op.add_column('report_runs', sa.Column('trigger', postgresql.ENUM('initial', 'manual', 'system', name='v2_report_run_trigger'), autoincrement=False, nullable=True)) + op.add_column('report_runs', sa.Column('baseline_cliff_share', sa.DOUBLE_PRECISION(precision=53), autoincrement=False, nullable=True)) + # Post-generation correction: autogenerate strips the first and last + # parenthesis of the reflected condition, which leaves invalid SQL. + op.create_check_constraint(op.f('ck_report_runs_cliff_impact_complete'), 'report_runs', '(baseline_cliff_gap IS NULL) = (baseline_cliff_share IS NULL) AND (baseline_cliff_gap IS NULL) = (reform_cliff_gap IS NULL) AND (baseline_cliff_gap IS NULL) = (reform_cliff_share IS NULL)') + op.add_column('budget_window_runs', sa.Column('trigger', postgresql.ENUM('initial', 'manual', 'system', name='v2_report_run_trigger'), autoincrement=False, nullable=True)) + # ### end Alembic commands ### diff --git a/policyengine_api/data/v2/migration_target.py b/policyengine_api/data/v2/migration_target.py index 6c3b6c7f4..ca56eb1a9 100644 --- a/policyengine_api/data/v2/migration_target.py +++ b/policyengine_api/data/v2/migration_target.py @@ -27,7 +27,7 @@ from sqlmodel import Session V2_ALEMBIC_DISPOSABLE_TEST = "V2_ALEMBIC_DISPOSABLE_TEST" -V2_ALEMBIC_HEAD_REVISION = "bc334f9877b7" +V2_ALEMBIC_HEAD_REVISION = "4e30076d4b9f" DISPOSABLE_DATABASE_NAME = "policyengine_v2_alembic_test" DISPOSABLE_HOSTS = frozenset({"localhost", "127.0.0.1", "::1", "postgres"}) MIGRATION_ROLE = "policyengine_v2_migrator" diff --git a/policyengine_api/data/v2/models/base.py b/policyengine_api/data/v2/models/base.py index 3ea81a366..82e171a54 100644 --- a/policyengine_api/data/v2/models/base.py +++ b/policyengine_api/data/v2/models/base.py @@ -39,12 +39,6 @@ "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/data/v2/models/reports.py b/policyengine_api/data/v2/models/reports.py index 6bf2e64c3..9e599f9eb 100644 --- a/policyengine_api/data/v2/models/reports.py +++ b/policyengine_api/data/v2/models/reports.py @@ -7,7 +7,7 @@ from datetime import datetime from enum import StrEnum -from typing import TYPE_CHECKING, Any, ClassVar +from typing import TYPE_CHECKING, Any from uuid import UUID import sqlalchemy as sa @@ -79,14 +79,8 @@ class Report(TimestampedModel, table=True): dataset or region clears the reference; the model and household can't be deleted while a report names them. - A report is shared by everyone who asks for it, so it describes no one - caller: a report's name and description are on each user's saved report. - The table's ``label``, ``description`` and ``user_id`` stay SQLModel - fields, as rule ``api.data.orm-only`` requires of every column, and - ``exclude_properties`` leaves them out of the mapper, so API v1 neither - loads nor writes them: a value given to the constructor is never stored, - and the class attributes are the table's columns, not values to read. A - release keeps working while a later revision drops them. + A report is shared by everyone who asks for it, so it names no user. A + report's name and description are on each user's saved report. The simulation service finds a report by ``definition_key``, the SHA-256 of what it compares (its country, type, each side's policy and dynamic, @@ -99,9 +93,6 @@ class Report(TimestampedModel, table=True): """ __tablename__ = "reports" - __mapper_args__: ClassVar[dict[str, Any]] = { - "exclude_properties": ("label", "description", "user_id") - } __table_args__ = ( sa.CheckConstraint( "year IS NULL OR year BETWEEN 1900 AND 2200", @@ -130,19 +121,8 @@ class Report(TimestampedModel, table=True): sa.Index("ix_reports_dataset_independent_key", "dataset_independent_key"), ) - # In the table but left out of the mapper (``exclude_properties``) until a - # revision drops them. - label: str | None = Field(default=None, max_length=255) - description: str | None = None country: str = Field(max_length=16) type: str | None = Field(default=None, max_length=128) - # In the table but left out of the mapper, like ``label``. - user_id: UUID | None = Field( - default=None, - foreign_key="users.id", - ondelete="SET NULL", - index=True, - ) tax_benefit_model_id: UUID = Field( foreign_key="tax_benefit_models.id", ondelete="RESTRICT", @@ -230,7 +210,6 @@ class BudgetWindowRun(TimestampedModel, table=True): """ __tablename__ = "budget_window_runs" - __mapper_args__: ClassVar[dict[str, Any]] = {"exclude_properties": ("trigger",)} __table_args__ = ( sa.UniqueConstraint("id", "report_id", name="uq_budget_window_runs_id_report"), sa.CheckConstraint( @@ -261,13 +240,6 @@ class BudgetWindowRun(TimestampedModel, table=True): index=True, ) policyengine_version: str | None = Field(default=None, max_length=128) - # In the table but left out of the mapper (``exclude_properties``) until a - # revision drops it: a shared run answers more than one request, and each - # user's trigger is on their record of it. - trigger: ReportRunTrigger | None = Field( - default=None, - sa_type=enum_type(ReportRunTrigger, "v2_report_run_trigger"), - ) recalculate: bool = False status: ReportRunStatus = Field( default=ReportRunStatus.PENDING, @@ -292,16 +264,12 @@ class ReportRun(TimestampedModel, table=True): It compares ``baseline_simulation_run_id`` with ``reform_simulation_run_id``; a household report with only a baseline has no reform run. A year of a budget window names its ``budget_window_run_id`` - and ``year``, at most one report run per year of a window run. - ``spm_provenance`` is the SPM receipt and ``data_version`` the data release - it used. Its labour supply response has its own two tables. Its cliff impact - is its two simulation runs' (``CliffImpact``), and each user's trigger is on - their record of the run. The table's four older cliff columns and - ``trigger`` stay SQLModel fields, as rule ``api.data.orm-only`` requires of - every column, and ``exclude_properties`` leaves them out of the mapper, so - API v1 neither loads nor writes them: a value given to the constructor is - never stored, and the class attributes are the table's columns, not values - to read. A release keeps working while a later revision drops them. + and ``year``, at most one report run per year of a window run. An economy + comparison's cliff impact is its two simulation runs' cliff results + (``cliff_impacts``); ``spm_provenance`` is the SPM receipt and + ``data_version`` the data release it used. Its labour supply response has + its own two tables. A run is shared by every request that joins it, so + each user's trigger is on their ``user_report_run_associations`` row. Outside budget windows, a report has at most one run that hasn't failed for each pair of package versions, which identical requests join; a @@ -310,15 +278,6 @@ class ReportRun(TimestampedModel, table=True): """ __tablename__ = "report_runs" - __mapper_args__: ClassVar[dict[str, Any]] = { - "exclude_properties": ( - "trigger", - "baseline_cliff_gap", - "baseline_cliff_share", - "reform_cliff_gap", - "reform_cliff_share", - ) - } __table_args__ = ( sa.UniqueConstraint( "report_id", @@ -350,12 +309,6 @@ class ReportRun(TimestampedModel, table=True): name="fk_report_runs_budget_window_run_id_budget_window_runs", ondelete="CASCADE", ), - sa.CheckConstraint( - "(baseline_cliff_gap IS NULL) = (baseline_cliff_share IS NULL) " - "AND (baseline_cliff_gap IS NULL) = (reform_cliff_gap IS NULL) " - "AND (baseline_cliff_gap IS NULL) = (reform_cliff_share IS NULL)", - name="ck_report_runs_cliff_impact_complete", - ), sa.Index( "ix_report_runs_current_output", "report_id", @@ -404,13 +357,6 @@ class ReportRun(TimestampedModel, table=True): default=ReportRunStatus.PENDING, sa_type=enum_type(ReportRunStatus, "v2_report_run_status"), ) - # In the table but left out of the mapper (``exclude_properties``) until a - # revision drops it: a shared run answers more than one request, and each - # user's trigger is on their record of it. - trigger: ReportRunTrigger | None = Field( - default=None, - sa_type=enum_type(ReportRunTrigger, "v2_report_run_trigger"), - ) idempotency_key: UUID | None = Field(default=None) modal_call_id: str | None = Field(default=None, max_length=255) started_at: datetime | None = Field( @@ -423,12 +369,6 @@ class ReportRun(TimestampedModel, table=True): ) error_message: str | None = None markdown: str | None = Field(default=None, sa_type=sa.Text) - # In the table but left out of the mapper (``exclude_properties``) until a - # revision drops them. - baseline_cliff_gap: float | None = None - baseline_cliff_share: float | None = None - reform_cliff_gap: float | None = None - reform_cliff_share: float | None = None spm_provenance: dict[str, Any] | None = Field( default=None, sa_type=sa.JSON().with_variant(postgresql.JSONB(), "postgresql"), diff --git a/policyengine_api/data/v2/models/users.py b/policyengine_api/data/v2/models/users.py index ee923cb08..3efe21d2b 100644 --- a/policyengine_api/data/v2/models/users.py +++ b/policyengine_api/data/v2/models/users.py @@ -79,7 +79,7 @@ class User(IdentifiedModel, table=True): A signed-in user, of any type but ``unauthenticated``, always has a primary country. Deleting a user deletes their sign-in identities, saved associations and records of the report runs they asked for; the reports - and runs themselves are shared and stay. + and runs themselves are shared, name no user and stay. """ __tablename__ = "users" diff --git a/policyengine_api/data/v2/privileges.py b/policyengine_api/data/v2/privileges.py index 1975e517d..2797fed4d 100644 --- a/policyengine_api/data/v2/privileges.py +++ b/policyengine_api/data/v2/privileges.py @@ -50,7 +50,7 @@ the database refuses any change to what a run is (its simulation or report, versions, dataset, region, year, simulation runs, budget-window run or whether a forced re-run created it) or to what a budget-window run is (its report, -catalog version, .py version, trigger or whether it calculates again). It +catalog version, .py version or whether it calculates again). It doesn't limit a worker to its own run; the workers' code does. Their code lives in the simulation API's repository, so the deploy check covers them here. @@ -260,10 +260,6 @@ def _run_table( ), "household_jobs": _run_table("result"), "report_runs": _run_table( - "baseline_cliff_gap", - "baseline_cliff_share", - "reform_cliff_gap", - "reform_cliff_share", "spm_provenance", "data_version", catalog_writer=READ, diff --git a/policyengine_api/services/v2/stored_reports/database_connectors/reads_results.py b/policyengine_api/services/v2/stored_reports/database_connectors/reads_results.py index bec67bdfa..0c19564d8 100644 --- a/policyengine_api/services/v2/stored_reports/database_connectors/reads_results.py +++ b/policyengine_api/services/v2/stored_reports/database_connectors/reads_results.py @@ -96,8 +96,7 @@ def read_economy_result_rows( # noqa: PLR0913 # the session, then each part of The withheld area codes are read only for a local-area report's run (``on_local_area_dataset``), whose writer records them. ``cliff_calculations`` are its simulation runs' cliff calculations, as - ``read_cliff_calculations`` read them. The report run's own four cliff - columns are not read. + ``read_cliff_calculations`` read them. """ report_run_id = report_run.id simulation_run_ids = ( diff --git a/policyengine_api/services/v2/stored_reports/economy_results/transformations.py b/policyengine_api/services/v2/stored_reports/economy_results/transformations.py index d82ed8962..cbf81e01a 100644 --- a/policyengine_api/services/v2/stored_reports/economy_results/transformations.py +++ b/policyengine_api/services/v2/stored_reports/economy_results/transformations.py @@ -25,8 +25,7 @@ - ``constituency_withheld_codes`` and ``local_authority_withheld_codes``, for a local-area report only, from ``withheld_area_codes``, sorted. - ``cliff_impact`` from each simulation run's cliff calculation - (``cliff_impacts``), once both have succeeded, and never from the report - run's own four cliff columns. + (``cliff_impacts``), once both have succeeded. - ``spm_provenance``, ``data_version`` and ``model_version`` from the report run's own columns; the SPM receipts are read as ``SPMComparisonProvenance``. diff --git a/policyengine_api/services/v2/stored_reports/economy_results/types.py b/policyengine_api/services/v2/stored_reports/economy_results/types.py index 6428c9020..a7f1d0295 100644 --- a/policyengine_api/services/v2/stored_reports/economy_results/types.py +++ b/policyengine_api/services/v2/stored_reports/economy_results/types.py @@ -363,8 +363,8 @@ class EconomyResult(EconomyResultModel): class ReportRunResultColumns: """The result columns of the report run itself. - ``country_package_version`` is the run's. Its four cliff columns are not - read: a report run's cliffs are its simulation runs' (``cliff_impacts``). + ``country_package_version`` is the run's. A report run's cliffs are its + simulation runs' (``cliff_impacts``). """ country_package_version: str diff --git a/tests/fixtures/economy_results.py b/tests/fixtures/economy_results.py index ea6d5d67d..f51b08291 100644 --- a/tests/fixtures/economy_results.py +++ b/tests/fixtures/economy_results.py @@ -8,9 +8,10 @@ follow the writer as PolicyEngine/policyengine-sim-api#1068 changes it (``46c38f07``): one row per code a result's ``constituency_withheld_codes`` and ``local_authority_withheld_codes`` list. A result's ``cliff_impact`` is -the one exception: the report run's four cliff columns are left out, whatever -that writer stores there, since no read uses them, and it becomes a succeeded -``cliff_impacts`` row for each side's simulation run, the rows API v1 reads. +the one exception: the four cliff columns that writer stored on the report +run are left out, since revision 4e30076d4b9f drops them, and it becomes a +succeeded ``cliff_impacts`` row for each side's simulation run, the rows API +v1 reads. Each row is a dict of the table's columns; ``id`` and ``created_at`` are left for the caller. """ diff --git a/tests/integration/privilege_statements.py b/tests/integration/privilege_statements.py index ec22fbf02..3f80dc249 100644 --- a/tests/integration/privilege_statements.py +++ b/tests/integration/privilege_statements.py @@ -13,12 +13,6 @@ columns. Each class maps one table, with the columns of every test that refuses a statement on it; a statement sends only the columns it sets. No code creates tables from these classes: Alembic creates them from the models. - -``ReportColumns`` also maps ``label``, ``ReportRunColumns`` ``trigger`` and the -four older cliff columns, and ``BudgetWindowRunColumns`` its ``trigger``: the -models' mappers leave them out until a revision drops them. No model maps -them, so every test that reads or writes them, or is refused them, sends its -statement through these classes. """ # No ``from __future__ import annotations``: SQLAlchemy reads the classes' @@ -37,7 +31,6 @@ CliffImpact, ReportRun, Simulation, - UserReportRunAssociation, WithheldAreaCode, ) @@ -68,13 +61,12 @@ class SimulationColumns: @named_column_tables.mapped class ReportColumns: - """A report's key version, and its label, which its mapper leaves out.""" + """A report's key version.""" __tablename__ = "reports" id: Mapped[UUID] = mapped_column(primary_key=True) key_version: Mapped[int | None] - label: Mapped[str | None] @named_column_tables.mapped @@ -134,27 +126,20 @@ class LaborSupplyDecileResponseColumns: @named_column_tables.mapped class BudgetWindowRunColumns: - """A new budget-window run's columns, and ``trigger``, which its mapper omits.""" + """A new budget-window run's columns.""" __tablename__ = "budget_window_runs" id: Mapped[UUID] = mapped_column(primary_key=True) report_id: Mapped[UUID] tax_benefit_model_version_id: Mapped[UUID] - trigger: Mapped[str | None] = mapped_column( - _type_of(UserReportRunAssociation, "trigger") - ) recalculate: Mapped[bool] status: Mapped[str] = mapped_column(_type_of(BudgetWindowRun, "status")) @named_column_tables.mapped class ReportRunColumns: - """A new report run's columns, ``trigger`` and the four older cliff columns. - - ``ReportRun``'s mapper leaves ``trigger`` and the cliff columns out until a - revision drops them, so statements that set them go through this class. - """ + """A new report run's columns, and its data version.""" __tablename__ = "report_runs" @@ -164,23 +149,7 @@ class ReportRunColumns: country_package_version: Mapped[str] policyengine_version: Mapped[str] status: Mapped[str] = mapped_column(_type_of(ReportRun, "status")) - trigger: Mapped[str | None] = mapped_column( - _type_of(UserReportRunAssociation, "trigger") - ) - baseline_cliff_gap: Mapped[float | None] - baseline_cliff_share: Mapped[float | None] - reform_cliff_gap: Mapped[float | None] - reform_cliff_share: Mapped[float | None] - - -# The four older cliff columns ``ReportRun``'s mapper leaves out, which only -# ``ReportRunColumns`` maps. -REPORT_RUN_CLIFF_COLUMNS = ( - "baseline_cliff_gap", - "baseline_cliff_share", - "reform_cliff_gap", - "reform_cliff_share", -) + data_version: Mapped[str | None] @named_column_tables.mapped diff --git a/tests/integration/test_alembic_v2_report_column_drops.py b/tests/integration/test_alembic_v2_report_column_drops.py new file mode 100644 index 000000000..0889e3c28 --- /dev/null +++ b/tests/integration/test_alembic_v2_report_column_drops.py @@ -0,0 +1,424 @@ +"""Check the report column drops revision against disposable Postgres. + +Revision 4e30076d4b9f, on the cliff impacts revision bc334f9877b7, drops what +shared report rows no longer hold: ``reports.label``, ``description`` and +``user_id``, ``report_runs.trigger`` and its four cliff columns, and +``budget_window_runs.trigger``, with the foreign key, index and check that +depend on them. The ``v2_report_run_trigger`` type stays, because +``user_report_run_associations`` uses it. The downgrade adds the columns back +without their values. +""" + +from __future__ import annotations + +from copy import deepcopy +from typing import TYPE_CHECKING, Any +from uuid import UUID, uuid4 + +import pytest +from alembic import command +from sqlalchemy import JSON, delete, select +from sqlalchemy.dialects import postgresql +from sqlalchemy.dialects.postgresql.base import PGInspector +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column +from sqlmodel import col + +from policyengine_api.data.v2.migration_target import V2_ALEMBIC_DISPOSABLE_TEST +from policyengine_api.data.v2.models import ( + BudgetWindowRun, + Report, + ReportRun, + Simulation, + SimulationRun, + User, +) +from policyengine_api.data.v2.privilege_reconciliation import ( + DEPLOYMENT_ENVIRONMENT, + run, +) +from policyengine_api.data.v2.settings import V2_MIGRATION_DATABASE_URL +from tests.fixtures.database_sessions import grant, schema_inspector +from tests.fixtures.integration.alembic_v2 import alembic_v2_config +from tests.integration.simulation_rows import ( + RUN_VERSIONS, + PublicApiRows, + add_row, + delete_public_api_rows, + insert_public_api_rows, +) + +if TYPE_CHECKING: + from collections.abc import Iterator + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + from tests.integration.conftest import ManagedV2Roles + +CLIFF_IMPACTS_REVISION = "bc334f9877b7" +REPORT_COLUMN_DROPS_REVISION = "4e30076d4b9f" +DROPPED_COLUMNS = { + "reports": {"label", "description", "user_id"}, + "report_runs": { + "trigger", + "baseline_cliff_gap", + "baseline_cliff_share", + "reform_cliff_gap", + "reform_cliff_share", + }, + "budget_window_runs": {"trigger"}, +} + + +def _existing_enum(type_name: str) -> postgresql.ENUM: + """Return a column type naming an enum type the revisions already created. + + Rows name its values as text, which PostgreSQL checks against the type. + """ + return postgresql.ENUM(name=type_name, create_type=False) + + +class ParentRevisionBase(DeclarativeBase): + """The declarative base of the tables as the parent revision left them.""" + + +class ReportAtParent(ParentRevisionBase): + """A report's required columns, with the per-user ones the revision drops.""" + + __tablename__ = "reports" + + id: Mapped[UUID] = mapped_column(primary_key=True) + label: Mapped[str | None] + description: Mapped[str | None] + user_id: Mapped[UUID | None] + country: Mapped[str] + tax_benefit_model_id: Mapped[UUID] + inputs: Mapped[dict[str, Any]] = mapped_column(JSON) + + +class ReportRunAtParent(ParentRevisionBase): + """A report run's required columns, with its trigger and four cliff columns.""" + + __tablename__ = "report_runs" + + id: Mapped[UUID] = mapped_column(primary_key=True) + report_id: Mapped[UUID] + baseline_simulation_run_id: Mapped[UUID] + country_package_version: Mapped[str] + policyengine_version: Mapped[str] + status: Mapped[str] = mapped_column(_existing_enum("v2_report_run_status")) + trigger: Mapped[str | None] = mapped_column(_existing_enum("v2_report_run_trigger")) + baseline_cliff_gap: Mapped[float | None] + baseline_cliff_share: Mapped[float | None] + reform_cliff_gap: Mapped[float | None] + reform_cliff_share: Mapped[float | None] + + +class BudgetWindowRunAtParent(ParentRevisionBase): + """A budget-window run's required columns, with its trigger.""" + + __tablename__ = "budget_window_runs" + + id: Mapped[UUID] = mapped_column(primary_key=True) + report_id: Mapped[UUID] + tax_benefit_model_version_id: Mapped[UUID] + trigger: Mapped[str | None] = mapped_column(_existing_enum("v2_report_run_trigger")) + recalculate: Mapped[bool] + status: Mapped[str] = mapped_column(_existing_enum("v2_report_run_status")) + + +def _schema_shape(sessions: sessionmaker[Session]) -> dict[str, dict[str, Any]]: + """Reflect every table's columns, keys, indexes and checks, by name.""" + inspector = schema_inspector(sessions) + return { + table_name: { + "columns": { + column["name"]: ( + column["type"].compile(dialect=postgresql.dialect()), + column["nullable"], + column.get("default"), + ) + for column in inspector.get_columns(table_name) + }, + "primary_key": inspector.get_pk_constraint(table_name), + "foreign_keys": { + key["name"]: ( + tuple(key["constrained_columns"]), + key["referred_table"], + key["options"].get("ondelete"), + ) + for key in inspector.get_foreign_keys(table_name) + }, + "unique_constraints": { + unique["name"]: tuple(unique["column_names"]) + for unique in inspector.get_unique_constraints(table_name) + }, + "indexes": { + index["name"]: ( + tuple(index["column_names"]), + index["unique"], + index.get("dialect_options", {}).get("postgresql_where"), + ) + for index in inspector.get_indexes(table_name) + }, + "checks": { + check["name"]: check["sqltext"] + for check in inspector.get_check_constraints(table_name) + }, + } + for table_name in inspector.get_table_names(schema="public") + if table_name != "alembic_version" + } + + +def _enum_labels(sessions: sessionmaker[Session]) -> dict[str, list[str]]: + """Return each enum type in the public schema with its labels in order.""" + inspector = schema_inspector(sessions) + assert isinstance(inspector, PGInspector) + return { + enum_type["name"]: enum_type["labels"] + for enum_type in inspector.get_enums(schema="public") + } + + +def _without_dropped_schema( + parent_shape: dict[str, dict[str, Any]], +) -> dict[str, dict[str, Any]]: + """Return the parent's schema less what the revision should remove.""" + expected = deepcopy(parent_shape) + for table_name, column_names in DROPPED_COLUMNS.items(): + for column_name in column_names: + del expected[table_name]["columns"][column_name] + del expected["reports"]["foreign_keys"]["fk_reports_user_id_users"] + del expected["reports"]["indexes"]["ix_reports_user_id"] + del expected["report_runs"]["checks"]["ck_report_runs_cliff_impact_complete"] + return expected + + +def _privilege_environment( + database_url: str, managed_v2_roles: ManagedV2Roles +) -> dict[str, str]: + """Return what the deploy's privilege steps read.""" + return { + V2_MIGRATION_DATABASE_URL: database_url, + V2_ALEMBIC_DISPOSABLE_TEST: "1", + DEPLOYMENT_ENVIRONMENT: managed_v2_roles.deployment_environment, + } + + +@pytest.fixture +def sessions( + v2_owner_sessions: sessionmaker[Session], + disposable_v2_database_url: str, + managed_v2_roles: ManagedV2Roles, +) -> Iterator[sessionmaker[Session]]: + """Yield the owner's Session factories; leave the database at the v2 head. + + Downgrading to the base removes every table and its grants, so the roles + get theirs back for the tests that run after this one. + """ + try: + yield v2_owner_sessions + finally: + command.upgrade(alembic_v2_config(), "head") + apply_status = run( + "apply", + environ=_privilege_environment( + disposable_v2_database_url, managed_v2_roles + ), + ) + assert apply_status == 0 + + +def _build_parent_schema(sessions: sessionmaker[Session]) -> dict[str, dict[str, Any]]: + """Build the parent revision from the base, without this revision's downgrade.""" + config = alembic_v2_config() + command.upgrade(config, "head") + command.downgrade(config, "base") + command.upgrade(config, CLIFF_IMPACTS_REVISION) + return _schema_shape(sessions) + + +def test_the_revision_drops_only_the_per_user_and_cliff_schema( + sessions: sessionmaker[Session], +) -> None: + parent_shape = _build_parent_schema(sessions) + parent_enums = _enum_labels(sessions) + + command.upgrade(alembic_v2_config(), REPORT_COLUMN_DROPS_REVISION) + + assert _schema_shape(sessions) == _without_dropped_schema(parent_shape) + assert _enum_labels(sessions) == parent_enums + + +def test_the_trigger_type_stays_for_each_users_run_records( + sessions: sessionmaker[Session], +) -> None: + command.upgrade(alembic_v2_config(), REPORT_COLUMN_DROPS_REVISION) + + assert _enum_labels(sessions)["v2_report_run_trigger"] == [ + "initial", + "manual", + "system", + ] + record_columns = _schema_shape(sessions)["user_report_run_associations"]["columns"] + assert record_columns["trigger"][0] == "v2_report_run_trigger" + + +def _store_rows_with_dropped_values( + session: Session, rows: PublicApiRows +) -> dict[str, UUID]: + """Store a report, its run and its window run, each holding dropped values.""" + ids = { + name: uuid4() + for name in ("user", "simulation", "run", "report", "report_run", "window_run") + } + add_row(session, User, id=ids["user"], user_type="standard", primary_country="us") + add_row( + session, + Simulation, + id=ids["simulation"], + simulation_type="economy", + dataset_id=rows.dataset_id, + tax_benefit_model_version_id=rows.version_id, + year=2026, + ) + add_row( + session, + SimulationRun, + id=ids["run"], + simulation_id=ids["simulation"], + tax_benefit_model_version_id=rows.version_id, + year=2026, + status="pending", + **RUN_VERSIONS, + ) + add_row( + session, + ReportAtParent, + id=ids["report"], + label="Stored label", + description="Stored description", + user_id=ids["user"], + country="us", + tax_benefit_model_id=rows.model_id, + inputs={}, + ) + add_row( + session, + ReportRunAtParent, + id=ids["report_run"], + report_id=ids["report"], + baseline_simulation_run_id=ids["run"], + status="pending", + trigger="initial", + baseline_cliff_gap=1.0, + baseline_cliff_share=0.1, + reform_cliff_gap=2.0, + reform_cliff_share=0.2, + **RUN_VERSIONS, + ) + add_row( + session, + BudgetWindowRunAtParent, + id=ids["window_run"], + report_id=ids["report"], + tax_benefit_model_version_id=rows.version_id, + trigger="manual", + recalculate=False, + status="pending", + ) + return ids + + +def _delete_stored_rows(session: Session, ids: dict[str, UUID]) -> None: + """Delete the rows; deleting the report deletes its runs.""" + session.execute(delete(Report).where(col(Report.id) == ids["report"])) + session.execute(delete(SimulationRun).where(col(SimulationRun.id) == ids["run"])) + session.execute(delete(Simulation).where(col(Simulation.id) == ids["simulation"])) + session.execute(delete(User).where(col(User.id) == ids["user"])) + + +def test_rows_survive_the_drop_and_a_downgrade_restores_columns_without_values( + sessions: sessionmaker[Session], +) -> None: + """The columns come back empty: a downgrade can't restore what was dropped.""" + config = alembic_v2_config() + parent_shape = _build_parent_schema(sessions) + with sessions.begin() as session: + public_api_rows = insert_public_api_rows(session) + ids = _store_rows_with_dropped_values(session, public_api_rows) + try: + command.upgrade(config, REPORT_COLUMN_DROPS_REVISION) + + with sessions() as session: + kept_rows = session.execute( + select( + col(Report.country), + col(ReportRun.status), + col(BudgetWindowRun.status), + ) + .select_from(Report) + .join(ReportRun, col(ReportRun.report_id) == col(Report.id)) + .join(BudgetWindowRun, col(BudgetWindowRun.report_id) == col(Report.id)) + .where(col(Report.id) == ids["report"]) + ).one() + assert tuple(kept_rows) == ("us", "pending", "pending") + + command.downgrade(config, CLIFF_IMPACTS_REVISION) + + assert _schema_shape(sessions) == parent_shape + with sessions() as session: + restored_values = session.execute( + select( + ReportAtParent.label, + ReportAtParent.description, + ReportAtParent.user_id, + ReportRunAtParent.trigger, + ReportRunAtParent.baseline_cliff_gap, + ReportRunAtParent.baseline_cliff_share, + ReportRunAtParent.reform_cliff_gap, + ReportRunAtParent.reform_cliff_share, + BudgetWindowRunAtParent.trigger, + ) + .select_from(ReportAtParent) + .join( + ReportRunAtParent, + ReportRunAtParent.report_id == ReportAtParent.id, + ) + .join( + BudgetWindowRunAtParent, + BudgetWindowRunAtParent.report_id == ReportAtParent.id, + ) + .where(ReportAtParent.id == ids["report"]) + ).one() + assert set(restored_values) == {None} + finally: + with sessions.begin() as session: + _delete_stored_rows(session, ids) + delete_public_api_rows(session, public_api_rows) + + +def test_the_deploys_privilege_steps_pass_after_the_upgrade( + sessions: sessionmaker[Session], + disposable_v2_database_url: str, + managed_v2_roles: ManagedV2Roles, +) -> None: + """``apply`` and ``verify`` pass when the Modal worker held the cliff grants.""" + config = alembic_v2_config() + command.upgrade(config, "head") + command.downgrade(config, CLIFF_IMPACTS_REVISION) + cliff_columns = ", ".join(sorted(DROPPED_COLUMNS["report_runs"] - {"trigger"})) + with sessions.begin() as session: + grant( + session, + f"UPDATE ({cliff_columns})", + on=ReportRunAtParent, + to=managed_v2_roles.modal_worker, + ) + + command.upgrade(config, REPORT_COLUMN_DROPS_REVISION) + environ = _privilege_environment(disposable_v2_database_url, managed_v2_roles) + + assert run("apply", environ=environ) == 0 + assert run("verify", environ=environ) == 0 diff --git a/tests/integration/test_alembic_v2_simulation_runs.py b/tests/integration/test_alembic_v2_simulation_runs.py index 3d6ca4e34..73b9c1d4b 100644 --- a/tests/integration/test_alembic_v2_simulation_runs.py +++ b/tests/integration/test_alembic_v2_simulation_runs.py @@ -44,7 +44,6 @@ ) from tests.fixtures.database_sessions import schema_inspector from tests.fixtures.integration.alembic_v2 import table_columns -from tests.integration.privilege_statements import ReportRunColumns, update_row from tests.integration.simulation_rows import ( RUN_VERSIONS, PublicApiRows, @@ -108,7 +107,6 @@ "RESTRICT", ), ("simulations", "region_id"): ("regions", "SET NULL"), - ("reports", "user_id"): ("users", "SET NULL"), ("reports", "tax_benefit_model_id"): ("tax_benefit_models", "RESTRICT"), ("reports", "policy_id"): ("policies", "SET NULL"), ("reports", "household_id"): ("households", "RESTRICT"), @@ -274,9 +272,6 @@ def test_head_keeps_the_foreign_keys_to_the_public_api_tables( } assert public_api_keys == PUBLIC_API_FOREIGN_KEYS - assert {"ix_reports_user_id"} <= { - index["name"] for index in inspector.get_indexes("reports") - } def _count(session: Session, column: Mapped[Any], value: object) -> int: @@ -589,7 +584,7 @@ def test_results_are_unique_per_run_and_name_runs_that_exist( ) -def test_a_report_runs_labor_supply_and_cliff_impact_are_typed( +def test_a_report_runs_labor_supply_and_spm_receipt_are_typed( session: Session, public_api_rows: PublicApiRows ) -> None: report_run_id = _insert_report_run( @@ -644,22 +639,6 @@ def test_a_report_runs_labor_supply_and_cliff_impact_are_typed( report_run_id=report_run_id, decile=1, ) - # ReportRun's mapper leaves the four cliff columns out until a revision - # drops them, so they are set through ReportRunColumns. - with refused(session, match="ck_report_runs_cliff_impact_complete"): - session.execute( - update_row(ReportRunColumns, report_run_id, baseline_cliff_gap=1.0) - ) - session.execute( - update_row( - ReportRunColumns, - report_run_id, - baseline_cliff_gap=1.0, - baseline_cliff_share=0.1, - reform_cliff_gap=2.0, - reform_cliff_share=0.2, - ) - ) _update_report_run( session, report_run_id, diff --git a/tests/integration/test_v2_report_cliff_reads.py b/tests/integration/test_v2_report_cliff_reads.py index 6805dcd93..af83a4d03 100644 --- a/tests/integration/test_v2_report_cliff_reads.py +++ b/tests/integration/test_v2_report_cliff_reads.py @@ -33,11 +33,6 @@ from policyengine_api.services.v2.stored_reports.services import V2StoredReportService from tests.fixtures.database_sessions import recorded_statements from tests.fixtures.economy_results import uk_economy_result, us_economy_result -from tests.integration.privilege_statements import ( - REPORT_RUN_CLIFF_COLUMNS, - ReportRunColumns, - update_row, -) from tests.integration.stored_report_rows import ( STARTED_AT, RunSettings, @@ -59,6 +54,12 @@ CURRENT_VERSIONS = {"country_package_version": "1.5.0", "policyengine_version": "4.2.0"} FAILURE = "cliff_calculation_failed: the calculation raised an error" +REPORT_RUN_CLIFF_COLUMNS = ( + "baseline_cliff_gap", + "baseline_cliff_share", + "reform_cliff_gap", + "reform_cliff_share", +) def current_versions(country_id: str) -> PackageVersions: @@ -155,49 +156,17 @@ def test_a_succeeded_run_reads_its_simulation_runs_cliff_results( } -def test_a_report_runs_own_cliff_columns_are_not_read( - owner_sessions: sessionmaker[Session], - catalogs: dict[str, CatalogRows], - client: TestClient, -) -> None: - catalog = catalogs["uk"] - with owner_sessions.begin() as session: - report = store_report(session, catalog) - run_ids = store_report_run( - session, - catalog, - report, - RunSettings(versions=CURRENT_VERSIONS), - result=uk_economy_result(), - ) - # The report run's own columns hold cliffs; its simulation runs have - # none. ReportRun's mapper leaves these columns out, so they are set - # through ReportRunColumns. - session.execute( - update_row( - ReportRunColumns, - run_ids.report_run_id, - baseline_cliff_gap=1.0, - baseline_cliff_share=0.1, - reform_cliff_gap=2.0, - reform_cliff_share=0.2, - ) - ) - - item = read_report(client, report.report_id, "uk") - - assert item["status"] == "succeeded" - assert item["result"]["cliff_impact"] is None - assert item["cliffs"]["status"] == "not_calculated" - - def test_reading_a_report_and_its_runs_names_no_report_run_cliff_column( owner_sessions: sessionmaker[Session], catalogs: dict[str, CatalogRows], client: TestClient, runtime_sessions: sessionmaker[Session], ) -> None: - """No statement the read sends names a report run's own cliff columns.""" + """No statement the read sends names the cliff columns report runs held. + + Revision 4e30076d4b9f drops them, so a statement naming one would fail the + read; the scan also says which column it named. + """ with owner_sessions.begin() as session: report = store_report(session, catalogs["us"]) store_report_run( diff --git a/tests/integration/test_v2_shared_report_rows.py b/tests/integration/test_v2_shared_report_rows.py index 480e58834..278483ccb 100644 --- a/tests/integration/test_v2_shared_report_rows.py +++ b/tests/integration/test_v2_shared_report_rows.py @@ -50,9 +50,7 @@ ) from tests.fixtures.database_sessions import act_as, act_as_owner, query_plan from tests.integration.privilege_statements import ( - BudgetWindowRunColumns, ReportColumns, - ReportRunColumns, SimulationColumns, unfailed, update_row, @@ -457,15 +455,39 @@ def test_the_public_api_finds_reports_by_the_shared_key_alone( @pytest.mark.parametrize( - ("table", "key_columns"), + ("table", "key_columns", "constraint"), [ - ("simulations", {"key_version": 1, "definition_key": NATIONAL_KEY.upper()}), - ("simulations", {"key_version": 1, "definition_key": NATIONAL_KEY[:63]}), + ( + "simulations", + {"key_version": 1, "definition_key": NATIONAL_KEY.upper()}, + "ck_simulations_definition_key", + ), + ( + "simulations", + {"key_version": 1, "definition_key": NATIONAL_KEY[:63]}, + "ck_simulations_definition_key", + ), # Lowercase, 64 characters, but not hexadecimal. - ("simulations", {"key_version": 1, "definition_key": "g" * 64}), - ("simulations", {"key_version": 0, "definition_key": NATIONAL_KEY}), - ("simulations", {"key_version": None, "definition_key": NATIONAL_KEY}), - ("simulations", {"key_version": 1, "definition_key": None}), + ( + "simulations", + {"key_version": 1, "definition_key": "g" * 64}, + "ck_simulations_definition_key", + ), + ( + "simulations", + {"key_version": 0, "definition_key": NATIONAL_KEY}, + "ck_simulations_key_version", + ), + ( + "simulations", + {"key_version": None, "definition_key": NATIONAL_KEY}, + "ck_simulations_keys_complete", + ), + ( + "simulations", + {"key_version": 1, "definition_key": None}, + "ck_simulations_keys_complete", + ), ( "reports", { @@ -473,6 +495,7 @@ def test_the_public_api_finds_reports_by_the_shared_key_alone( "definition_key": NATIONAL_KEY, "dataset_independent_key": None, }, + "ck_reports_keys_complete", ), ( "reports", @@ -481,6 +504,7 @@ def test_the_public_api_finds_reports_by_the_shared_key_alone( "definition_key": None, "dataset_independent_key": DATASET_INDEPENDENT_KEY, }, + "ck_reports_keys_complete", ), ( "reports", @@ -489,6 +513,7 @@ def test_the_public_api_finds_reports_by_the_shared_key_alone( "definition_key": NATIONAL_KEY, "dataset_independent_key": DATASET_INDEPENDENT_KEY.upper(), }, + "ck_reports_dataset_independent_key", ), ], ) @@ -497,6 +522,7 @@ def test_a_malformed_or_incomplete_key_is_refused( public_api_rows: PublicApiRows, table: str, key_columns: dict[str, object], + constraint: str, ) -> None: columns: dict[str, object] = ( { @@ -513,7 +539,9 @@ def test_a_malformed_or_incomplete_key_is_refused( ) columns |= {"id": uuid4(), "year": 2026, **key_columns} - with refused(session, IntegrityError, match="violates check constraint"): + with refused( + session, IntegrityError, match=f'violates check constraint "{constraint}"' + ): add_row(session, KEYED_MODELS[table], **columns) @@ -660,7 +688,7 @@ def window_run( def test_the_simulation_service_writes_shared_rows_without_per_user_columns( session: Session, managed_v2_roles: ManagedV2Roles, public_api_rows: PublicApiRows ) -> None: - """A report without a label, and runs without a trigger, are stored as such.""" + """The service stores reports and runs with no label, user or trigger.""" simulation_id = _simulation(session, public_api_rows, NATIONAL_KEY) act_as(session, managed_v2_roles.simulation_service) baseline_run_id = _simulation_run(session, public_api_rows, simulation_id) @@ -696,20 +724,13 @@ def test_the_simulation_service_writes_shared_rows_without_per_user_columns( act_as(session, managed_v2_roles.runtime) stored = session.execute( - select( - ReportColumns.label, - ReportRunColumns.trigger, - BudgetWindowRunColumns.trigger, - ) - .select_from(ReportColumns) - .join(ReportRunColumns, ReportRunColumns.report_id == ReportColumns.id) - .join( - BudgetWindowRunColumns, - BudgetWindowRunColumns.report_id == ReportColumns.id, - ) - .where(ReportColumns.id == report_id) + select(col(Report.id), col(ReportRun.id), col(BudgetWindowRun.id)) + .select_from(Report) + .join(ReportRun, col(ReportRun.report_id) == col(Report.id)) + .join(BudgetWindowRun, col(BudgetWindowRun.report_id) == col(Report.id)) + .where(col(Report.id) == report_id) ).one() - assert tuple(stored) == (None, None, None) + assert tuple(stored) == (report_id, report_run_id, window_run_id) def test_no_simulation_role_changes_a_rows_key_or_a_runs_forced_marker( diff --git a/tests/integration/test_v2_simulation_role_privileges.py b/tests/integration/test_v2_simulation_role_privileges.py index 78f6458d7..7f591fa4a 100644 --- a/tests/integration/test_v2_simulation_role_privileges.py +++ b/tests/integration/test_v2_simulation_role_privileges.py @@ -17,11 +17,10 @@ which map only the columns they name. The other refused updates use the models: both simulation roles may update ``updated_at`` on the run, budget-window run and cliff calculation tables, and ``poverty`` and ``withheld_area_codes`` -have no ``updated_at``. A column a model's mapper leaves out, such as a report -run's ``trigger`` and four older cliff columns, or a budget-window run's -``trigger``, until a revision drops them, has no statement through the model, -so its writes and refusals go through the class that maps it, -``ReportRunColumns`` or ``BudgetWindowRunColumns``. +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. """ from __future__ import annotations @@ -263,7 +262,7 @@ def test_the_simulation_service_creates_rows_and_records_only_its_calls( update_row(SimulationRun, ids["run"], started_at=func.now()), update_row(SimulationRun, ids["run"], output_uri="gs://bucket/run"), update_row(SimulationRun, ids["run"], year=2027), - update_row(ReportRunColumns, ids["report_run"], baseline_cliff_gap=1.0), + update_row(ReportRunColumns, ids["report_run"], data_version="1.0.0"), insert(PovertyColumns).values( id=uuid4(), simulation_run_id=ids["run"], @@ -315,16 +314,6 @@ def test_modal_workers_write_their_run_status_and_results_only( updated_at=func.now(), ) ) - session.execute( - update_row( - ReportRunColumns, - ids["report_run"], - baseline_cliff_gap=1.0, - baseline_cliff_share=0.1, - reform_cliff_gap=2.0, - reform_cliff_share=0.2, - ) - ) add_row( session, LaborSupplyDecileResponse, @@ -358,7 +347,6 @@ def test_modal_workers_write_their_run_status_and_results_only( id=uuid4(), report_id=ids["report"], tax_benefit_model_version_id=public_api_rows.version_id, - trigger="manual", recalculate=True, status="pending", ), @@ -550,7 +538,6 @@ def test_modal_workers_start_finish_and_fail_budget_windows( assert started_windows == [window_id, failing_window_id] assert (succeeded_window, failed_window) == (window_id, failing_window_id) for statement in ( - update_row(BudgetWindowRunColumns, window_id, trigger="manual"), update_row(BudgetWindowRun, window_id, recalculate=False), update_row( BudgetWindowRun, @@ -620,16 +607,13 @@ def test_the_public_api_reads_runs_and_results_but_writes_neither( country_package_version="1.0.0", policyengine_version="4.0.0", status="pending", - trigger="initial", ), ) -# The class that maps the columns each model's mapper leaves out. -UNMAPPED_COLUMN_CLASSES: dict[type[Any], type[Any]] = { - BudgetWindowRun: BudgetWindowRunColumns, - ReportRun: ReportRunColumns, -} +# The class that maps the columns each model's mapper leaves out. Since +# revision 4e30076d4b9f no model leaves a column out. +UNMAPPED_COLUMN_CLASSES: dict[type[Any], type[Any]] = {} @pytest.mark.parametrize("role_kind", ["simulation_service", "modal_worker"]) diff --git a/tests/integration/test_v2_user_identity_persistence.py b/tests/integration/test_v2_user_identity_persistence.py index 27fa76e79..c31a7e674 100644 --- a/tests/integration/test_v2_user_identity_persistence.py +++ b/tests/integration/test_v2_user_identity_persistence.py @@ -25,6 +25,7 @@ from policyengine_api.data.v2 import user_association_migration_qualification from policyengine_api.data.v2.models import ( LegacyUserMapping, + Report, User, UserHouseholdAssociation, UserIdentity, @@ -83,6 +84,12 @@ from policyengine_api.services.v2.user_simulations.types import ( UserSimulationCreateFields, ) +from tests.fixtures.database_sessions import schema_inspector +from tests.integration.simulation_rows import ( + add_row, + delete_public_api_rows, + insert_public_api_rows, +) from tests.unit.v2.user_service_support import default_legacy_references if TYPE_CHECKING: @@ -748,6 +755,54 @@ def delete_user(self, subject: str) -> None: ) +def test_account_deletion_leaves_reports_which_name_no_user( + sessions, v2_owner_sessions: sessionmaker[Session] +) -> None: + """A report is shared, so deleting an account neither needs nor changes it.""" + + class NoOpDeleter: + def prepare_deletion(self) -> None: + return None + + def delete_user(self, subject: str) -> None: + return None + + report_id = uuid4() + with v2_owner_sessions.begin() as session: + public_api_rows = insert_public_api_rows(session) + add_row( + session, + Report, + id=report_id, + country="us", + tax_benefit_model_id=public_api_rows.model_id, + inputs={}, + ) + try: + principal = _principal(sessions, "google-oauth2|report-reader") + accounts = V2AccountService( + AccountDatabaseSession(sessions), + auth0_user_deleter_factory=NoOpDeleter, + ) + user_id = accounts.get_account(principal=principal, country_id="us").id + + accounts.delete_account(principal=principal) + + report_columns = { + column["name"] + for column in schema_inspector(v2_owner_sessions).get_columns("reports") + } + assert "user_id" not in report_columns + with sessions() as session: + assert session.get(User, user_id) is None + with v2_owner_sessions() as session: + assert session.get(Report, report_id) is not None + finally: + with v2_owner_sessions.begin() as session: + session.execute(delete(Report).where(Report.id == report_id)) + delete_public_api_rows(session, public_api_rows) + + @pytest.mark.usefixtures("sessions") def test_qualification_reads_counts_in_a_read_only_transaction( disposable_v2_database_url: str, diff --git a/tests/unit/test_alembic_workflows.py b/tests/unit/test_alembic_workflows.py index 9ac642958..24dc8d21b 100644 --- a/tests/unit/test_alembic_workflows.py +++ b/tests/unit/test_alembic_workflows.py @@ -216,6 +216,7 @@ def test_reusable_v2_alembic_check_uses_only_disposable_postgres(): assert "test_alembic_v2_shared_report_keys.py" in lifecycle_script assert "test_alembic_v2_cliff_impacts.py" in lifecycle_script assert "test_alembic_v2_dynamics.py" in lifecycle_script + assert "test_alembic_v2_report_column_drops.py" in lifecycle_script assert "redis:7.2-alpine" not in workflow assert "RUNTIME_CACHE_TEST_URL" not in workflow assert "test_v2_catalog_installed.py" not in workflow diff --git a/tests/unit/v2/test_alembic_v2_revisions.py b/tests/unit/v2/test_alembic_v2_revisions.py index 6231fa35e..cf87a3b36 100644 --- a/tests/unit/v2/test_alembic_v2_revisions.py +++ b/tests/unit/v2/test_alembic_v2_revisions.py @@ -70,16 +70,20 @@ # The dynamics revision, on the user invitations revision, and parent of the # cliff impacts revision. DYNAMICS_REVISION = "9d1d12a7ac58" -# The cliff impacts revision, on the dynamics revision. +# The cliff impacts revision, on the dynamics revision, and parent of the +# report column drops revision. CLIFF_IMPACTS_REVISION = "bc334f9877b7" +# The report column drops revision, on the cliff impacts revision. +REPORT_COLUMN_DROPS_REVISION = "4e30076d4b9f" def test_v2_revision_chain_has_generated_policy_and_user_identity_changes() -> None: config = Config(str(REPO / "alembic-v2.ini")) script = ScriptDirectory.from_config(config) assert script.get_heads() == [V2_ALEMBIC_HEAD_REVISION] - assert V2_ALEMBIC_HEAD_REVISION == CLIFF_IMPACTS_REVISION + assert V2_ALEMBIC_HEAD_REVISION == REPORT_COLUMN_DROPS_REVISION assert [revision.revision for revision in script.walk_revisions()] == [ + REPORT_COLUMN_DROPS_REVISION, CLIFF_IMPACTS_REVISION, DYNAMICS_REVISION, USER_INVITATIONS_REVISION, @@ -1230,7 +1234,6 @@ def test_cliff_impacts_revision_creates_only_its_table_with_one_correction() -> ] downgrade = revision[revision.index("def downgrade()") :] - assert V2_ALEMBIC_HEAD_REVISION == CLIFF_IMPACTS_REVISION assert ( "Generation: uv run alembic -c alembic-v2.ini revision --autogenerate" in revision @@ -1265,3 +1268,60 @@ def test_cliff_impacts_revision_creates_only_its_table_with_one_correction() -> assert ".drop(op.get_bind())" not in body assert "op.alter_column(" not in upgrade assert "op.add_column(" not in upgrade + + +def test_report_column_drops_revision_drops_only_the_named_columns() -> None: + """The revision after cliff impacts drops what shared report rows don't hold. + + It is generated, removes the nine columns with the key, index and check + that depend on them, writes no data, and its downgrade adds the columns + back, empty. + """ + (path,) = (REPO / "migrations/v2/versions").glob( + f"{REPORT_COLUMN_DROPS_REVISION}_*.py" + ) + revision = path.read_text(encoding="utf-8") + upgrade = revision[ + revision.index("def upgrade()") : revision.index("def downgrade()") + ] + downgrade = revision[revision.index("def downgrade()") :] + dropped_columns = [ + ("budget_window_runs", "trigger"), + ("report_runs", "baseline_cliff_gap"), + ("report_runs", "baseline_cliff_share"), + ("report_runs", "reform_cliff_gap"), + ("report_runs", "reform_cliff_share"), + ("report_runs", "trigger"), + ("reports", "description"), + ("reports", "label"), + ("reports", "user_id"), + ] + + assert ( + "Generation: uv run alembic -c alembic-v2.ini revision --autogenerate" + in revision + ) + assert re.search( + rf"""down_revision: Union\[str, None\] = ["']{CLIFF_IMPACTS_REVISION}["']""", + revision, + ) + drop_column_call = r"""op\.drop_column\(\s*["'](\w+)["'],\s*["'](\w+)["']""" + add_column_call = ( + r"""op\.add_column\(\s*["'](\w+)["'],\s*sa\.Column\(\s*["'](\w+)["']""" + ) + assert sorted(re.findall(drop_column_call, upgrade)) == dropped_columns + assert sorted(re.findall(add_column_call, downgrade)) == dropped_columns + # The one correction restores the parentheses autogenerate strips. + assert revision.count("Post-generation correction:") == 1 + assert ( + "'(baseline_cliff_gap IS NULL) = (baseline_cliff_share IS NULL) " + "AND (baseline_cliff_gap IS NULL) = (reform_cliff_gap IS NULL) " + "AND (baseline_cliff_gap IS NULL) = (reform_cliff_share IS NULL)'" + ) in downgrade + assert "ix_reports_user_id" in upgrade + assert "fk_reports_user_id_users" in upgrade + assert "ck_report_runs_cliff_impact_complete" in upgrade + for body in (upgrade, downgrade): + assert "op.execute(" not in body + assert "op.bulk_insert(" not in body + assert "op.drop_table(" not in body diff --git a/tests/unit/v2/test_economy_result_rebuild.py b/tests/unit/v2/test_economy_result_rebuild.py index 459377278..76923bc40 100644 --- a/tests/unit/v2/test_economy_result_rebuild.py +++ b/tests/unit/v2/test_economy_result_rebuild.py @@ -6,9 +6,10 @@ writer itself stored at a named commit (``scripts/generate_economy_result_golden.py``), so a rebuild that matches it reverses the real writer, and a change in the writer fails once the file is -generated again. A report run's own cliff columns are not read: a result's -cliff impact comes from its two simulation runs' cliff calculations, so the -golden rows rebuild their results without one, whatever those columns hold. +generated again. The cliff columns the writer stored on its report run, +which revision 4e30076d4b9f drops, are left out: a result's cliff impact +comes from its two simulation runs' cliff calculations, so the golden rows +rebuild their results without one, whatever those columns held. """ from __future__ import annotations @@ -76,7 +77,7 @@ "withheld_area_codes": WithheldAreaCode, "cliff_impacts": CliffImpact, } -# The report run's own cliff columns, which no read uses: C1 ยท 41 drops them. +# The cliff columns report runs held when the golden rows were recorded. REPORT_RUN_CLIFF_COLUMNS = ( "baseline_cliff_gap", "baseline_cliff_share", diff --git a/tests/unit/v2/test_model_persistence.py b/tests/unit/v2/test_model_persistence.py index 3fa01a7cc..e492687d1 100644 --- a/tests/unit/v2/test_model_persistence.py +++ b/tests/unit/v2/test_model_persistence.py @@ -95,7 +95,6 @@ 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_privilege_manifest.py b/tests/unit/v2/test_privilege_manifest.py index 5e138cd34..87dba159c 100644 --- a/tests/unit/v2/test_privilege_manifest.py +++ b/tests/unit/v2/test_privilege_manifest.py @@ -77,10 +77,6 @@ "simulation_runs": frozenset({"output_uri", "output_sha256", "household_result"}), "report_runs": frozenset( { - "baseline_cliff_gap", - "baseline_cliff_share", - "reform_cliff_gap", - "reform_cliff_share", "spm_provenance", "data_version", } @@ -129,7 +125,6 @@ "year", "country_package_version", "policyengine_version", - "trigger", "idempotency_key", "forced", } @@ -152,7 +147,6 @@ "report_id", "tax_benefit_model_version_id", "policyengine_version", - "trigger", "recalculate", } ), @@ -229,8 +223,7 @@ def _missing(relative_path: str, role: str) -> list[str]: def _column_keys_by_table() -> dict[str, set[str]]: """Return the names of each v2 table's columns, as SQLite's copy stores them. - A grant is on the table's columns, which include those a mapper leaves - out, such as a report run's four older cliff columns. + A grant is on the table's columns, which include any a mapper leaves out. """ return {name: set(table.columns) for name, table in stored_v2_schema().items()} diff --git a/tests/unit/v2/test_report_column_mapping.py b/tests/unit/v2/test_report_column_mapping.py deleted file mode 100644 index 3c3f7ee24..000000000 --- a/tests/unit/v2/test_report_column_mapping.py +++ /dev/null @@ -1,90 +0,0 @@ -"""API v1's models leave out the report columns a later revision drops. - -The deploy upgrades the database before new code takes traffic, so the release -serving during that upgrade must not name a column it removes. The tables keep -the columns until then: each stays a SQLModel field, as rule -``api.data.orm-only`` requires of every column, and ``exclude_properties`` -leaves it out of the mapper, so the models neither select nor write it. -""" - -import pytest -import sqlalchemy as sa -from pydantic_core import PydanticUndefined -from sqlmodel import select - -from policyengine_api.data.v2.models import ( - BudgetWindowRun, - Report, - ReportRun, - User, -) -from tests.unit.v2.v2_schema_reading import model_columns, stored_v2_table - -UNMAPPED_COLUMNS = [ - (Report, "label"), - (Report, "description"), - (Report, "user_id"), - (ReportRun, "trigger"), - (BudgetWindowRun, "trigger"), -] - - -@pytest.mark.parametrize(("model", "column_name"), UNMAPPED_COLUMNS) -def test_a_whole_row_read_names_no_unmapped_column( - model: type, column_name: str -) -> None: - selected_names = {column.name for column in select(model).selected_columns} - - assert column_name not in selected_names - - -@pytest.mark.parametrize(("model", "column_name"), UNMAPPED_COLUMNS) -def test_the_mapper_leaves_out_an_unmapped_column( - model: type, column_name: str -) -> None: - mapper = sa.inspect(model) - - assert column_name in mapper.exclude_properties - assert column_name not in mapper.column_attrs - - -@pytest.mark.parametrize(("model", "column_name"), UNMAPPED_COLUMNS) -def test_the_table_keeps_an_unmapped_column_until_a_revision_drops_it( - model: type, column_name: str -) -> None: - stored_column = stored_v2_table(model.__tablename__).columns[column_name] - field = model.model_fields[column_name] - column_arguments = getattr(field, "sa_column_kwargs", None) - - assert stored_column.nullable - assert field.default is None - assert column_arguments in (None, PydanticUndefined) - - -@pytest.mark.parametrize("model", [ReportRun, BudgetWindowRun]) -def test_a_runs_trigger_keeps_the_type_users_run_records_share(model: type) -> None: - trigger_type = model.model_fields["trigger"].sa_type - record_trigger_type = model_columns("user_report_run_associations").trigger.type - - assert isinstance(trigger_type, sa.Enum) - assert isinstance(record_trigger_type, sa.Enum) - assert trigger_type.name == record_trigger_type.name == "v2_report_run_trigger" - assert trigger_type.enums == record_trigger_type.enums - - -def test_the_reports_user_key_and_index_stay_with_the_column() -> None: - reports = stored_v2_table("reports") - - (user_key,) = ( - foreign_key - for foreign_key in reports.foreign_keys - if foreign_key.columns == ("user_id",) - ) - assert user_key.targets == ("users.id",) - assert user_key.ondelete == "SET NULL" - assert reports.index_columns["ix_reports_user_id"] == ("user_id",) - - -def test_reports_and_users_have_no_relationship() -> None: - assert "user" not in Report.__sqlmodel_relationships__ - assert "reports" not in User.__sqlmodel_relationships__ diff --git a/tests/unit/v2/test_shared_report_models.py b/tests/unit/v2/test_shared_report_models.py index 4d27c03cb..ff673bdbe 100644 --- a/tests/unit/v2/test_shared_report_models.py +++ b/tests/unit/v2/test_shared_report_models.py @@ -219,19 +219,21 @@ def window_run( ("table_name", "column_name"), [ ("reports", "label"), + ("reports", "description"), + ("reports", "user_id"), ("report_runs", "trigger"), ("budget_window_runs", "trigger"), ], ) -def test_per_user_columns_of_shared_rows_need_no_value( +def test_shared_rows_hold_no_per_user_columns( table_name: str, column_name: str ) -> None: - """A shared row describes no one caller, so the simulation service may omit them. + """A shared row describes no one caller. - They go in a later revision; until then the table keeps them nullable, so - a row written without them is stored. + A report's name is on each user's saved report, and a run's trigger on + each user's record of the run. """ - assert stored_v2_table(table_name).columns[column_name].nullable + assert column_name not in stored_v2_table(table_name).columns def test_user_report_run_associations_record_each_users_request_for_a_run() -> None: diff --git a/tests/unit/v2/test_simulation_run_models.py b/tests/unit/v2/test_simulation_run_models.py index 228d4b43e..baa50473d 100644 --- a/tests/unit/v2/test_simulation_run_models.py +++ b/tests/unit/v2/test_simulation_run_models.py @@ -7,12 +7,9 @@ Columns are read from the models' mappers, and keys, constraints and indexes from SQLite's copy of the schema (tests/unit/v2/v2_schema_reading.py), as are -the columns a mapper leaves out, such as a report run's four older cliff -columns. +the columns revision 4e30076d4b9f dropped, which no table holds. """ -from uuid import uuid4 - import sqlalchemy as sa from sqlalchemy.dialects import postgresql @@ -20,12 +17,12 @@ BudgetWindowRun, LaborSupplyDecileResponse, LaborSupplyResponse, + Report, ReportRun, SimulationRun, + User, ) from tests.fixtures.database_sessions import ( - recorded_statements, - sqlite_v2_sessions, v2_schema_statements, ) from tests.unit.v2.v2_schema_reading import ( @@ -38,7 +35,7 @@ ) RUN_STATUSES = ["pending", "running", "succeeded", "failed"] -# The baseline's and reform's cliff gap and share, stored together or not at all. +# A report run's cliffs are its simulation runs' cliff results, not its columns. CLIFF_IMPACT_COLUMNS = ( "baseline_cliff_gap", "baseline_cliff_share", @@ -107,7 +104,6 @@ "RESTRICT", ), ("simulations", "region_id"): ("regions", "SET NULL"), - ("reports", "user_id"): ("users", "SET NULL"), ("reports", "tax_benefit_model_id"): ("tax_benefit_models", "RESTRICT"), ("reports", "policy_id"): ("policies", "SET NULL"), ("reports", "household_id"): ("households", "RESTRICT"), @@ -282,19 +278,13 @@ def test_report_runs_record_their_modal_call() -> None: assert "report_run_comparisons" not in stored_v2_schema() -def test_report_runs_record_cliff_impact_spm_receipt_and_data_version() -> None: - """The comparison parts with no result table are typed, except the receipt. - - The four cliff columns are read from the stored table: the mapper leaves - them out. - """ +def test_report_runs_record_their_spm_receipt_and_data_version_but_no_cliffs() -> None: + """The comparison parts with no result table are typed, except the receipt.""" report_runs = model_columns("report_runs") stored_columns = stored_v2_table("report_runs").columns - for column_name in CLIFF_IMPACT_COLUMNS: - assert stored_columns[column_name].nullable, column_name - assert isinstance(stored_columns[column_name].type, sa.Float), column_name - assert "ck_report_runs_cliff_impact_complete" in _check_names("report_runs") + assert set(stored_columns).isdisjoint(CLIFF_IMPACT_COLUMNS) + assert "ck_report_runs_cliff_impact_complete" not in _check_names("report_runs") assert report_runs.spm_provenance.nullable spm_type = report_runs.spm_provenance.type assert isinstance(spm_type.dialect_impl(postgresql.dialect()), postgresql.JSONB) @@ -303,51 +293,16 @@ def test_report_runs_record_cliff_impact_spm_receipt_and_data_version() -> None: assert {"labor_supply_result", "cliff_impact_result"}.isdisjoint(report_runs.keys()) -def test_report_runs_load_none_of_their_cliff_columns() -> None: - """A run's cliffs are its simulation runs', so API v1 leaves these columns alone. - - They stay SQLModel fields, as rule ``api.data.orm-only`` requires of every - column, with no Core column of their own, and the mapper leaves them out - until a revision drops them. - """ +def test_report_runs_load_and_write_none_of_their_cliff_columns() -> None: + """A run's cliffs are its simulation runs', so the model has no cliff columns.""" loaded_columns = str(sa.select(ReportRun).compile(dialect=postgresql.dialect())) assert [name for name in CLIFF_IMPACT_COLUMNS if name in loaded_columns] == [] assert set(CLIFF_IMPACT_COLUMNS).isdisjoint( sa.inspect(ReportRun).column_attrs.keys() ) - assert set(CLIFF_IMPACT_COLUMNS) <= set(ReportRun.model_fields) - core_columns = [ - argument - for argument in ReportRun.__table_args__ - if isinstance(argument, sa.Column) - ] - assert core_columns == [] - - -def test_storing_a_report_run_writes_none_of_its_cliff_columns() -> None: - report_run = ReportRun( - report_id=uuid4(), - baseline_simulation_run_id=uuid4(), - reform_simulation_run_id=uuid4(), - country_package_version="1.0.0", - policyengine_version="4.2.0", - baseline_cliff_gap=1.5, - baseline_cliff_share=0.1, - reform_cliff_gap=2.5, - reform_cliff_share=0.2, - ) - - with ( - sqlite_v2_sessions() as sessions, - recorded_statements(sessions) as statements, - sessions.begin() as session, - ): - session.add(report_run) - - (stored,) = [statement for statement in statements if "INSERT" in statement] - assert "report_runs" in stored - assert [name for name in CLIFF_IMPACT_COLUMNS if name in stored] == [] + assert set(CLIFF_IMPACT_COLUMNS).isdisjoint(ReportRun.model_fields) + assert [name for name in CLIFF_IMPACT_COLUMNS if hasattr(ReportRun, name)] == [] def test_labor_supply_responses_have_one_typed_row_per_report_run() -> None: @@ -669,9 +624,12 @@ def test_simulation_tables_keep_foreign_keys_to_the_rows_they_name() -> None: assert set(tables) >= SIMULATION_SIDE_TABLES -def test_reports_index_their_owner_for_account_deletion() -> None: - """Deleting a user clears ``reports.user_id``, which an index finds.""" - assert ("user_id",) in _indexes("reports").values() +def test_reports_name_no_user() -> None: + """A shared report has no owner, so deleting a user leaves it untouched.""" + assert "user_id" not in stored_v2_table("reports").columns + assert ("user_id",) not in _indexes("reports").values() + assert "user" not in Report.__sqlmodel_relationships__ + assert "reports" not in User.__sqlmodel_relationships__ def test_the_catalog_versions_runs_and_jobs_use_are_indexed() -> None: diff --git a/tests/unit/v2/v2_schema_reading.py b/tests/unit/v2/v2_schema_reading.py index 5c3cb8978..6026ef88a 100644 --- a/tests/unit/v2/v2_schema_reading.py +++ b/tests/unit/v2/v2_schema_reading.py @@ -9,8 +9,7 @@ of the schema (``stored_v2_schema``), read with SQLAlchemy's Inspector, which reads what the database holds. SQLite keeps every name, column list, delete rule, check condition and index the models declare. Its columns also hold - those a mapper leaves out (``exclude_properties``), such as a report run's - four older cliff columns, which stay in the table until a revision drops them. + 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``).