From 3685235efce74151647f29a0861ff73d77b3bdfb Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:41:32 +0400 Subject: [PATCH 1/4] =?UTF-8?q?C1=20=C2=B7=2053:=20tests=20for=20dropping?= =?UTF-8?q?=20parameter=5Fvalues.dynamic=5Fid=20(failing)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Revision 1c651058fac5 is to drop parameter_values.dynamic_id with its key to dynamics, ck_parameter_values_single_owner and the per-dynamic partial unique index, and to replace the current-law index, whose condition named the column, with uq_parameter_values_current_law_parameter_start_date on policy_id IS NULL. - A Postgres test of the revision: the schema change and its exact downgrade against the parent built from the base, surviving rows and the new index, a downgrade through 7f7335f0eb31 and back, what a row still naming a dynamic becomes, and the deploy's privilege steps. - The revision chain, the generated operations, the model's columns, checks and indexes, the lifecycle head check and CI's lifecycle script. - Tests that stored or read a dynamic's value in parameter_values at the head drop it; tests of earlier revisions use ParameterValueWithDynamic, a column-only class of the table as those revisions leave it. - The dynamics revisions' unit tests move, unchanged, from test_alembic_v2_revisions to test_alembic_v2_dynamic_revisions, which keeps the first under the 1,500-line limit for test code. Co-Authored-By: Claude Opus 5.5 --- .../parameter_values_with_dynamics.py | 41 ++ ...est_alembic_v2_dynamic_parameter_tables.py | 18 +- tests/integration/test_alembic_v2_dynamics.py | 47 +- .../integration/test_alembic_v2_lifecycle.py | 18 +- ...bic_v2_parameter_values_dynamic_id_drop.py | 546 ++++++++++++++++++ ..._catalog_publication_dynamic_parameters.py | 1 - .../test_v2_catalog_publication_pruning.py | 35 +- .../test_v2_dynamic_persistence.py | 16 +- tests/unit/test_alembic_workflows.py | 2 + .../v2/test_alembic_v2_dynamic_revisions.py | 302 ++++++++++ tests/unit/v2/test_alembic_v2_revisions.py | 208 +------ tests/unit/v2/test_dynamic_table_models.py | 47 -- .../test_metadata_service_pruned_versions.py | 1 - tests/unit/v2/test_model_persistence.py | 26 +- tests/unit/v2/test_models.py | 37 +- 15 files changed, 976 insertions(+), 369 deletions(-) create mode 100644 tests/integration/parameter_values_with_dynamics.py create mode 100644 tests/integration/test_alembic_v2_parameter_values_dynamic_id_drop.py create mode 100644 tests/unit/v2/test_alembic_v2_dynamic_revisions.py diff --git a/tests/integration/parameter_values_with_dynamics.py b/tests/integration/parameter_values_with_dynamics.py new file mode 100644 index 000000000..4af0c111d --- /dev/null +++ b/tests/integration/parameter_values_with_dynamics.py @@ -0,0 +1,41 @@ +"""``parameter_values`` as the revisions before 1c651058fac5 leave it. + +Until revision 1c651058fac5 the table has ``dynamic_id``, a dynamic's values +were stored in it (until revision 7f7335f0eb31 moved them to +``dynamic_parameter_values``), and the downgrade through 7f7335f0eb31 copies +them back. ``ParameterValue`` no longer maps the column, so tests of those +revisions store and read such rows through this class, on a registry of its +own. No code creates a table from it: Alembic creates the table. +""" + +# No ``from __future__ import annotations``: SQLAlchemy reads the class's +# ``Mapped`` annotations when it maps it, so their names stay imported at +# runtime. +from datetime import datetime +from typing import Any +from uuid import UUID + +from sqlalchemy import DateTime +from sqlalchemy.dialects import postgresql +from sqlalchemy.orm import Mapped, mapped_column, registry + +parameter_values_with_dynamics = registry() + + +@parameter_values_with_dynamics.mapped +class ParameterValueWithDynamic: + """A ``parameter_values`` row with the ``dynamic_id`` it had before 1c651058fac5. + + ``created_at`` is filled in by the database when an insert leaves it out. + """ + + __tablename__ = "parameter_values" + + id: Mapped[UUID] = mapped_column(primary_key=True) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True)) + parameter_id: Mapped[UUID] + value_json: Mapped[Any] = mapped_column(postgresql.JSONB) + start_date: Mapped[datetime] = mapped_column(DateTime(timezone=True)) + end_date: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + policy_id: Mapped[UUID | None] + dynamic_id: Mapped[UUID | None] diff --git a/tests/integration/test_alembic_v2_dynamic_parameter_tables.py b/tests/integration/test_alembic_v2_dynamic_parameter_tables.py index 807495ab1..c9288a80d 100644 --- a/tests/integration/test_alembic_v2_dynamic_parameter_tables.py +++ b/tests/integration/test_alembic_v2_dynamic_parameter_tables.py @@ -47,6 +47,9 @@ from tests.fixtures.database_sessions import schema_inspector from tests.fixtures.integration.alembic_v2 import alembic_v2_config from tests.integration.alembic_version_rows import current_revision +from tests.integration.parameter_values_with_dynamics import ( + ParameterValueWithDynamic, +) from tests.integration.simulation_rows import add_row, refused if TYPE_CHECKING: @@ -284,7 +287,7 @@ def _store_country(session: Session, country_id: str) -> StoredCountry: for name in DYNAMIC_PARAMETERS[country_id]: add_row( session, - ParameterValue, + ParameterValueWithDynamic, id=uuid4(), parameter_id=stored.parameter_ids[name], dynamic_id=stored.dynamic_id, @@ -415,7 +418,10 @@ def _parameter_rows(session: Session, model: Any, version_ids: list[UUID]) -> se def _parameter_value_rows(session: Session, version_ids: list[UUID]) -> set: - """Return ``parameter_values`` rows of the versions' parameters.""" + """Return ``parameter_values`` rows of the versions' parameters. + + The table has ``dynamic_id`` at the revisions these tests read it at. + """ return { ( row.id, @@ -428,8 +434,10 @@ def _parameter_value_rows(session: Session, version_ids: list[UUID]) -> set: row.dynamic_id, ) for row in session.scalars( - select(ParameterValue) - .join(Parameter, col(Parameter.id) == col(ParameterValue.parameter_id)) + select(ParameterValueWithDynamic) + .join( + Parameter, col(Parameter.id) == ParameterValueWithDynamic.parameter_id + ) .where(col(Parameter.tax_benefit_model_version_id).in_(version_ids)) ) } @@ -955,7 +963,7 @@ def test_the_upgrade_refuses_while_a_dynamic_value_names_a_policy_parameter( with sessions.begin() as session: add_row( session, - ParameterValue, + ParameterValueWithDynamic, id=value_id, parameter_id=us.parameter_ids[US_POLICY_PARAMETER], dynamic_id=us.dynamic_id, diff --git a/tests/integration/test_alembic_v2_dynamics.py b/tests/integration/test_alembic_v2_dynamics.py index 4fab71132..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,8 +23,6 @@ from policyengine_api.data.v2.models import ( Dynamic, LegacyPolicyMapping, - Parameter, - ParameterValue, Policy, ) from tests.fixtures.database_sessions import schema_inspector @@ -156,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( @@ -249,36 +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: +def test_a_dynamic_is_stored_once(session: Session) -> None: + """A dynamic is unique by its content hash, which has 64 characters. + + 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, ParameterValue, id=uuid4(), **value) - with refused(session, match="uq_parameter_values_dynamic_parameter_start_date"): - add_row(session, ParameterValue, 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, - ParameterValue, - 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_catalog_publication_dynamic_parameters.py b/tests/integration/test_v2_catalog_publication_dynamic_parameters.py index a83b28613..130af3ee4 100644 --- a/tests/integration/test_v2_catalog_publication_dynamic_parameters.py +++ b/tests/integration/test_v2_catalog_publication_dynamic_parameters.py @@ -146,7 +146,6 @@ def _current_law_values( .where( col(Parameter.tax_benefit_model_version_id) == version_id, col(ParameterValue.policy_id).is_(None), - col(ParameterValue.dynamic_id).is_(None), ) ) dynamic_values = session.execute( diff --git a/tests/integration/test_v2_catalog_publication_pruning.py b/tests/integration/test_v2_catalog_publication_pruning.py index 74c4ebe90..630f5e1a8 100644 --- a/tests/integration/test_v2_catalog_publication_pruning.py +++ b/tests/integration/test_v2_catalog_publication_pruning.py @@ -189,7 +189,6 @@ def _prunable_rows( .where( col(Parameter.tax_benefit_model_version_id) == version_id, col(ParameterValue.policy_id).is_(None), - col(ParameterValue.dynamic_id).is_(None), ) .order_by(col(ParameterValue.id)), ), @@ -257,7 +256,11 @@ def _kept_rows(sessions: sessionmaker[Session], model_name: str, version: str) - def _owned_rows(sessions: sessionmaker[Session]) -> dict[str, list[tuple]]: - """Return every policy, dynamic and value a policy or dynamic owns.""" + """Return every policy, dynamic and value a policy owns. + + A dynamic's values are ``dynamic_parameter_values`` rows, whose pruning + ``test_v2_catalog_publication_dynamic_parameters`` checks. + """ return { "owned_values": _rows( sessions, @@ -269,14 +272,8 @@ def _owned_rows(sessions: sessionmaker[Session]) -> dict[str, list[tuple]]: col(ParameterValue.start_date), col(ParameterValue.end_date), col(ParameterValue.policy_id), - col(ParameterValue.dynamic_id), - ) - .where( - sa.or_( - col(ParameterValue.policy_id).is_not(None), - col(ParameterValue.dynamic_id).is_not(None), - ) ) + .where(col(ParameterValue.policy_id).is_not(None)) .order_by(col(ParameterValue.id)), ), "policies": _rows( @@ -291,7 +288,7 @@ def _owned_rows(sessions: sessionmaker[Session]) -> dict[str, list[tuple]]: def _add_saved_reform_and_dynamic( sessions: sessionmaker[Session], version: str ) -> None: - """Store a policy and a dynamic, each with its own value of a US parameter.""" + """Store a policy with its own value of a US parameter, and a dynamic.""" with sessions() as session: model = session.exec( select(TaxBenefitModel).where(TaxBenefitModel.name == US_MODEL) @@ -332,12 +329,6 @@ def _add_saved_reform_and_dynamic( start_date=datetime(2026, 1, 1, tzinfo=UTC), policy_id=policy.id, ), - ParameterValue( - parameter_id=parameter.id, - value_json=0.3, - start_date=datetime(2026, 1, 1, tzinfo=UTC), - dynamic_id=dynamic.id, - ), ] ) session.commit() @@ -389,10 +380,10 @@ def test_publication_prunes_versions_older_than_the_kept_ones_as_the_writer( ) -> None: """Pruning deletes exactly the old version's current-law data, as the writer. - The old version holds a saved reform and a dynamic, each with its own - value. Only the old version's current-law values, tree rows and search - file go; its marker is set. The kept versions, the reform, the dynamic, - their values, the old version's parameters and every other row stay. + The old version holds a saved reform with its own value, and a dynamic. + Only the old version's current-law values, tree rows and search file go; + its marker is set. The kept versions, the reform and its value, the + dynamic, the old version's parameters and every other row stay. """ writer_sessions = v2_sessions_as_role(CATALOG_WRITER_ROLE) _publish(writer_sessions, OLD_VERSION) @@ -417,7 +408,8 @@ def test_publication_prunes_versions_older_than_the_kept_ones_as_the_writer( _fixture_pruned("us", OLD_VERSION), ) assert third.catalog_pruning_failures == () - assert len(owned_before["owned_values"]) == 2 + assert len(owned_before["owned_values"]) == 1 + assert len(owned_before["dynamics"]) == 1 assert _owned_rows(publication_sessions) == owned_before for model_name in MODEL_NAMES: old_kept, old_prunable = before[(model_name, OLD_VERSION)] @@ -999,7 +991,6 @@ def test_a_version_without_current_law_rows_is_marked_pruned_with_zero_counts( session.execute( sa.delete(ParameterValue).where( col(ParameterValue.policy_id).is_(None), - col(ParameterValue.dynamic_id).is_(None), col(ParameterValue.parameter_id).in_( sa.select(col(Parameter.id)).where( col(Parameter.tax_benefit_model_version_id) == us_old_id diff --git a/tests/integration/test_v2_dynamic_persistence.py b/tests/integration/test_v2_dynamic_persistence.py index a209ef40c..05d320173 100644 --- a/tests/integration/test_v2_dynamic_persistence.py +++ b/tests/integration/test_v2_dynamic_persistence.py @@ -110,12 +110,7 @@ def _remove_catalog( ) ) session.execute( - delete(ParameterValue).where( - or_( - ParameterValue.policy_id.in_(policy_ids), - ParameterValue.dynamic_id.in_(dynamic_ids), - ) - ) + delete(ParameterValue).where(ParameterValue.policy_id.in_(policy_ids)) ) session.execute( delete(DynamicParameterValue).where( @@ -229,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( @@ -239,12 +235,6 @@ def _stored_names(session: Session, *, policy_id=None, dynamic_id=None) -> set[s .where(ParameterValue.policy_id == policy_id) ) ) - assert ( - session.scalars( - select(ParameterValue.id).where(ParameterValue.dynamic_id == dynamic_id) - ).all() - == [] - ) return set( session.scalars( select(DynamicParameter.name) 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 544b2f70c..b0242eb29 100644 --- a/tests/unit/v2/test_dynamic_table_models.py +++ b/tests/unit/v2/test_dynamic_table_models.py @@ -4,7 +4,6 @@ import sys from collections.abc import Iterator from contextlib import contextmanager -from datetime import UTC, datetime import pytest from sqlalchemy.exc import IntegrityError @@ -15,7 +14,6 @@ Dynamic, LegacyPolicyMapping, Parameter, - ParameterValue, Policy, TaxBenefitModel, TaxBenefitModelVersion, @@ -23,13 +21,10 @@ from tests.fixtures.database_sessions import sqlite_v2_sessions from tests.fixtures.v2_countries import add_listed_countries 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]]: @@ -101,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") @@ -151,31 +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: - 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() - for value in (0.1, 0.2): - session.add( - ParameterValue( - parameter_id=parameter.id, - dynamic_id=dynamic.id, - value_json=value, - start_date=START_DATE, - ) - ) - with pytest.raises(IntegrityError, match="UNIQUE constraint failed"): - session.commit() - - def test_a_mapping_cannot_name_another_country_s_dynamic() -> None: model, version, _parameter = _catalog() diff --git a/tests/unit/v2/test_metadata_service_pruned_versions.py b/tests/unit/v2/test_metadata_service_pruned_versions.py index 8f42df5cc..3ad40831f 100644 --- a/tests/unit/v2/test_metadata_service_pruned_versions.py +++ b/tests/unit/v2/test_metadata_service_pruned_versions.py @@ -137,7 +137,6 @@ def _prune_us_version(session: Session) -> None: select(ParameterValue).where( col(ParameterValue.parameter_id).in_(version_parameter_ids), col(ParameterValue.policy_id).is_(None), - col(ParameterValue.dynamic_id).is_(None), ) ).all() tree_rows = session.exec( diff --git a/tests/unit/v2/test_model_persistence.py b/tests/unit/v2/test_model_persistence.py index e492687d1..1ab9cec8f 100644 --- a/tests/unit/v2/test_model_persistence.py +++ b/tests/unit/v2/test_model_persistence.py @@ -13,7 +13,6 @@ from policyengine_api.data.v2.models import ( Country, - Dynamic, Household, LegacyPolicyMapping, LegacyUserMapping, @@ -261,34 +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() - - invalid_owner = ParameterValue( - parameter_id=parameter.id, - policy_id=policy.id, - dynamic_id=dynamic.id, - value_json={"rate": 0.1}, - start_date=start, - ) - session.add(invalid_owner) - with pytest.raises(IntegrityError): - session.commit() - 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 8271ecceb..4aedf21b3 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,8 +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_hold_only_policy_and_current_law_values() -> None: + """A dynamic's values are ``dynamic_parameter_values`` rows since C1 · 50. + + ``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 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_complete_metadata_compiles_for_postgres_without_mutation() -> None: From 57daf08840ac8f0a1a63f9fdecfec7df549dd858 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:45:21 +0400 Subject: [PATCH 2/4] =?UTF-8?q?C1=20=C2=B7=2053:=20drop=20parameter=5Fvalu?= =?UTF-8?q?es.dynamic=5Fid?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Revision 1c651058fac5, on 7f7335f0eb31, autogenerated with no corrections after ParameterValue lost dynamic_id, ck_parameter_values_single_owner and uq_parameter_values_dynamic_parameter_start_date. 7f7335f0eb31 moved every dynamic's values to dynamic_parameter_values, so a parameter_values row is now a policy's value or a current-law value. PostgreSQL drops an index whose condition names a dropped column, and Alembic compares an index's condition by name only, so the current-law index is renamed uq_parameter_values_current_law_parameter_start_date, on policy_id IS NULL (the user's decision 2). The downgrade restores the column, its key, the check and both indexes, which 7f7335f0eb31's downgrade needs to copy dynamics' values back. - Current-law reads, publication's comparison and uniqueness check, pruning and publication's insert no longer name dynamic_id; a policy's values are inserted without it. - V2_ALEMBIC_HEAD_REVISION, CI's lifecycle script, the alembic-migrations skill (a section with the deploy order and the operator's read-only count, the user's decisions 1 and 3), the Stage 9 guide and the testing skill follow. - No role's privilege names the column. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/test_alembic_v2_lifecycle.sh | 4 +- .../v2-parameter-values-dynamic-id.removed.md | 1 + docs/engineering/skills/alembic-migrations.md | 88 +++++++++++++++++-- docs/engineering/skills/testing.md | 3 +- docs/migration/stage-9-v2-metadata.md | 4 +- ...58fac5_drop_parameter_values_dynamic_id.py | 57 ++++++++++++ .../data/v2/catalog/publication_inserts.py | 2 - .../data/v2/catalog/publication_pruning.py | 5 +- .../v2/catalog/publication_reconciliation.py | 11 +-- policyengine_api/data/v2/migration_target.py | 2 +- policyengine_api/data/v2/models/metadata.py | 40 +++------ policyengine_api/data/v2/privileges.py | 4 +- .../database_connectors/reads_parameters.py | 18 ++-- .../policies/database_connectors/creates.py | 1 - 14 files changed, 173 insertions(+), 67 deletions(-) create mode 100644 changelog.d/v2-parameter-values-dynamic-id.removed.md create mode 100644 migrations/v2/versions/1c651058fac5_drop_parameter_values_dynamic_id.py 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 4a7c0268a..2d093a4d4 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -712,7 +712,7 @@ publication advisory lock, reads the model's stored versions again, skips the version if the rule no longer chooses it, and otherwise deletes exactly: - the version's current-law `parameter_values`: rows of the version's - parameters whose `policy_id` and `dynamic_id` are both null; + parameters whose `policy_id` is null; - the version's current-law `dynamic_parameter_values`: rows of the version's dynamic parameters whose `dynamic_id` is null (since revision `7f7335f0eb31`, by the user's decision C1 · 46, Q3); @@ -725,8 +725,7 @@ never deletes or changes any other row: not `parameters` or reforms' and dynamics' included), not the `tax_benefit_model_versions` row apart from that column, and not `parameter_nodes`, `variables`, `regions`, `datasets`, `policies`, `dynamics`, any `parameter_values` row with a -`policy_id` or `dynamic_id`, or any `dynamic_parameter_values` row with a -`dynamic_id`. +`policy_id`, or any `dynamic_parameter_values` row with a `dynamic_id`. A transaction that raises an exception, of any kind, rolls back that version alone; the failure is reported in the command's evidence and on stderr, the command still succeeds, and the next publication tries again. @@ -756,6 +755,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 +1358,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,10 +1712,84 @@ 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. `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. `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 · 50 + leaves it out of the mapper (the user's decision 1 for C1 · 53), and every + release since C1 · 50's revision deployed contains that change. +- 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/docs/migration/stage-9-v2-metadata.md b/docs/migration/stage-9-v2-metadata.md index 1da3c0fd7..e635061a5 100644 --- a/docs/migration/stage-9-v2-metadata.md +++ b/docs/migration/stage-9-v2-metadata.md @@ -641,8 +641,8 @@ of a new version took 17 to 20 minutes in production, inside the job's `policyengine_api/data/v2/catalog/publication_pruning.py`. Pruning a version runs one transaction that deletes its current-law -`parameter_values` (rows of its parameters with neither a `policy_id` nor a -`dynamic_id`), its current-law `dynamic_parameter_values` (rows of its +`parameter_values` (rows of its parameters with no `policy_id`), its +current-law `dynamic_parameter_values` (rows of its dynamic parameters with no `dynamic_id`), its `parameter_tree_children` rows and its `parameter_search_files` rows, and sets its `catalog_values_pruned_at`. It never deletes `parameters` or 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/catalog/publication_inserts.py b/policyengine_api/data/v2/catalog/publication_inserts.py index 3935174a0..f149e6e25 100644 --- a/policyengine_api/data/v2/catalog/publication_inserts.py +++ b/policyengine_api/data/v2/catalog/publication_inserts.py @@ -327,7 +327,6 @@ def _parameters_insert( "start_date", "end_date", "policy_id", - "dynamic_id", ], sa.select( col(StagedParameterValue.id), @@ -340,7 +339,6 @@ def _parameters_insert( col(StagedParameterValue.start_date), col(StagedParameterValue.end_date), sa.cast(sa.null(), column_type(ParameterValue, "policy_id")), - sa.cast(sa.null(), column_type(ParameterValue, "dynamic_id")), ) .select_from( sa.join( diff --git a/policyengine_api/data/v2/catalog/publication_pruning.py b/policyengine_api/data/v2/catalog/publication_pruning.py index 4028fd157..8ec85c8b5 100644 --- a/policyengine_api/data/v2/catalog/publication_pruning.py +++ b/policyengine_api/data/v2/catalog/publication_pruning.py @@ -12,8 +12,8 @@ release whose promotion failed, or a rollback to an older version, since the release workflow seeds before it deploys. Pruning a version deletes exactly: -- its current-law parameter values: those of its parameters with neither a - policy nor a dynamic, and those of its dynamic parameters with no dynamic; +- its current-law parameter values: those of its parameters with no policy, + and those of its dynamic parameters with no dynamic; - its parameter tree rows; - its parameter search files; @@ -284,7 +284,6 @@ def prune_catalog_version(session: Session, version_id: UUID) -> PrunedRows | No sa.delete(ParameterValue).where( col(ParameterValue.parameter_id).in_(version_parameter_ids), col(ParameterValue.policy_id).is_(None), - col(ParameterValue.dynamic_id).is_(None), ), ) version_dynamic_parameter_ids = sa.select(col(DynamicParameter.id)).where( diff --git a/policyengine_api/data/v2/catalog/publication_reconciliation.py b/policyengine_api/data/v2/catalog/publication_reconciliation.py index 4edd09199..bcbfacdb6 100644 --- a/policyengine_api/data/v2/catalog/publication_reconciliation.py +++ b/policyengine_api/data/v2/catalog/publication_reconciliation.py @@ -345,7 +345,6 @@ def staged_parameter_values(*, dynamic: bool) -> Select: .where( selected_version, col(ParameterValue.policy_id).is_(None), - col(ParameterValue.dynamic_id).is_(None), ) ) @@ -579,15 +578,13 @@ def count_region_differences( def assert_canonical_value_uniqueness(session: Session) -> None: """Raise CatalogPublicationError if a parameter has duplicate current-law values. - Current-law values are those with neither a policy nor a dynamic, in - either table; each parameter may have only one per start date. + Current-law values are those with no policy in ``parameter_values`` and + those with no dynamic in ``dynamic_parameter_values``; each parameter may + have only one per start date. """ duplicates = ( sa.select(col(ParameterValue.parameter_id)) - .where( - col(ParameterValue.policy_id).is_(None), - col(ParameterValue.dynamic_id).is_(None), - ) + .where(col(ParameterValue.policy_id).is_(None)) .group_by( col(ParameterValue.parameter_id), col(ParameterValue.start_date), 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/metadata.py b/policyengine_api/data/v2/models/metadata.py index ca41b0097..761763ba6 100644 --- a/policyengine_api/data/v2/models/metadata.py +++ b/policyengine_api/data/v2/models/metadata.py @@ -430,18 +430,13 @@ 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. ``dynamic_id`` is no longer - written: a dynamic's values are ``DynamicParameterValue`` rows since - revision 7f7335f0eb31 moved them, and C1 · 53 drops the column, its check - and its index once no simulation service release maps it. + parameter has at most one per start date. A dynamic's values are + ``DynamicParameterValue`` rows: revision 7f7335f0eb31 moved them there, and + revision 1c651058fac5 dropped ``dynamic_id`` with its check and index. """ __tablename__ = "parameter_values" __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", @@ -452,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", @@ -471,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"), ), ) @@ -500,11 +485,6 @@ class ParameterValue(IdentifiedModel, table=True): foreign_key="policies.id", ondelete="CASCADE", ) - 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/policyengine_api/data/v2/privileges.py b/policyengine_api/data/v2/privileges.py index 5dc02fbbc..b210a37dc 100644 --- a/policyengine_api/data/v2/privileges.py +++ b/policyengine_api/data/v2/privileges.py @@ -305,8 +305,8 @@ def _run_table( runtime=READ, catalog_writer=READ_INSERT_DELETE | _ANALYZE ), # API v1 also inserts a v2 policy's own parameter values. Catalog pruning - # deletes an older version's current-law values (those with no policy or - # dynamic), never a policy's. Dynamics' values were moved to + # deletes an older version's current-law values (those with no policy), + # never a policy's. Dynamics' values were moved to # dynamic_parameter_values (C1 · 50). "parameter_values": _access( runtime=READ_INSERT, catalog_writer=READ_WRITE | _ANALYZE, **_RUN_INPUT_READS diff --git a/policyengine_api/services/v2/metadata/database_connectors/reads_parameters.py b/policyengine_api/services/v2/metadata/database_connectors/reads_parameters.py index c3cc7fc80..3ab7471fe 100644 --- a/policyengine_api/services/v2/metadata/database_connectors/reads_parameters.py +++ b/policyengine_api/services/v2/metadata/database_connectors/reads_parameters.py @@ -118,12 +118,11 @@ def read_parameter_values( ) -> list[ParameterValue]: """Return a page of a model version's current-law parameter values. - Values tied to a policy or dynamic are excluded. The selection's - parameter_id keeps one parameter's values, its parameter_names the values - of the parameters with those names, and its selected_day those in effect - on that day. Rows are ordered by parameter name, then newest - first, and limit + 1 are fetched so the caller can tell whether another - page exists. + A policy's values are excluded. The selection's parameter_id keeps one + parameter's values, its parameter_names the values of the parameters with + those names, and its selected_day those in effect on that day. Rows are + ordered by parameter name, then newest first, and limit + 1 are fetched + so the caller can tell whether another page exists. """ parameter_id = selection.parameter_id selected_day = selection.selected_day @@ -133,7 +132,6 @@ def read_parameter_values( .where( col(Parameter.tax_benefit_model_version_id) == model_version_id, col(ParameterValue.policy_id).is_(None), - col(ParameterValue.dynamic_id).is_(None), ) ) if parameter_id is not None: @@ -174,7 +172,6 @@ def read_parameter_value( col(ParameterValue.id) == value_id, col(Parameter.tax_benefit_model_version_id) == model_version_id, col(ParameterValue.policy_id).is_(None), - col(ParameterValue.dynamic_id).is_(None), ), ) return rows[0] if rows else None @@ -185,8 +182,8 @@ def read_current_law_values_by_parameter_name( ) -> list[CurrentLawValueRow]: """Return the current-law values of the named parameters of a model version. - Values tied to a policy or dynamic are excluded. Rows are ordered by - parameter name, then start date. + A policy's values are excluded. Rows are ordered by parameter name, then + start date. """ if not parameter_names: return [] @@ -203,7 +200,6 @@ def read_current_law_values_by_parameter_name( col(Parameter.tax_benefit_model_version_id) == model_version_id, col(Parameter.name).in_(sorted(parameter_names)), col(ParameterValue.policy_id).is_(None), - col(ParameterValue.dynamic_id).is_(None), ) .order_by(col(Parameter.name), col(ParameterValue.start_date)), ) diff --git a/policyengine_api/services/v2/policies/database_connectors/creates.py b/policyengine_api/services/v2/policies/database_connectors/creates.py index 8627aaf55..c9564e092 100644 --- a/policyengine_api/services/v2/policies/database_connectors/creates.py +++ b/policyengine_api/services/v2/policies/database_connectors/creates.py @@ -58,7 +58,6 @@ def create_parameter_values( [ ParameterValue( policy_id=policy_id, - dynamic_id=None, parameter_id=value.parameter_id, value_json=value.value, start_date=value.start_date, From 33e14c352f637a43bf9b4fc61aca1e604418a123 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:03:08 +0400 Subject: [PATCH 3/4] =?UTF-8?q?C1=20=C2=B7=2053:=20check=20that=20pruning?= =?UTF-8?q?=20keeps=20a=20dynamic's=20values=20(review=20round=201)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review round 1 found no bug. Its one code-quality finding: once parameter_values lost dynamic_id, no test stored a dynamic's value where pruning could delete it, so nothing noticed if pruning stopped keeping dynamic_parameter_values rows with a dynamic_id. The pruning test of the dynamic-parameter publication module now stores a US dynamic on the old version, with a value of one of its model assumptions from the date its current-law value starts, and checks it is still there after pruning. With pruning's dynamic_id IS NULL filter removed, the test fails. The pruning module's docstring names where this is checked. Co-Authored-By: Claude Opus 5.5 --- ..._catalog_publication_dynamic_parameters.py | 99 ++++++++++++++++++- .../test_v2_catalog_publication_pruning.py | 5 +- 2 files changed, 101 insertions(+), 3 deletions(-) diff --git a/tests/integration/test_v2_catalog_publication_dynamic_parameters.py b/tests/integration/test_v2_catalog_publication_dynamic_parameters.py index 130af3ee4..6be51a2a3 100644 --- a/tests/integration/test_v2_catalog_publication_dynamic_parameters.py +++ b/tests/integration/test_v2_catalog_publication_dynamic_parameters.py @@ -14,7 +14,7 @@ import gzip import json -from dataclasses import replace +from dataclasses import dataclass, replace from typing import TYPE_CHECKING, Any from uuid import UUID, uuid4 @@ -61,6 +61,7 @@ if TYPE_CHECKING: from collections.abc import Callable, Iterator + from datetime import datetime from sqlalchemy.orm import sessionmaker from sqlmodel import Session @@ -399,6 +400,96 @@ def _prunable_counts(sessions: sessionmaker[Session], version_id: UUID) -> dict: } +@dataclass(frozen=True) +class StoredDynamicValue: + """A dynamic's value the test stored: its ID, parameter, value and dates.""" + + id: UUID + dynamic_id: UUID + dynamic_parameter_id: UUID + value_json: Any + start_date: datetime + + +def _add_dynamic_value_on_a_current_law_date( + sessions: sessionmaker[Session], version_id: UUID +) -> StoredDynamicValue: + """Store a US dynamic of the version with a value of one of its assumptions. + + The value starts when the assumption's current-law value starts, so only + its ``dynamic_id`` tells pruning that it isn't current law. + """ + name = "simulation.marginal_tax_rate_delta" + parameter_id = _parameters_by_name(sessions, DynamicParameter, version_id)[name] + with sessions.begin() as session: + model_id, start_date = session.execute( + sa.select( + col(TaxBenefitModelVersion.model_id), + col(DynamicParameterValue.start_date), + ) + .join( + DynamicParameter, + col(DynamicParameter.tax_benefit_model_version_id) + == col(TaxBenefitModelVersion.id), + ) + .join( + DynamicParameterValue, + col(DynamicParameterValue.dynamic_parameter_id) + == col(DynamicParameter.id), + ) + .where( + col(DynamicParameter.id) == parameter_id, + col(DynamicParameterValue.dynamic_id).is_(None), + ) + ).one() + stored = StoredDynamicValue( + id=uuid4(), + dynamic_id=uuid4(), + dynamic_parameter_id=parameter_id, + value_json=5, + start_date=start_date, + ) + add_row( + session, + Dynamic, + id=stored.dynamic_id, + country_id="us", + tax_benefit_model_id=model_id, + tax_benefit_model_version_id=version_id, + canonicalization_version=1, + content_hash="e" * 64, + ) + add_row( + session, + DynamicParameterValue, + id=stored.id, + dynamic_parameter_id=stored.dynamic_parameter_id, + dynamic_id=stored.dynamic_id, + value_json=stored.value_json, + start_date=stored.start_date, + ) + return stored + + +def _dynamic_values( + sessions: sessionmaker[Session], dynamic_id: UUID +) -> list[StoredDynamicValue]: + """Return a dynamic's stored values, in the shape the test stored them.""" + with sessions() as session: + return [ + StoredDynamicValue(*row) + for row in session.execute( + sa.select( + col(DynamicParameterValue.id), + col(DynamicParameterValue.dynamic_id), + col(DynamicParameterValue.dynamic_parameter_id), + col(DynamicParameterValue.value_json), + col(DynamicParameterValue.start_date), + ).where(col(DynamicParameterValue.dynamic_id) == dynamic_id) + ) + ] + + def test_pruning_deletes_both_tables_current_law_values_and_restore_rewrites_them( publication_sessions: sessionmaker[Session], writer_sessions: sessionmaker[Session], @@ -413,6 +504,9 @@ def test_pruning_deletes_both_tables_current_law_values_and_restore_rewrites_the country_id: _version_id(publication_sessions, country_id, OLD_VERSION) for country_id in COUNTRY_IDS } + dynamic_value = _add_dynamic_value_on_a_current_law_date( + publication_sessions, old_ids["us"] + ) first_published = { country_id: _current_law_values(publication_sessions, version_id) for country_id, version_id in old_ids.items() @@ -456,6 +550,9 @@ def test_pruning_deletes_both_tables_current_law_values_and_restore_rewrites_the _parameters_by_name(publication_sessions, DynamicParameter, version_id) == dynamic_parameters[country_id] ) + assert _dynamic_values(publication_sessions, dynamic_value.dynamic_id) == [ + dynamic_value + ] rollback = _publish(writer_sessions, OLD_VERSION) diff --git a/tests/integration/test_v2_catalog_publication_pruning.py b/tests/integration/test_v2_catalog_publication_pruning.py index 630f5e1a8..365c92c05 100644 --- a/tests/integration/test_v2_catalog_publication_pruning.py +++ b/tests/integration/test_v2_catalog_publication_pruning.py @@ -258,8 +258,9 @@ def _kept_rows(sessions: sessionmaker[Session], model_name: str, version: str) - def _owned_rows(sessions: sessionmaker[Session]) -> dict[str, list[tuple]]: """Return every policy, dynamic and value a policy owns. - A dynamic's values are ``dynamic_parameter_values`` rows, whose pruning - ``test_v2_catalog_publication_dynamic_parameters`` checks. + A dynamic's values are ``dynamic_parameter_values`` rows, which this + module's catalog has no parameter for: that pruning keeps them is checked + in ``test_v2_catalog_publication_dynamic_parameters``. """ return { "owned_values": _rows( From cf2dfdd276f38beb9542039a4b5e05f7fbd8e5f8 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:36:48 +0400 Subject: [PATCH 4/4] =?UTF-8?q?C1=20=C2=B7=2053:=20name=20C1=20=C2=B7=2051?= =?UTF-8?q?a=20as=20the=20release=20that=20stops=20mapping=20dynamic=5Fid?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit C1 · 50 (#4347) merged without leaving dynamic_id out of ParameterValue's mapper, so the skill section's deploy order names C1 · 51a, which the user added to do it in its own release before this revision runs. Co-Authored-By: Claude Opus 5.5 --- docs/engineering/skills/alembic-migrations.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 2d093a4d4..fb758d1de 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -1763,9 +1763,10 @@ response unchanged. 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 · 50 - leaves it out of the mapper (the user's decision 1 for C1 · 53), and every - release since C1 · 50's revision deployed contains that change. +- 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.