diff --git a/.github/scripts/test_alembic_v2_lifecycle.sh b/.github/scripts/test_alembic_v2_lifecycle.sh index 1bea685eb..be57a95d1 100755 --- a/.github/scripts/test_alembic_v2_lifecycle.sh +++ b/.github/scripts/test_alembic_v2_lifecycle.sh @@ -5,6 +5,7 @@ set -euo pipefail uv run --frozen --extra dev pytest -q \ tests/unit/v2/test_alembic_v2.py \ tests/unit/v2/test_alembic_v2_revisions.py \ + tests/unit/v2/test_alembic_v2_dynamic_revisions.py \ tests/integration/test_alembic_v2_lifecycle.py \ tests/integration/test_alembic_v2_catalog_tables.py \ tests/integration/test_alembic_v2_simulation_runs.py \ @@ -16,4 +17,5 @@ uv run --frozen --extra dev pytest -q \ tests/integration/test_alembic_v2_dynamics.py \ tests/integration/test_alembic_v2_report_column_drops.py \ tests/integration/test_alembic_v2_user_dynamics.py \ - tests/integration/test_alembic_v2_dynamic_parameter_tables.py + tests/integration/test_alembic_v2_dynamic_parameter_tables.py \ + tests/integration/test_alembic_v2_parameter_values_dynamic_id_drop.py diff --git a/changelog.d/v2-parameter-values-dynamic-id.removed.md b/changelog.d/v2-parameter-values-dynamic-id.removed.md new file mode 100644 index 000000000..1706b2ad0 --- /dev/null +++ b/changelog.d/v2-parameter-values-dynamic-id.removed.md @@ -0,0 +1 @@ +`parameter_values` no longer has `dynamic_id`: since revision `7f7335f0eb31` a dynamic's values are `dynamic_parameter_values` rows. Revision `1c651058fac5` drops the column with its key to `dynamics`, the single-owner check `ck_parameter_values_single_owner` and the per-dynamic index `uq_parameter_values_dynamic_parameter_start_date`, and replaces the current-law index with `uq_parameter_values_current_law_parameter_start_date` on `policy_id IS NULL`. A `parameter_values` row is now a policy's value or a current-law value. diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 9bf12388f..9ee2c2906 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -310,9 +310,9 @@ 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` is until C1 · 53's revision, and the per-user - and cliff columns of `reports`, `report_runs` and `budget_window_runs` were - until revision `4e30076d4b9f`, has no statement + `parameter_values.dynamic_id` was until revision `1c651058fac5`, and 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 @@ -756,6 +756,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: +`1c651058fac5`'s adds `parameter_values.dynamic_id` back empty, with its key, +check and per-dynamic index (see "API v2 parameter values without dynamics"), `7f7335f0eb31`'s moves the dynamic parameters and their values back into `parameters` and `parameter_values` and drops their tables (see "API v2 dynamic parameters in their own tables"), @@ -1357,7 +1359,8 @@ changes, so that dynamics are stored as policies are: still reads every row of `parameter_values` (millions of current-law values), and, as Alembic creates it without `CONCURRENTLY`, inserts into that table wait until the build finishes. It is also declared for SQLite, - so the unit tests' databases keep the same rule. + so the unit tests' databases keep the same rule. Revision `1c651058fac5` + drops it with `parameter_values.dynamic_id`. - `legacy_policy_mappings` gains the nullable `dynamic_id`, the dynamic the v1-to-v2 policy copy split from a v1 policy: a key with the mapping's country to `dynamics` (`fk_legacy_policy_mappings_dynamic_country`, @@ -1710,13 +1713,88 @@ writer inserts both, deletes only current-law values (pruning) and analyzes both (`MAINTAIN`), and updates neither; the simulation service and its Modal workers read both, which C1 · 52 needs; comparison runs have no access. `parameter_values.dynamic_id`, its single-owner check and its partial -unique index stay until C1 · 53, because older simulation service releases -map the column; API v1 stops mapping it from C1 · 51a's release (see -"Columns a mapper leaves out"), so the release serving while C1 · 53's -revision runs names none of what it drops. -`tests/integration/test_alembic_v2_dynamic_parameter_tables.py` +unique index stay until revision `1c651058fac5` (see "API v2 parameter values +without dynamics"), because older simulation service releases map the column; +API v1 stops mapping it from C1 · 51a's release (see "Columns a mapper leaves +out"), so the release serving while that revision runs names none of what it +drops. `tests/integration/test_alembic_v2_dynamic_parameter_tables.py` checks that nothing else changes, the move with both kinds of row, the refusal, the read-only step, the downgrade and the re-upgrade, and `tests/integration/test_v2_catalog_publication_dynamic_parameters.py` publication, pruning, restoring and a downgrade round trip as the catalog writer. + +### API v2 parameter values without dynamics + +Revision `1c651058fac5` (parent `7f7335f0eb31`) was autogenerated, with its ID +given by `--rev-id`, after `ParameterValue` lost `dynamic_id`, the +single-owner check and the per-dynamic index. It has no post-generation +correction. Since `7f7335f0eb31` moved every dynamic's values to +`dynamic_parameter_values`, no `parameter_values` row names a dynamic, so it +drops: + +- `parameter_values.dynamic_id`, with its key to `dynamics` + (`fk_parameter_values_dynamic_id_dynamics`); +- `ck_parameter_values_single_owner`, which kept a row to one of a policy and + a dynamic; +- `uq_parameter_values_dynamic_parameter_start_date`, `9d1d12a7ac58`'s index + of one value per dynamic, parameter and start date. + +A `parameter_values` row is then a policy's value (`policy_id` set) or a +current-law value (`policy_id` null). + +**The current-law index is renamed.** The condition of +`uq_parameter_values_canonical_parameter_start_date`, one current-law value +per parameter and start date, was `policy_id IS NULL AND dynamic_id IS NULL`, +and PostgreSQL drops an index whose condition names a dropped column. Alembic +compares an index's condition by name only, as it does a check's, so, as for +`ck_users_user_type_allowed`, the model names the index with its new condition +`policy_id IS NULL` `uq_parameter_values_current_law_parameter_start_date`, +and autogenerate drops the old index and creates the new one (the user's +decision 2 for C1 · 53, 2026-11-26). It is also declared for SQLite. + +Building it reads every current-law value (millions of rows), after the drop +of the old index has locked `parameter_values` until the migration +transaction commits, so every read and write of the table waits for the +build, and API v1's and the simulation service's statements, which time out +after 5 seconds, fail meanwhile. `9d1d12a7ac58`'s index build, which read every +row but indexed only dynamics' rows, took about 10 seconds in production. In +production nothing reads these rows through the v2 routes yet; the dual-write +v1-to-v2 policy copy writes them, and a failed copy is logged with the v1 +response unchanged. + +**What must be in production first,** because the deploy upgrades the schema +before the new release takes traffic (see "CI/CD behavior"), and a whole-row +load names every mapped column: + +- An API v1 release whose `ParameterValue` doesn't map `dynamic_id`: C1 · 51a + leaves it out of the mapper (the user's decision 1 for C1 · 53; C1 · 50 + merged without that change), so the pull request merges only once C1 · 51a's + release is in production. +- The simulation service's C1 · 52 (PolicyEngine/policyengine-sim-api#1129), + which stops mapping the column: older releases select it in every policy + read. + +**An operator counts first** (the user's decision 3 for C1 · 53). A row that +still names a dynamic becomes a current-law value when the column goes, +silently, unless it shares its parameter and start date with a current-law +value, when the new index fails the upgrade and nothing changes. None is +expected: `7f7335f0eb31` moves every dynamic's value and refuses one that +names a parameter it doesn't move, and no release since writes the column. +One merge takes the revision through staging and production, so before +merging, an operator runs this read-only count in both environments, and the +pull request merges only when both are 0: + +```sql +SELECT count(*) FROM parameter_values WHERE dynamic_id IS NOT NULL; +``` + +**The downgrade** adds the column back empty with its key, the check and the +per-dynamic index, and replaces the current-law index with the old one, so +that `7f7335f0eb31`'s downgrade can copy every dynamic's values back into +`parameter_values` with their `dynamic_id`. No role's privilege names the +column. `tests/integration/test_alembic_v2_parameter_values_dynamic_id_drop.py` +compares the revision and its downgrade with the parent schema built from +the base, and checks that rows survive, the new index, a downgrade through +`7f7335f0eb31` and back, what a row still naming a dynamic becomes, and the +deploy's privilege steps. diff --git a/docs/engineering/skills/testing.md b/docs/engineering/skills/testing.md index 37d786785..d466d3664 100644 --- a/docs/engineering/skills/testing.md +++ b/docs/engineering/skills/testing.md @@ -303,7 +303,7 @@ The generated-only v2 Alembic chain and disposable Postgres lifecycle: ```bash uv run pytest tests/unit/v2/test_alembic_v2.py tests/unit/v2/test_alembic_v2_revisions.py \ - tests/unit/test_alembic_workflows.py -q + tests/unit/v2/test_alembic_v2_dynamic_revisions.py tests/unit/test_alembic_workflows.py -q V2_ALEMBIC_DISPOSABLE_TEST=1 V2_MIGRATION_DATABASE_URL="postgresql+psycopg://.../policyengine_v2_alembic_test" \ uv run pytest tests/integration/test_alembic_v2_lifecycle.py tests/integration/test_alembic_v2_catalog_tables.py -q ``` @@ -642,6 +642,7 @@ uv run --frozen pytest \ tests/unit/v2/test_models.py \ tests/unit/v2/test_alembic_v2.py \ tests/unit/v2/test_alembic_v2_revisions.py \ + tests/unit/v2/test_alembic_v2_dynamic_revisions.py \ tests/unit/test_readiness.py \ tests/unit/test_cloud_run_deploy_scripts.py \ tests/unit/test_migration_contract_artifacts.py \ diff --git a/migrations/v2/versions/1c651058fac5_drop_parameter_values_dynamic_id.py b/migrations/v2/versions/1c651058fac5_drop_parameter_values_dynamic_id.py new file mode 100644 index 000000000..7f5d7e8a7 --- /dev/null +++ b/migrations/v2/versions/1c651058fac5_drop_parameter_values_dynamic_id.py @@ -0,0 +1,57 @@ +"""drop parameter values dynamic_id + +Revision ID: 1c651058fac5 +Revises: 7f7335f0eb31 +Create Date: 2026-11-26 18:42:38.287815 +Generation: uv run alembic -c alembic-v2.ini revision --autogenerate --rev-id 1c651058fac5 + +Revision 7f7335f0eb31 moved every dynamic's values to dynamic_parameter_values, +so no parameter_values row names a dynamic. This drops parameter_values' +dynamic_id with its key to dynamics, the single-owner check and the +per-dynamic partial unique index. PostgreSQL also drops an index whose +condition names a dropped column, and Alembic compares an index's condition +by name only, so the model renamed the current-law index, and the upgrade +replaces uq_parameter_values_canonical_parameter_start_date with +uq_parameter_values_current_law_parameter_start_date on policy_id IS NULL. +The operations are exactly as generated. + +A row that still names a dynamic becomes a current-law value, so an operator +counts them first. Every release still serving when this runs must leave +dynamic_id out of its models. The downgrade adds the column back empty, with +its key, check and indexes, so that 7f7335f0eb31's downgrade can copy +dynamics' values back. +""" + +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +import sqlmodel + + +revision: str = '1c651058fac5' +down_revision: Union[str, None] = '7f7335f0eb31' +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_index(op.f('uq_parameter_values_canonical_parameter_start_date'), table_name='parameter_values', postgresql_where='((policy_id IS NULL) AND (dynamic_id IS NULL))') + op.drop_index(op.f('uq_parameter_values_dynamic_parameter_start_date'), table_name='parameter_values', postgresql_where='(dynamic_id IS NOT NULL)') + op.create_index('uq_parameter_values_current_law_parameter_start_date', 'parameter_values', ['parameter_id', 'start_date'], unique=True, postgresql_where=sa.text('policy_id IS NULL'), sqlite_where=sa.text('policy_id IS NULL')) + op.drop_constraint(op.f('fk_parameter_values_dynamic_id_dynamics'), 'parameter_values', type_='foreignkey') + op.drop_constraint(op.f('ck_parameter_values_single_owner'), 'parameter_values', type_='check') + op.drop_column('parameter_values', 'dynamic_id') + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('parameter_values', sa.Column('dynamic_id', sa.UUID(), autoincrement=False, nullable=True)) + op.create_check_constraint(op.f('ck_parameter_values_single_owner'), 'parameter_values', 'policy_id IS NULL OR dynamic_id IS NULL') + op.create_foreign_key(op.f('fk_parameter_values_dynamic_id_dynamics'), 'parameter_values', 'dynamics', ['dynamic_id'], ['id'], ondelete='CASCADE') + op.drop_index('uq_parameter_values_current_law_parameter_start_date', table_name='parameter_values', postgresql_where=sa.text('policy_id IS NULL'), sqlite_where=sa.text('policy_id IS NULL')) + op.create_index(op.f('uq_parameter_values_dynamic_parameter_start_date'), 'parameter_values', ['dynamic_id', 'parameter_id', 'start_date'], unique=True, postgresql_where='(dynamic_id IS NOT NULL)') + op.create_index(op.f('uq_parameter_values_canonical_parameter_start_date'), 'parameter_values', ['parameter_id', 'start_date'], unique=True, postgresql_where='((policy_id IS NULL) AND (dynamic_id IS NULL))') + # ### end Alembic commands ### diff --git a/policyengine_api/data/v2/migration_target.py b/policyengine_api/data/v2/migration_target.py index bf6858886..fd293a628 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 = "7f7335f0eb31" +V2_ALEMBIC_HEAD_REVISION = "1c651058fac5" 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/metadata.py b/policyengine_api/data/v2/models/metadata.py index cc517f40a..761763ba6 100644 --- a/policyengine_api/data/v2/models/metadata.py +++ b/policyengine_api/data/v2/models/metadata.py @@ -2,7 +2,7 @@ from datetime import datetime from enum import StrEnum -from typing import TYPE_CHECKING, Any, ClassVar, Literal, Optional +from typing import TYPE_CHECKING, Any, Literal, Optional from uuid import UUID import sqlalchemy as sa @@ -431,23 +431,12 @@ class ParameterValue(IdentifiedModel, table=True): A value owned by a policy is deleted with it, and a policy sets at most one per parameter and start date. A value with no policy is current law, and a parameter has at most one per start date. A dynamic's values are - ``DynamicParameterValue`` rows since revision 7f7335f0eb31 moved them, so - no row has a ``dynamic_id``. The column 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 C1 · 53 - drops the column, its check and its index, once no simulation service - release maps it either. + ``DynamicParameterValue`` rows: revision 7f7335f0eb31 moved them there, and + revision 1c651058fac5 dropped ``dynamic_id`` with its check and index. """ __tablename__ = "parameter_values" - __mapper_args__: ClassVar[dict[str, Any]] = {"exclude_properties": ("dynamic_id",)} __table_args__ = ( - sa.CheckConstraint( - "policy_id IS NULL OR dynamic_id IS NULL", - name="ck_parameter_values_single_owner", - ), sa.CheckConstraint( "end_date IS NULL OR end_date >= start_date", name="ck_parameter_values_effective_period", @@ -458,18 +447,6 @@ class ParameterValue(IdentifiedModel, table=True): "start_date", name="uq_parameter_values_policy_parameter_start_date", ), - # A dynamic's values are unique as a policy's are. The index covers - # only dynamics' rows, so it doesn't index every current-law value; - # rows without a dynamic never conflict in a unique key anyway. - sa.Index( - "uq_parameter_values_dynamic_parameter_start_date", - "dynamic_id", - "parameter_id", - "start_date", - unique=True, - postgresql_where=sa.text("dynamic_id IS NOT NULL"), - sqlite_where=sa.text("dynamic_id IS NOT NULL"), - ), sa.Index( "ix_parameter_values_parameter_period", "parameter_id", @@ -477,15 +454,17 @@ class ParameterValue(IdentifiedModel, table=True): "end_date", ), # SQLModel does not expose dialect-specific partial unique indexes. - # Canonical values have neither an owning policy nor dynamic, while - # those owners may each store their own value for the same period. + # Current-law values have no owning policy, while each policy may + # store its own value for the same period. Alembic compares an + # index's condition by its name only, so the index took a new name + # when its condition stopped naming dynamic_id (revision 1c651058fac5). sa.Index( - "uq_parameter_values_canonical_parameter_start_date", + "uq_parameter_values_current_law_parameter_start_date", "parameter_id", "start_date", unique=True, - postgresql_where=sa.text("policy_id IS NULL AND dynamic_id IS NULL"), - sqlite_where=sa.text("policy_id IS NULL AND dynamic_id IS NULL"), + postgresql_where=sa.text("policy_id IS NULL"), + sqlite_where=sa.text("policy_id IS NULL"), ), ) @@ -506,13 +485,6 @@ class ParameterValue(IdentifiedModel, table=True): foreign_key="policies.id", ondelete="CASCADE", ) - # In the table but left out of the mapper (``exclude_properties``) until a - # revision drops it. - dynamic_id: UUID | None = Field( - default=None, - foreign_key="dynamics.id", - ondelete="CASCADE", - ) parameter: Parameter = Relationship(back_populates="values") policy: Optional["Policy"] = Relationship(back_populates="parameter_values") diff --git a/tests/integration/test_alembic_v2_dynamics.py b/tests/integration/test_alembic_v2_dynamics.py index abdebd3a7..a441ed970 100644 --- a/tests/integration/test_alembic_v2_dynamics.py +++ b/tests/integration/test_alembic_v2_dynamics.py @@ -10,7 +10,6 @@ from __future__ import annotations -from datetime import UTC, datetime from typing import TYPE_CHECKING, Any from uuid import UUID, uuid4 @@ -24,15 +23,11 @@ from policyengine_api.data.v2.models import ( Dynamic, LegacyPolicyMapping, - Parameter, Policy, ) from tests.fixtures.database_sessions import schema_inspector from tests.fixtures.integration.alembic_v2 import alembic_v2_config, table_columns from tests.integration.alembic_version_rows import current_revision -from tests.integration.parameter_values_with_dynamics import ( - ParameterValueWithDynamic, -) from tests.integration.simulation_rows import ( PublicApiRows, add_row, @@ -158,18 +153,6 @@ def _insert_dynamic( return dynamic_id -def _insert_parameter(session: Session, rows: PublicApiRows) -> UUID: - parameter_id = uuid4() - add_row( - session, - Parameter, - id=parameter_id, - name="gov.simulation.labor_supply_responses.elasticities.income", - tax_benefit_model_version_id=rows.version_id, - ) - return parameter_id - - def _insert_policy(session: Session, rows: PublicApiRows, *, country_id: str) -> UUID: policy_id = uuid4() add_row( @@ -251,42 +234,22 @@ def test_the_revision_changes_only_dynamics_their_values_and_mappings( command.check(config) -def test_a_dynamic_is_stored_once_and_sets_one_value_per_parameter_and_date( - session: Session, -) -> None: - """A dynamic is unique by its content hash, and its values as a policy's are. +def test_a_dynamic_is_stored_once(session: Session) -> None: + """A dynamic is unique by its content hash, which has 64 characters. - ``parameter_values`` keeps ``dynamic_id`` and the revision's partial unique - index until C1 · 53 drops them; ``ParameterValue`` no longer maps the - column, so the values are written through ``ParameterValueWithDynamic``. + The revision's partial unique index on a dynamic's ``parameter_values`` is + gone at the head: revision 7f7335f0eb31 moved dynamics' values to + ``dynamic_parameter_values``, which keeps that rule, and revision + 1c651058fac5 dropped ``parameter_values.dynamic_id`` with the index. """ rows = insert_public_api_rows(session) - parameter_id = _insert_parameter(session, rows) - dynamic_id = _insert_dynamic(session, rows) + _insert_dynamic(session, rows) with refused(session, match="uq_dynamics_canonicalization_content_hash"): _insert_dynamic(session, rows) with refused(session, match="ck_dynamics_content_hash_length"): _insert_dynamic(session, rows, content_hash="short") - value = { - "parameter_id": parameter_id, - "dynamic_id": dynamic_id, - "value_json": 0.1, - "start_date": datetime(2026, 1, 1, tzinfo=UTC), - } - add_row(session, ParameterValueWithDynamic, id=uuid4(), **value) - with refused(session, match="uq_parameter_values_dynamic_parameter_start_date"): - add_row(session, ParameterValueWithDynamic, id=uuid4(), **value) - # Another dynamic may set the same parameter from the same date. - other_dynamic_id = _insert_dynamic(session, rows, content_hash="e" * 64) - add_row( - session, - ParameterValueWithDynamic, - id=uuid4(), - **{**value, "dynamic_id": other_dynamic_id}, - ) - def test_a_mapping_names_a_dynamic_of_its_country_which_stays_while_named( session: Session, diff --git a/tests/integration/test_alembic_v2_lifecycle.py b/tests/integration/test_alembic_v2_lifecycle.py index e8152daa6..b9672da3b 100644 --- a/tests/integration/test_alembic_v2_lifecycle.py +++ b/tests/integration/test_alembic_v2_lifecycle.py @@ -273,11 +273,14 @@ def _assert_head(sessions: sessionmaker[Session]) -> None: index["name"]: index for index in schema_inspector(sessions).get_indexes("parameter_values") } - canonical_index = parameter_value_indexes[ - "uq_parameter_values_canonical_parameter_start_date" + current_law_index = parameter_value_indexes[ + "uq_parameter_values_current_law_parameter_start_date" ] - assert canonical_index["unique"] - assert canonical_index["column_names"] == ["parameter_id", "start_date"] + assert current_law_index["unique"] + assert current_law_index["column_names"] == ["parameter_id", "start_date"] + assert current_law_index["dialect_options"]["postgresql_where"] == ( + "(policy_id IS NULL)" + ) policy_value_constraint = next( constraint for constraint in schema_inspector(sessions).get_unique_constraints( @@ -547,10 +550,13 @@ def _assert_stage11_downgrade(sessions: sessionmaker[Session]) -> None: def _assert_baseline_downgrade(sessions: sessionmaker[Session]) -> None: _assert_revision(sessions, BASELINE_REVISION) - assert "uq_parameter_values_canonical_parameter_start_date" not in { + assert { + "uq_parameter_values_canonical_parameter_start_date", + "uq_parameter_values_current_law_parameter_start_date", + }.isdisjoint( index["name"] for index in schema_inspector(sessions).get_indexes("parameter_values") - } + ) def _assert_base(sessions: sessionmaker[Session]) -> None: diff --git a/tests/integration/test_alembic_v2_parameter_values_dynamic_id_drop.py b/tests/integration/test_alembic_v2_parameter_values_dynamic_id_drop.py new file mode 100644 index 000000000..2320193b4 --- /dev/null +++ b/tests/integration/test_alembic_v2_parameter_values_dynamic_id_drop.py @@ -0,0 +1,546 @@ +"""Check the revision that drops ``parameter_values.dynamic_id`` against Postgres. + +Revision 1c651058fac5, on the dynamic parameter tables revision 7f7335f0eb31, +drops ``parameter_values.dynamic_id`` with its key to ``dynamics``, the +single-owner check and the per-dynamic partial unique index: revision +7f7335f0eb31 moved every dynamic's values to ``dynamic_parameter_values``. +PostgreSQL also drops the current-law index, whose condition named the column, +so the revision creates it again under a new name with ``policy_id IS NULL``. +The downgrade restores the column, key, check and both indexes, so that the +downgrade through 7f7335f0eb31 can copy dynamics' values back. + +The rows are written as the disposable database's owner. +""" + +from __future__ import annotations + +from copy import deepcopy +from datetime import UTC, datetime +from typing import TYPE_CHECKING, Any +from uuid import UUID, uuid4 + +import pytest +from alembic import command +from sqlalchemy import delete, select, update +from sqlalchemy.dialects import postgresql +from sqlalchemy.exc import IntegrityError +from sqlmodel import col + +from policyengine_api.data.v2.migration_target import V2_ALEMBIC_DISPOSABLE_TEST +from policyengine_api.data.v2.models import ( + Dynamic, + DynamicParameter, + DynamicParameterValue, + Parameter, + ParameterValue, + Policy, + TaxBenefitModel, + TaxBenefitModelVersion, +) +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 schema_inspector +from tests.fixtures.integration.alembic_v2 import alembic_v2_config, table_columns +from tests.integration.alembic_version_rows import current_revision +from tests.integration.parameter_values_with_dynamics import ( + ParameterValueWithDynamic, +) +from tests.integration.simulation_rows import ( + PublicApiRows, + add_row, + delete_public_api_rows, + insert_public_api_rows, + refused, +) + +if TYPE_CHECKING: + from collections.abc import Iterator + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + from tests.integration.conftest import ManagedV2Roles + +USER_DYNAMICS_REVISION = "d417fe8b1b17" +DYNAMIC_PARAMETER_TABLES_REVISION = "7f7335f0eb31" +DYNAMIC_ID_DROP_REVISION = "1c651058fac5" +CURRENT_LAW_INDEX = "uq_parameter_values_current_law_parameter_start_date" +START_2026 = datetime(2026, 1, 1, tzinfo=UTC) +START_2027 = datetime(2027, 1, 1, tzinfo=UTC) +US_ELASTICITY = "gov.simulation.labor_supply_responses.elasticity" + + +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 _expected_after_the_drop( + parent_shape: dict[str, dict[str, Any]], +) -> dict[str, dict[str, Any]]: + """Return the parent's schema less the dynamic's columns, with the new index.""" + expected = deepcopy(parent_shape) + values = expected["parameter_values"] + del values["columns"]["dynamic_id"] + del values["foreign_keys"]["fk_parameter_values_dynamic_id_dynamics"] + del values["checks"]["ck_parameter_values_single_owner"] + del values["indexes"]["uq_parameter_values_dynamic_parameter_start_date"] + del values["indexes"]["uq_parameter_values_canonical_parameter_start_date"] + values["indexes"][CURRENT_LAW_INDEX] = ( + ("parameter_id", "start_date"), + True, + "(policy_id IS NULL)", + ) + 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. + """ + command.upgrade(alembic_v2_config(), "head") + 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.downgrade(config, "base") + command.upgrade(config, DYNAMIC_PARAMETER_TABLES_REVISION) + return _schema_shape(sessions) + + +def test_the_revision_drops_only_what_a_dynamic_s_values_needed( + sessions: sessionmaker[Session], +) -> None: + """The drop, and a current-law index with no ``dynamic_id`` in its condition. + + The downgrade gives back exactly the parent's schema. + """ + config = alembic_v2_config() + parent_shape = _build_parent_schema(sessions) + + command.upgrade(config, DYNAMIC_ID_DROP_REVISION) + + assert _schema_shape(sessions) == _expected_after_the_drop(parent_shape) + + command.downgrade(config, DYNAMIC_PARAMETER_TABLES_REVISION) + + assert _schema_shape(sessions) == parent_shape + + +def _add_parameter(session: Session, rows: PublicApiRows, name: str) -> UUID: + parameter_id = uuid4() + add_row( + session, + Parameter, + id=parameter_id, + name=name, + tax_benefit_model_version_id=rows.version_id, + ) + return parameter_id + + +def _add_policy(session: Session, rows: PublicApiRows) -> UUID: + policy_id = uuid4() + add_row( + session, + Policy, + id=policy_id, + country_id="us", + tax_benefit_model_id=rows.model_id, + tax_benefit_model_version_id=rows.version_id, + canonicalization_version=1, + content_hash=uuid4().hex * 2, + ) + return policy_id + + +def _add_dynamic(session: Session, model_id: UUID, version_id: UUID) -> UUID: + dynamic_id = uuid4() + add_row( + session, + Dynamic, + id=dynamic_id, + country_id="us", + tax_benefit_model_id=model_id, + tax_benefit_model_version_id=version_id, + canonicalization_version=1, + content_hash=uuid4().hex * 2, + ) + return dynamic_id + + +def _delete_catalog_rows( + session: Session, rows: PublicApiRows, *, policy_ids: list[UUID] +) -> None: + """Delete the policies and dynamics, then the version with its parameters.""" + session.execute(delete(Policy).where(col(Policy.id).in_(policy_ids))) + session.execute( + delete(Dynamic).where( + col(Dynamic.tax_benefit_model_version_id) == rows.version_id + ) + ) + session.execute( + delete(Parameter).where( + col(Parameter.tax_benefit_model_version_id) == rows.version_id + ) + ) + delete_public_api_rows(session, rows) + + +def test_rows_survive_and_a_parameter_keeps_one_current_law_value_per_date( + sessions: sessionmaker[Session], +) -> None: + """A current-law value and a policy's value stay, and the new index refuses. + + The index covers every value with no policy, and no policy's value. + """ + config = alembic_v2_config() + command.downgrade(config, DYNAMIC_PARAMETER_TABLES_REVISION) + with sessions.begin() as session: + rows = insert_public_api_rows(session) + parameter_id = _add_parameter(session, rows, "gov.irs.rate") + policy_id = _add_policy(session, rows) + current_law_value_id = uuid4() + policy_value_id = uuid4() + current_law = { + "parameter_id": parameter_id, + "value_json": 0.5, + "start_date": START_2026, + } + add_row(session, ParameterValue, id=current_law_value_id, **current_law) + add_row( + session, + ParameterValue, + id=policy_value_id, + **{**current_law, "value_json": 0.4}, + policy_id=policy_id, + ) + try: + command.upgrade(config, DYNAMIC_ID_DROP_REVISION) + + with sessions() as session: + stored = set( + session.execute( + select( + col(ParameterValue.id), + col(ParameterValue.policy_id), + col(ParameterValue.value_json), + ).where(col(ParameterValue.parameter_id) == parameter_id) + ) + ) + assert stored == { + (current_law_value_id, None, 0.5), + (policy_value_id, policy_id, 0.4), + } + with refused(session, match=CURRENT_LAW_INDEX): + add_row(session, ParameterValue, id=uuid4(), **current_law) + # Another policy may set the same parameter from the same date. + other_policy_id = _add_policy(session, rows) + add_row( + session, + ParameterValue, + id=uuid4(), + **current_law, + policy_id=other_policy_id, + ) + session.rollback() + finally: + with sessions.begin() as session: + _delete_catalog_rows(session, rows, policy_ids=[policy_id]) + + +def _us_model_id(session: Session) -> tuple[UUID, bool]: + """Return ``policyengine-us``'s model, storing it first if it isn't stored. + + The dynamic parameter tables revision classifies a version's parameters + by its model's name, so a round trip through it needs this model. + """ + stored = session.scalars( + select(col(TaxBenefitModel.id)).where( + col(TaxBenefitModel.name) == "policyengine-us" + ) + ).one_or_none() + if stored is not None: + return stored, False + model_id = uuid4() + add_row(session, TaxBenefitModel, id=model_id, name="policyengine-us") + return model_id, True + + +def test_a_downgrade_through_the_move_puts_a_dynamic_s_values_back( + sessions: sessionmaker[Session], +) -> None: + """The restored column takes a dynamic's values back, and the upgrades move them. + + The downgrade through 7f7335f0eb31 copies dynamics' values into + ``parameter_values`` with their ``dynamic_id``, where the restored check + and per-dynamic index apply again. Upgrading to the head moves them back + to ``dynamic_parameter_values`` and drops the column again. + """ + config = alembic_v2_config() + with sessions.begin() as session: + model_id, model_created = _us_model_id(session) + version_id = uuid4() + add_row( + session, + TaxBenefitModelVersion, + id=version_id, + model_id=model_id, + version=f"c1-53-{version_id.hex[:12]}", + current_law_id=1, + metadata_time_periods=[2026], + ) + parameter_id = uuid4() + add_row( + session, + DynamicParameter, + id=parameter_id, + name=US_ELASTICITY, + tax_benefit_model_version_id=version_id, + ) + dynamic_id = _add_dynamic(session, model_id, version_id) + current_law_value_id = uuid4() + dynamic_value_id = uuid4() + add_row( + session, + DynamicParameterValue, + id=current_law_value_id, + dynamic_parameter_id=parameter_id, + value_json=0.0, + start_date=START_2026, + ) + add_row( + session, + DynamicParameterValue, + id=dynamic_value_id, + dynamic_parameter_id=parameter_id, + dynamic_id=dynamic_id, + value_json=0.3, + start_date=START_2027, + ) + try: + command.downgrade(config, USER_DYNAMICS_REVISION) + + with sessions() as session: + restored = set( + session.execute( + select( + ParameterValueWithDynamic.id, + ParameterValueWithDynamic.dynamic_id, + ParameterValueWithDynamic.policy_id, + ).where(ParameterValueWithDynamic.parameter_id == parameter_id) + ) + ) + assert restored == { + (current_law_value_id, None, None), + (dynamic_value_id, dynamic_id, None), + } + dynamic_value = { + "parameter_id": parameter_id, + "dynamic_id": dynamic_id, + "value_json": 0.4, + "start_date": START_2027, + } + with refused( + session, match="uq_parameter_values_dynamic_parameter_start_date" + ): + add_row(session, ParameterValueWithDynamic, id=uuid4(), **dynamic_value) + policy_id = uuid4() + add_row( + session, + Policy, + id=policy_id, + country_id="us", + tax_benefit_model_id=model_id, + tax_benefit_model_version_id=version_id, + canonicalization_version=1, + content_hash=uuid4().hex * 2, + ) + with refused(session, match="ck_parameter_values_single_owner"): + add_row( + session, + ParameterValueWithDynamic, + id=uuid4(), + **{**dynamic_value, "start_date": START_2026}, + policy_id=policy_id, + ) + session.rollback() + + command.upgrade(config, "head") + + assert "dynamic_id" not in table_columns(sessions, "parameter_values") + with sessions() as session: + moved = set( + session.execute( + select( + col(DynamicParameterValue.id), + col(DynamicParameterValue.dynamic_id), + ).where( + col(DynamicParameterValue.dynamic_parameter_id) == parameter_id + ) + ) + ) + assert moved == {(current_law_value_id, None), (dynamic_value_id, dynamic_id)} + finally: + command.upgrade(config, "head") + with sessions.begin() as session: + session.execute(delete(Dynamic).where(col(Dynamic.id) == dynamic_id)) + session.execute( + delete(TaxBenefitModelVersion).where( + col(TaxBenefitModelVersion.id) == version_id + ) + ) + if model_created: + session.execute( + delete(TaxBenefitModel).where(col(TaxBenefitModel.id) == model_id) + ) + + +def test_a_value_still_naming_a_dynamic_becomes_current_law_unless_it_clashes( + sessions: sessionmaker[Session], +) -> None: + """Why an operator counts such values before the merge (C1 · 53, decision 3). + + None should exist after 7f7335f0eb31. One that shares its parameter and + start date with a current-law value fails the new index, and the upgrade + changes nothing; any other silently becomes a current-law value. + """ + config = alembic_v2_config() + command.downgrade(config, DYNAMIC_PARAMETER_TABLES_REVISION) + with sessions.begin() as session: + rows = insert_public_api_rows(session) + parameter_id = _add_parameter(session, rows, "gov.irs.rate") + dynamic_id = _add_dynamic(session, rows.model_id, rows.version_id) + add_row( + session, + ParameterValue, + id=uuid4(), + parameter_id=parameter_id, + value_json=0.5, + start_date=START_2026, + ) + stray_value_id = uuid4() + add_row( + session, + ParameterValueWithDynamic, + id=stray_value_id, + parameter_id=parameter_id, + dynamic_id=dynamic_id, + value_json=0.3, + start_date=START_2026, + ) + try: + with pytest.raises(IntegrityError, match=CURRENT_LAW_INDEX): + command.upgrade(config, DYNAMIC_ID_DROP_REVISION) + + assert current_revision(sessions) == DYNAMIC_PARAMETER_TABLES_REVISION + with sessions.begin() as session: + assert session.scalars( + select(ParameterValueWithDynamic.dynamic_id).where( + ParameterValueWithDynamic.id == stray_value_id + ) + ).all() == [dynamic_id] + session.execute( + update(ParameterValueWithDynamic) + .where(ParameterValueWithDynamic.id == stray_value_id) + .values(start_date=START_2027) + ) + + command.upgrade(config, DYNAMIC_ID_DROP_REVISION) + + with sessions() as session: + assert session.scalars( + select(col(ParameterValue.policy_id)).where( + col(ParameterValue.id) == stray_value_id + ) + ).all() == [None] + finally: + with sessions.begin() as session: + _delete_catalog_rows(session, rows, policy_ids=[]) + + +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 on the head after an upgrade from the parent.""" + config = alembic_v2_config() + command.downgrade(config, DYNAMIC_PARAMETER_TABLES_REVISION) + command.upgrade(config, "head") + 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_v2_dynamic_persistence.py b/tests/integration/test_v2_dynamic_persistence.py index 4ed1945e9..05d320173 100644 --- a/tests/integration/test_v2_dynamic_persistence.py +++ b/tests/integration/test_v2_dynamic_persistence.py @@ -39,9 +39,6 @@ ) from policyengine_api.services.v2.policies.services import V2PolicyService from policyengine_api.services.v2.policies.types import LegacyPolicySnapshot -from tests.integration.parameter_values_with_dynamics import ( - ParameterValueWithDynamic, -) if TYPE_CHECKING: from collections.abc import Callable, Iterator @@ -227,7 +224,8 @@ def _stored_names(session: Session, *, policy_id=None, dynamic_id=None) -> set[s """Return the names a policy's or a dynamic's stored values set. A policy's values are ``parameter_values`` rows; a dynamic's are - ``dynamic_parameter_values`` rows, and it sets no ``parameter_values`` row. + ``dynamic_parameter_values`` rows (``parameter_values`` has no + ``dynamic_id`` since revision 1c651058fac5). """ if policy_id is not None: return set( @@ -237,16 +235,6 @@ def _stored_names(session: Session, *, policy_id=None, dynamic_id=None) -> set[s .where(ParameterValue.policy_id == policy_id) ) ) - # ParameterValue no longer maps the column, which the table keeps until - # C1 · 53 drops it. - assert ( - session.scalars( - select(ParameterValueWithDynamic.id).where( - ParameterValueWithDynamic.dynamic_id == dynamic_id - ) - ).all() - == [] - ) return set( session.scalars( select(DynamicParameter.name) diff --git a/tests/integration/test_v2_simulation_role_privileges.py b/tests/integration/test_v2_simulation_role_privileges.py index 926f7e2e0..7f591fa4a 100644 --- a/tests/integration/test_v2_simulation_role_privileges.py +++ b/tests/integration/test_v2_simulation_role_privileges.py @@ -20,7 +20,7 @@ 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 of these tables leaves a column out. +``4e30076d4b9f`` no model leaves a column out. """ from __future__ import annotations @@ -612,7 +612,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 of the run tables leaves a column out. +# revision 4e30076d4b9f no model leaves a column out. UNMAPPED_COLUMN_CLASSES: dict[type[Any], type[Any]] = {} diff --git a/tests/unit/test_alembic_workflows.py b/tests/unit/test_alembic_workflows.py index c1410b614..612cca752 100644 --- a/tests/unit/test_alembic_workflows.py +++ b/tests/unit/test_alembic_workflows.py @@ -207,6 +207,7 @@ def test_reusable_v2_alembic_check_uses_only_disposable_postgres(): assert "bash .github/scripts/test_alembic_v2_lifecycle.sh" in workflow assert "test_alembic_v2.py" in lifecycle_script assert "test_alembic_v2_revisions.py" in lifecycle_script + assert "test_alembic_v2_dynamic_revisions.py" in lifecycle_script assert "test_alembic_v2_lifecycle.py" in lifecycle_script assert "test_alembic_v2_catalog_tables.py" in lifecycle_script assert "test_alembic_v2_simulation_runs.py" in lifecycle_script @@ -219,6 +220,7 @@ def test_reusable_v2_alembic_check_uses_only_disposable_postgres(): assert "test_alembic_v2_report_column_drops.py" in lifecycle_script assert "test_alembic_v2_user_dynamics.py" in lifecycle_script assert "test_alembic_v2_dynamic_parameter_tables.py" in lifecycle_script + assert "test_alembic_v2_parameter_values_dynamic_id_drop.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_dynamic_revisions.py b/tests/unit/v2/test_alembic_v2_dynamic_revisions.py new file mode 100644 index 000000000..81d8bf11a --- /dev/null +++ b/tests/unit/v2/test_alembic_v2_dynamic_revisions.py @@ -0,0 +1,302 @@ +"""Unit checks of the dynamics revisions of the v2 Alembic chain. + +The revisions that store dynamics like policies (9d1d12a7ac58), store users' +saved dynamics (d417fe8b1b17), move dynamic parameters and their values into +their own tables (7f7335f0eb31) and drop ``parameter_values.dynamic_id`` +(1c651058fac5). As in ``test_alembic_v2_revisions``, where the chain's order +is checked, these tests read the revision files and check the operations +each one runs. +""" + +import importlib.util +import re +from pathlib import Path + +from policyengine_api.constants import REPO +from policyengine_api.dynamic_parameters import DYNAMIC_PARAMETER_PREFIXES +from tests.unit.v2.test_alembic_v2_revisions import ( + DYNAMIC_PARAMETER_TABLES_REVISION, + DYNAMICS_REVISION, + PARAMETER_VALUES_DYNAMIC_ID_DROP_REVISION, + REPORT_COLUMN_DROPS_REVISION, + USER_DYNAMICS_REVISION, + USER_INVITATIONS_REVISION, +) + + +def test_dynamics_revision_stores_dynamics_like_policies_and_maps_them() -> None: + """The revision after user invitations stores dynamics as policies are stored. + + It is generated with no corrections: ``dynamics`` gains policies' five + columns, their two indexes, two unique constraints, three foreign keys + and two checks, and loses ``name`` and ``description``; + ``legacy_policy_mappings`` gains ``dynamic_id`` with its index and key; + ``parameter_values`` gains the partial unique index on dynamics' values. + The downgrade undoes each, and neither writes data. + """ + (path,) = (REPO / "migrations/v2/versions").glob(f"{DYNAMICS_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()") :] + + assert ( + "Generation: uv run alembic -c alembic-v2.ini revision --autogenerate" + in revision + ) + assert ( + f'down_revision: Union[str, None] = "{USER_INVITATIONS_REVISION}"' in revision + ) + assert "correction" not in revision.lower() + assert sorted(re.findall(r"op\.\w+", upgrade)) == sorted( + [ + *["op.add_column"] * 6, + *["op.create_index"] * 4, + *["op.create_unique_constraint"] * 2, + *["op.create_foreign_key"] * 4, + *["op.create_check_constraint"] * 2, + *["op.drop_column"] * 2, + # Two generated index names, three key names and two check names. + *["op.f"] * 7, + ] + ) + assert sorted(re.findall(r"op\.\w+", downgrade)) == sorted( + [ + *["op.drop_index"] * 4, + *["op.drop_constraint"] * 8, + *["op.drop_column"] * 6, + *["op.add_column"] * 2, + *["op.f"] * 7, + ] + ) + for column_name in ( + "country_id", + "tax_benefit_model_id", + "tax_benefit_model_version_id", + "canonicalization_version", + "content_hash", + ): + assert re.search( + rf'op\.add_column\(\s*"dynamics",\s*sa\.Column\(\s*"{column_name}",' + r"[^)]*\)?[^)]*nullable=False", + upgrade, + ) + assert re.search(r'op\.drop_column\("dynamics", "name"\)', upgrade) + assert re.search(r'op\.drop_column\("dynamics", "description"\)', upgrade) + assert re.search( + r'op\.add_column\(\s*"legacy_policy_mappings",\s*' + r'sa\.Column\("dynamic_id", sa\.Uuid\(\), nullable=True\)', + upgrade, + ) + assert "fk_legacy_policy_mappings_dynamic_country" in upgrade + assert "uq_parameter_values_dynamic_parameter_start_date" in upgrade + assert 'postgresql_where=sa.text("dynamic_id IS NOT NULL")' in upgrade + assert "op.execute(" not in revision + assert "op.bulk_insert(" not in revision + + +def test_user_dynamics_revision_creates_only_the_saved_dynamics_table() -> None: + """The revision after report column drops creates ``user_dynamics`` alone. + + It is generated with no corrections, with its ID chosen through + ``--rev-id``: one table, whose keys name its user (``CASCADE``), its + country and a dynamic of that country (both ``RESTRICT``), with its + three indexes. The downgrade drops them, and neither writes data. + """ + (path,) = (REPO / "migrations/v2/versions").glob(f"{USER_DYNAMICS_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()") :] + + assert ( + "Generation: uv run alembic -c alembic-v2.ini revision --autogenerate" + in revision + ) + assert ( + f'down_revision: Union[str, None] = "{REPORT_COLUMN_DROPS_REVISION}"' + in revision + ) + assert "correction" not in revision.lower() + operations = [name for name in re.findall(r"op\.\w+", upgrade) if name != "op.f"] + assert sorted(operations) == ["op.create_index"] * 3 + ["op.create_table"] + reversals = [name for name in re.findall(r"op\.\w+", downgrade) if name != "op.f"] + assert sorted(reversals) == ["op.drop_index"] * 3 + ["op.drop_table"] + assert re.search(r'op\.create_table\(\s*"user_dynamics"', upgrade) + assert 'op.drop_table("user_dynamics")' in downgrade + for constraint_name in ( + "fk_user_dynamics_dynamic_country", + "uq_user_dynamics_id_country", + "ix_user_dynamics_country_user_created_id", + "ix_user_dynamics_country_dynamic", + ): + assert constraint_name in upgrade + assert re.search( + r'\["dynamic_id", "country_id"\],\s*\["dynamics\.id", "dynamics\.country_id"\]', + upgrade, + ) + assert upgrade.count('ondelete="RESTRICT"') == 2 + assert upgrade.count('ondelete="CASCADE"') == 1 + assert "op.execute(" not in revision + assert "op.bulk_insert(" not in revision + + +def _dynamic_parameter_tables_revision_path() -> Path: + (path,) = (REPO / "migrations/v2/versions").glob( + f"{DYNAMIC_PARAMETER_TABLES_REVISION}_*.py" + ) + return path + + +def test_dynamic_parameter_tables_revision_creates_two_tables_and_moves_rows() -> None: + """The revision after user dynamics adds the two tables, then moves rows. + + Its tables and indexes are generated. Its one data step is the user's + migration decision (C1 · 46, Q2), written by hand: after the generated + tables are created it moves every stored dynamic parameter and value into + them, and before the generated drops its downgrade moves them back. It has + no other correction. + """ + revision = _dynamic_parameter_tables_revision_path().read_text(encoding="utf-8") + upgrade = revision[ + revision.index("def upgrade()") : revision.index("def downgrade()") + ] + downgrade = revision[revision.index("def downgrade()") :] + parent = USER_DYNAMICS_REVISION + + assert ( + "Generation: uv run alembic -c alembic-v2.ini revision --autogenerate" + in revision + ) + assert re.search( + rf"""down_revision: Union\[str, None\] = ["']{parent}["']""", revision + ) + assert "C1 · 46" in revision + assert "Q2" in revision + assert re.findall(r"""op\.create_table\(\s*["'](\w+)["']""", upgrade) == [ + "dynamic_parameters", + "dynamic_parameter_values", + ] + assert sorted( + re.findall(r"""op\.create_index\(\s*(?:op\.f\()?["'](\w+)["']""", upgrade) + ) == [ + "ix_dynamic_parameter_values_parameter_period", + "ix_dynamic_parameters_tax_benefit_model_version_id", + "uq_dynamic_parameter_values_current_law_parameter_start_date", + "uq_dynamic_parameter_values_dynamic_parameter_start_date", + ] + assert sorted(re.findall(r"""op\.drop_table\(\s*["'](\w+)["']""", downgrade)) == [ + "dynamic_parameter_values", + "dynamic_parameters", + ] + assert revision.count("Approved hand-written data step") == 2 + assert "Post-generation correction" not in revision + assert "op.bulk_insert(" not in revision + move = upgrade.index("_move_dynamic_parameters_into_their_tables()") + assert upgrade.rindex("op.create_index(") < move + move_back = downgrade.index("_move_dynamic_parameters_back()") + assert move_back < downgrade.index("op.drop_index(") + for table in ("parameters", "parameter_values", "parameter_tree_children"): + assert f'op.drop_table("{table}")' not in revision + + +def test_dynamic_parameter_tables_revision_keeps_its_own_copy_of_the_prefixes() -> None: + """The revision classifies with a frozen copy that matches the package's. + + A revision runs once per database, so it never imports application code + that may change; publication compares the installed version's rows with + the package's own classification right after it. + """ + path = _dynamic_parameter_tables_revision_path() + source = path.read_text(encoding="utf-8") + spec = importlib.util.spec_from_file_location("dynamic_parameter_tables", path) + assert spec is not None + assert spec.loader is not None + revision = importlib.util.module_from_spec(spec) + spec.loader.exec_module(revision) + + assert "policyengine_api" not in source + package_prefixes = dict(DYNAMIC_PARAMETER_PREFIXES) + assert package_prefixes == revision.DYNAMIC_PARAMETER_PREFIXES + + +def test_parameter_values_dynamic_id_drop_is_generated_with_no_corrections() -> None: + """The revision after the dynamic parameter tables drops what dynamics used. + + It is generated, with its ID chosen through ``--rev-id``, after + ``ParameterValue`` lost ``dynamic_id``, its single-owner check and its + per-dynamic index, and the current-law index was renamed, since Alembic + compares an index's condition by name only. PostgreSQL drops an index + whose condition names a dropped column, so the upgrade creates the renamed + index with ``policy_id IS NULL`` and the downgrade restores the old one. + Neither writes data, and there is no hand-written step: an operator counts + the rows that still name a dynamic before the merge (C1 · 53, decision 3). + """ + (path,) = (REPO / "migrations/v2/versions").glob( + f"{PARAMETER_VALUES_DYNAMIC_ID_DROP_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()") :] + index_name = r"""(?:op\.f\()?["'](\w+)["']""" + + assert ( + "Generation: uv run alembic -c alembic-v2.ini revision --autogenerate" + in revision + ) + parent = DYNAMIC_PARAMETER_TABLES_REVISION + assert re.search( + rf"""down_revision: Union\[str, None\] = ["']{parent}["']""", revision + ) + assert "correction" not in revision.lower() + operations = [name for name in re.findall(r"op\.\w+", upgrade) if name != "op.f"] + assert sorted(operations) == [ + "op.create_index", + "op.drop_column", + "op.drop_constraint", + "op.drop_constraint", + "op.drop_index", + "op.drop_index", + ] + reversals = [name for name in re.findall(r"op\.\w+", downgrade) if name != "op.f"] + assert sorted(reversals) == [ + "op.add_column", + "op.create_check_constraint", + "op.create_foreign_key", + "op.create_index", + "op.create_index", + "op.drop_index", + ] + assert re.findall( + rf"op\.drop_column\(\s*{index_name},\s*{index_name}", upgrade + ) == [("parameter_values", "dynamic_id")] + assert sorted(re.findall(rf"op\.drop_index\(\s*{index_name}", upgrade)) == [ + "uq_parameter_values_canonical_parameter_start_date", + "uq_parameter_values_dynamic_parameter_start_date", + ] + assert re.findall(rf"op\.create_index\(\s*{index_name}", upgrade) == [ + "uq_parameter_values_current_law_parameter_start_date" + ] + for dialect in ("postgresql", "sqlite"): + assert re.search( + rf"""{dialect}_where=sa\.text\(["']policy_id IS NULL["']\)""", upgrade + ) + assert "fk_parameter_values_dynamic_id_dynamics" in upgrade + assert "ck_parameter_values_single_owner" in upgrade + # The column comes back first, so the restored key, check and indexes can + # name it. + assert downgrade.index("op.add_column(") < downgrade.index( + "op.create_check_constraint(" + ) + assert sorted(re.findall(rf"op\.create_index\(\s*{index_name}", downgrade)) == [ + "uq_parameter_values_canonical_parameter_start_date", + "uq_parameter_values_dynamic_parameter_start_date", + ] + 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_alembic_v2_revisions.py b/tests/unit/v2/test_alembic_v2_revisions.py index 5cf4c5474..f0dc2e151 100644 --- a/tests/unit/v2/test_alembic_v2_revisions.py +++ b/tests/unit/v2/test_alembic_v2_revisions.py @@ -5,7 +5,6 @@ operations each one runs. """ -import importlib.util import re from pathlib import Path @@ -15,7 +14,6 @@ from policyengine_api.constants import REPO from policyengine_api.data.v2.migration_target import V2_ALEMBIC_HEAD_REVISION from policyengine_api.data.v2.models import V2_TABLE_NAMES -from policyengine_api.dynamic_parameters import DYNAMIC_PARAMETER_PREFIXES POST_BASELINE_TABLE_NAMES = frozenset( { @@ -84,16 +82,20 @@ # The user dynamics revision, on the report column drops revision, and parent # of the dynamic parameter tables revision. USER_DYNAMICS_REVISION = "d417fe8b1b17" -# The dynamic parameter tables revision, on the user dynamics revision. +# The dynamic parameter tables revision, on the user dynamics revision, and +# parent of the parameter values dynamic_id drop. DYNAMIC_PARAMETER_TABLES_REVISION = "7f7335f0eb31" +# The parameter values dynamic_id drop, on the dynamic parameter tables revision. +PARAMETER_VALUES_DYNAMIC_ID_DROP_REVISION = "1c651058fac5" 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 == DYNAMIC_PARAMETER_TABLES_REVISION + assert V2_ALEMBIC_HEAD_REVISION == PARAMETER_VALUES_DYNAMIC_ID_DROP_REVISION assert [revision.revision for revision in script.walk_revisions()] == [ + PARAMETER_VALUES_DYNAMIC_ID_DROP_REVISION, DYNAMIC_PARAMETER_TABLES_REVISION, USER_DYNAMICS_REVISION, REPORT_COLUMN_DROPS_REVISION, @@ -1158,78 +1160,6 @@ def test_user_invitations_revision_adds_its_table_and_the_dismissal_column() -> assert "source IN ('admin_route', 'script', 'invitation')" in upgrade -def test_dynamics_revision_stores_dynamics_like_policies_and_maps_them() -> None: - """The revision after user invitations stores dynamics as policies are stored. - - It is generated with no corrections: ``dynamics`` gains policies' five - columns, their two indexes, two unique constraints, three foreign keys - and two checks, and loses ``name`` and ``description``; - ``legacy_policy_mappings`` gains ``dynamic_id`` with its index and key; - ``parameter_values`` gains the partial unique index on dynamics' values. - The downgrade undoes each, and neither writes data. - """ - (path,) = (REPO / "migrations/v2/versions").glob(f"{DYNAMICS_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()") :] - - assert ( - "Generation: uv run alembic -c alembic-v2.ini revision --autogenerate" - in revision - ) - assert ( - f'down_revision: Union[str, None] = "{USER_INVITATIONS_REVISION}"' in revision - ) - assert "correction" not in revision.lower() - assert sorted(re.findall(r"op\.\w+", upgrade)) == sorted( - [ - *["op.add_column"] * 6, - *["op.create_index"] * 4, - *["op.create_unique_constraint"] * 2, - *["op.create_foreign_key"] * 4, - *["op.create_check_constraint"] * 2, - *["op.drop_column"] * 2, - # Two generated index names, three key names and two check names. - *["op.f"] * 7, - ] - ) - assert sorted(re.findall(r"op\.\w+", downgrade)) == sorted( - [ - *["op.drop_index"] * 4, - *["op.drop_constraint"] * 8, - *["op.drop_column"] * 6, - *["op.add_column"] * 2, - *["op.f"] * 7, - ] - ) - for column_name in ( - "country_id", - "tax_benefit_model_id", - "tax_benefit_model_version_id", - "canonicalization_version", - "content_hash", - ): - assert re.search( - rf'op\.add_column\(\s*"dynamics",\s*sa\.Column\(\s*"{column_name}",' - r"[^)]*\)?[^)]*nullable=False", - upgrade, - ) - assert re.search(r'op\.drop_column\("dynamics", "name"\)', upgrade) - assert re.search(r'op\.drop_column\("dynamics", "description"\)', upgrade) - assert re.search( - r'op\.add_column\(\s*"legacy_policy_mappings",\s*' - r'sa\.Column\("dynamic_id", sa\.Uuid\(\), nullable=True\)', - upgrade, - ) - assert "fk_legacy_policy_mappings_dynamic_country" in upgrade - assert "uq_parameter_values_dynamic_parameter_start_date" in upgrade - assert 'postgresql_where=sa.text("dynamic_id IS NOT NULL")' in upgrade - assert "op.execute(" not in revision - assert "op.bulk_insert(" not in revision - - def test_cliff_impacts_revision_creates_only_its_table_with_one_correction() -> None: """The revision after dynamics adds ``cliff_impacts``. @@ -1338,129 +1268,3 @@ def test_report_column_drops_revision_drops_only_the_named_columns() -> None: assert "op.execute(" not in body assert "op.bulk_insert(" not in body assert "op.drop_table(" not in body - - -def test_user_dynamics_revision_creates_only_the_saved_dynamics_table() -> None: - """The revision after report column drops creates ``user_dynamics`` alone. - - It is generated with no corrections, with its ID chosen through - ``--rev-id``: one table, whose keys name its user (``CASCADE``), its - country and a dynamic of that country (both ``RESTRICT``), with its - three indexes. The downgrade drops them, and neither writes data. - """ - (path,) = (REPO / "migrations/v2/versions").glob(f"{USER_DYNAMICS_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()") :] - - assert ( - "Generation: uv run alembic -c alembic-v2.ini revision --autogenerate" - in revision - ) - assert ( - f'down_revision: Union[str, None] = "{REPORT_COLUMN_DROPS_REVISION}"' - in revision - ) - assert "correction" not in revision.lower() - operations = [name for name in re.findall(r"op\.\w+", upgrade) if name != "op.f"] - assert sorted(operations) == ["op.create_index"] * 3 + ["op.create_table"] - reversals = [name for name in re.findall(r"op\.\w+", downgrade) if name != "op.f"] - assert sorted(reversals) == ["op.drop_index"] * 3 + ["op.drop_table"] - assert re.search(r'op\.create_table\(\s*"user_dynamics"', upgrade) - assert 'op.drop_table("user_dynamics")' in downgrade - for constraint_name in ( - "fk_user_dynamics_dynamic_country", - "uq_user_dynamics_id_country", - "ix_user_dynamics_country_user_created_id", - "ix_user_dynamics_country_dynamic", - ): - assert constraint_name in upgrade - assert re.search( - r'\["dynamic_id", "country_id"\],\s*\["dynamics\.id", "dynamics\.country_id"\]', - upgrade, - ) - assert upgrade.count('ondelete="RESTRICT"') == 2 - assert upgrade.count('ondelete="CASCADE"') == 1 - assert "op.execute(" not in revision - assert "op.bulk_insert(" not in revision - - -def _dynamic_parameter_tables_revision_path() -> Path: - (path,) = (REPO / "migrations/v2/versions").glob( - f"{DYNAMIC_PARAMETER_TABLES_REVISION}_*.py" - ) - return path - - -def test_dynamic_parameter_tables_revision_creates_two_tables_and_moves_rows() -> None: - """The revision after user dynamics adds the two tables, then moves rows. - - Its tables and indexes are generated. Its one data step is the user's - migration decision (C1 · 46, Q2), written by hand: after the generated - tables are created it moves every stored dynamic parameter and value into - them, and before the generated drops its downgrade moves them back. It has - no other correction. - """ - revision = _dynamic_parameter_tables_revision_path().read_text(encoding="utf-8") - upgrade = revision[ - revision.index("def upgrade()") : revision.index("def downgrade()") - ] - downgrade = revision[revision.index("def downgrade()") :] - parent = USER_DYNAMICS_REVISION - - assert ( - "Generation: uv run alembic -c alembic-v2.ini revision --autogenerate" - in revision - ) - assert re.search( - rf"""down_revision: Union\[str, None\] = ["']{parent}["']""", revision - ) - assert "C1 · 46" in revision - assert "Q2" in revision - assert re.findall(r"""op\.create_table\(\s*["'](\w+)["']""", upgrade) == [ - "dynamic_parameters", - "dynamic_parameter_values", - ] - assert sorted( - re.findall(r"""op\.create_index\(\s*(?:op\.f\()?["'](\w+)["']""", upgrade) - ) == [ - "ix_dynamic_parameter_values_parameter_period", - "ix_dynamic_parameters_tax_benefit_model_version_id", - "uq_dynamic_parameter_values_current_law_parameter_start_date", - "uq_dynamic_parameter_values_dynamic_parameter_start_date", - ] - assert sorted(re.findall(r"""op\.drop_table\(\s*["'](\w+)["']""", downgrade)) == [ - "dynamic_parameter_values", - "dynamic_parameters", - ] - assert revision.count("Approved hand-written data step") == 2 - assert "Post-generation correction" not in revision - assert "op.bulk_insert(" not in revision - move = upgrade.index("_move_dynamic_parameters_into_their_tables()") - assert upgrade.rindex("op.create_index(") < move - move_back = downgrade.index("_move_dynamic_parameters_back()") - assert move_back < downgrade.index("op.drop_index(") - for table in ("parameters", "parameter_values", "parameter_tree_children"): - assert f'op.drop_table("{table}")' not in revision - - -def test_dynamic_parameter_tables_revision_keeps_its_own_copy_of_the_prefixes() -> None: - """The revision classifies with a frozen copy that matches the package's. - - A revision runs once per database, so it never imports application code - that may change; publication compares the installed version's rows with - the package's own classification right after it. - """ - path = _dynamic_parameter_tables_revision_path() - source = path.read_text(encoding="utf-8") - spec = importlib.util.spec_from_file_location("dynamic_parameter_tables", path) - assert spec is not None - assert spec.loader is not None - revision = importlib.util.module_from_spec(spec) - spec.loader.exec_module(revision) - - assert "policyengine_api" not in source - package_prefixes = dict(DYNAMIC_PARAMETER_PREFIXES) - assert package_prefixes == revision.DYNAMIC_PARAMETER_PREFIXES diff --git a/tests/unit/v2/test_dynamic_table_models.py b/tests/unit/v2/test_dynamic_table_models.py index 2e068ecf7..b0242eb29 100644 --- a/tests/unit/v2/test_dynamic_table_models.py +++ b/tests/unit/v2/test_dynamic_table_models.py @@ -4,11 +4,8 @@ import sys from collections.abc import Iterator from contextlib import contextmanager -from datetime import UTC, datetime -from uuid import uuid4 import pytest -from sqlalchemy import insert from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import sessionmaker from sqlmodel import Session @@ -17,24 +14,17 @@ Dynamic, LegacyPolicyMapping, Parameter, - ParameterValue, Policy, TaxBenefitModel, TaxBenefitModelVersion, ) from tests.fixtures.database_sessions import sqlite_v2_sessions from tests.fixtures.v2_countries import add_listed_countries -from tests.integration.parameter_values_with_dynamics import ( - ParameterValueWithDynamic, -) from tests.unit.v2.v2_schema_reading import ( - declared_index, model_columns, stored_v2_table, ) -START_DATE = datetime(2026, 1, 1, tzinfo=UTC) - @contextmanager def _sqlite_sessions_with_foreign_keys() -> Iterator[sessionmaker[Session]]: @@ -106,23 +96,6 @@ def test_dynamics_have_policies_columns_and_no_name_or_description() -> None: } -def test_a_dynamic_s_values_are_unique_per_parameter_and_start_date() -> None: - index = declared_index( - ParameterValue, "uq_parameter_values_dynamic_parameter_start_date" - ) - - assert index.unique - assert tuple(column.name for column in index.columns) == ( - "dynamic_id", - "parameter_id", - "start_date", - ) - assert str(index.dialect_options["postgresql"]["where"]) == ( - "dynamic_id IS NOT NULL" - ) - assert str(index.dialect_options["sqlite"]["where"]) == "dynamic_id IS NOT NULL" - - def test_legacy_policy_mappings_name_an_optional_dynamic_of_their_country() -> None: mappings = stored_v2_table("legacy_policy_mappings") @@ -156,41 +129,6 @@ def test_identical_dynamic_content_is_stored_once() -> None: session.commit() -def test_a_dynamic_sets_one_value_per_parameter_and_start_date() -> None: - """The table keeps the rule while it keeps ``dynamic_id``. - - ``ParameterValue`` no longer maps the column, so the values are written - through the column-only ``ParameterValueWithDynamic``. - """ - model, version, parameter = _catalog() - - with ( - _sqlite_sessions_with_foreign_keys() as sessions, - sessions(expire_on_commit=True) as session, - ): - session.add_all([model, version, parameter]) - session.commit() - dynamic = _dynamic(model, version) - session.add(dynamic) - session.commit() - dynamic_value = { - "parameter_id": parameter.id, - "dynamic_id": dynamic.id, - "start_date": START_DATE, - } - session.execute( - insert(ParameterValueWithDynamic).values( - id=uuid4(), value_json=0.1, **dynamic_value - ) - ) - with pytest.raises(IntegrityError, match="UNIQUE constraint failed"): - session.execute( - insert(ParameterValueWithDynamic).values( - id=uuid4(), value_json=0.2, **dynamic_value - ) - ) - - def test_a_mapping_cannot_name_another_country_s_dynamic() -> None: model, version, _parameter = _catalog() diff --git a/tests/unit/v2/test_model_persistence.py b/tests/unit/v2/test_model_persistence.py index 569976731..1ab9cec8f 100644 --- a/tests/unit/v2/test_model_persistence.py +++ b/tests/unit/v2/test_model_persistence.py @@ -4,7 +4,7 @@ from contextlib import contextmanager from datetime import UTC, datetime, timedelta from pathlib import Path -from uuid import UUID, uuid4 +from uuid import UUID import pytest import sqlalchemy as sa @@ -13,7 +13,6 @@ from policyengine_api.data.v2.models import ( Country, - Dynamic, Household, LegacyPolicyMapping, LegacyUserMapping, @@ -30,9 +29,6 @@ from policyengine_api.data.v2.models.base import DIRECT_SQLALCHEMY_EXCEPTIONS from tests.fixtures.database_sessions import sqlite_v2_sessions from tests.fixtures.v2_countries import add_listed_countries -from tests.integration.parameter_values_with_dynamics import ( - ParameterValueWithDynamic, -) @contextmanager @@ -98,7 +94,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()) @@ -265,37 +260,13 @@ def test_policy_content_hash_is_unique_per_canonicalization_version() -> None: session.commit() -def test_policy_parameter_value_owner_period_and_identity_constraints() -> None: - model, version, parameter, policy = _policy_graph(content_hash="b" * 64) - dynamic = Dynamic( - country_id="us", - tax_benefit_model_id=model.id, - tax_benefit_model_version_id=version.id, - canonicalization_version=1, - content_hash="d" * 64, - ) +def test_policy_parameter_value_period_and_identity_constraints() -> None: + _model, _version, parameter, policy = _policy_graph(content_hash="b" * 64) start = datetime(2026, 1, 1, tzinfo=UTC) with _relational_sqlite_session() as session: session.add_all([parameter, policy]) session.commit() - session.add(dynamic) - session.commit() - - # ParameterValue no longer maps dynamic_id, which the table keeps - # until C1 · 53 drops it with the check. - with pytest.raises(IntegrityError, match="ck_parameter_values_single_owner"): - session.execute( - sa.insert(ParameterValueWithDynamic).values( - id=uuid4(), - parameter_id=parameter.id, - policy_id=policy.id, - dynamic_id=dynamic.id, - value_json={"rate": 0.1}, - start_date=start, - ) - ) - session.rollback() invalid_period = ParameterValue( parameter_id=parameter.id, diff --git a/tests/unit/v2/test_models.py b/tests/unit/v2/test_models.py index 2233742f2..2359c7d6c 100644 --- a/tests/unit/v2/test_models.py +++ b/tests/unit/v2/test_models.py @@ -207,10 +207,7 @@ def test_policy_parameter_values_use_jsonb_and_enforce_period_identity() -> None postgres_type = columns.value_json.type.dialect_impl(postgresql.dialect()) assert isinstance(postgres_type, postgresql.JSONB) - assert { - "ck_parameter_values_single_owner", - "ck_parameter_values_effective_period", - } <= values.constraint_names + assert "ck_parameter_values_effective_period" in values.constraint_names assert ("policy_id", "parameter_id", "start_date") in values.unique_column_sets assert sa.inspect(ParameterValue).relationships["policy"].back_populates == ( "parameter_values" @@ -478,13 +475,12 @@ def test_named_checks_and_required_indexes_cover_core_invariants() -> None: "ck_countries_society_wide_requires_household", "ck_report_runs_terminal_completion", "ck_simulation_runs_terminal_completion", - "ck_parameter_values_single_owner", }.issubset(constraint_names) assert { "ix_users_email", "ix_simulation_runs_current_output", "ix_report_runs_current_output", - "uq_parameter_values_canonical_parameter_start_date", + "uq_parameter_values_current_law_parameter_start_date", }.issubset(index_names) @@ -517,9 +513,14 @@ def test_stage9_uses_policyengine_version_as_its_only_catalog_release_identity() assert ("model_id", "version") in unique_column_sets -def test_canonical_parameter_values_have_a_postgres_partial_unique_index() -> None: +def test_current_law_parameter_values_have_a_partial_unique_index() -> None: + """A parameter has one current-law value per start date: a value with no policy. + + Revision 1c651058fac5 renamed the index when its condition lost + ``dynamic_id``: Alembic compares an index's condition by its name only. + """ index = declared_index( - ParameterValue, "uq_parameter_values_canonical_parameter_start_date" + ParameterValue, "uq_parameter_values_current_law_parameter_start_date" ) assert index.unique @@ -527,32 +528,24 @@ def test_canonical_parameter_values_have_a_postgres_partial_unique_index() -> No "parameter_id", "start_date", ) - predicate = str(index.dialect_options["postgresql"]["where"]) - assert predicate == "policy_id IS NULL AND dynamic_id IS NULL" + assert str(index.dialect_options["postgresql"]["where"]) == "policy_id IS NULL" + assert str(index.dialect_options["sqlite"]["where"]) == "policy_id IS NULL" -def test_parameter_values_keep_dynamic_id_which_the_model_no_longer_maps() -> None: - """API v1 names no ``parameter_values.dynamic_id``; the table keeps it for now. +def test_parameter_values_hold_only_policy_and_current_law_values() -> None: + """A dynamic's values are ``dynamic_parameter_values`` rows since C1 · 50. - The deploy upgrades the schema before the new release takes traffic, so - the release still serving when C1 · 53 drops the column must not name it, - and a whole-row load names every mapped column. The table keeps the - column, its key to ``dynamics``, the single-owner check and both partial - indexes that name it until that revision. + ``parameter_values`` has no ``dynamic_id`` column, no key to ``dynamics``, + no check that a row names one owner, and no index of a dynamic's values. """ values = stored_v2_table("parameter_values") + assert "dynamic_id" not in values.columns assert "dynamic_id" not in model_columns(ParameterValue) - assert "dynamic_id" not in sa.inspect(ParameterValue).attrs - assert "dynamic_id" in values.columns - assert [key.columns for key in values.foreign_keys_to("dynamics")] == [ - ("dynamic_id",) - ] - assert "ck_parameter_values_single_owner" in values.constraint_names - assert { - "uq_parameter_values_dynamic_parameter_start_date", - "uq_parameter_values_canonical_parameter_start_date", - } <= set(values.indexes) + assert values.foreign_keys_to("dynamics") == () + assert "ck_parameter_values_single_owner" not in values.constraint_names + assert "uq_parameter_values_dynamic_parameter_start_date" not in values.indexes + assert "uq_parameter_values_canonical_parameter_start_date" not in values.indexes def test_a_whole_parameter_value_read_names_no_dynamic_id() -> None: