From 9e3a4a6b02b24a388a2c343e50b31dc22e29cb60 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:09:24 +0400 Subject: [PATCH 1/4] =?UTF-8?q?C1=20=C2=B7=2051a:=20tests=20for=20no=20lon?= =?UTF-8?q?ger=20mapping=20parameter=5Fvalues.dynamic=5Fid=20(failing)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit API v1's ParameterValue is to leave dynamic_id out of its mapper, and no API v1 statement is to name the column, while the table keeps it with its key, check and both partial indexes. New tests check the mapper and the table, a whole-row read, the policy insert, publication's insert, comparison, uniqueness check and pruning, and the current-law reads. They fail now because the model maps the column and the code names it. Tests that set or read the column through the model write it through ParameterValueWithDynamic, the column-only class C1 · 53 adds (copied verbatim from 3685235ef), or drop it where it only filtered, with C1 · 53's own edits where they apply. 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 | 16 ++- ..._catalog_publication_dynamic_parameters.py | 100 +++++++++++++++++- .../test_v2_catalog_publication_pruning.py | 36 +++---- .../test_v2_dynamic_persistence.py | 16 +-- tests/unit/v2/test_catalog_publication.py | 44 ++++++++ tests/unit/v2/test_dynamic_table_models.py | 33 ++++-- tests/unit/v2/test_metadata_service.py | 44 ++++++++ .../test_metadata_service_pruned_versions.py | 1 - tests/unit/v2/test_model_persistence.py | 28 +++-- tests/unit/v2/test_models.py | 35 +++++- .../v2/test_policy_persistence_statements.py | 66 ++++++++++++ 13 files changed, 416 insertions(+), 62 deletions(-) create mode 100644 tests/integration/parameter_values_with_dynamics.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..abdebd3a7 100644 --- a/tests/integration/test_alembic_v2_dynamics.py +++ b/tests/integration/test_alembic_v2_dynamics.py @@ -25,12 +25,14 @@ Dynamic, LegacyPolicyMapping, Parameter, - ParameterValue, Policy, ) from tests.fixtures.database_sessions import schema_inspector from tests.fixtures.integration.alembic_v2 import alembic_v2_config, table_columns from tests.integration.alembic_version_rows import current_revision +from tests.integration.parameter_values_with_dynamics import ( + ParameterValueWithDynamic, +) from tests.integration.simulation_rows import ( PublicApiRows, add_row, @@ -252,6 +254,12 @@ def test_the_revision_changes_only_dynamics_their_values_and_mappings( def test_a_dynamic_is_stored_once_and_sets_one_value_per_parameter_and_date( session: Session, ) -> None: + """A dynamic is unique by its content hash, and its values as a policy's are. + + ``parameter_values`` keeps ``dynamic_id`` and the revision's partial unique + index until C1 · 53 drops them; ``ParameterValue`` no longer maps the + column, so the values are written through ``ParameterValueWithDynamic``. + """ rows = insert_public_api_rows(session) parameter_id = _insert_parameter(session, rows) dynamic_id = _insert_dynamic(session, rows) @@ -267,14 +275,14 @@ def test_a_dynamic_is_stored_once_and_sets_one_value_per_parameter_and_date( "value_json": 0.1, "start_date": datetime(2026, 1, 1, tzinfo=UTC), } - add_row(session, ParameterValue, id=uuid4(), **value) + add_row(session, ParameterValueWithDynamic, id=uuid4(), **value) with refused(session, match="uq_parameter_values_dynamic_parameter_start_date"): - add_row(session, ParameterValue, id=uuid4(), **value) + add_row(session, ParameterValueWithDynamic, id=uuid4(), **value) # Another dynamic may set the same parameter from the same date. other_dynamic_id = _insert_dynamic(session, rows, content_hash="e" * 64) add_row( session, - ParameterValue, + ParameterValueWithDynamic, id=uuid4(), **{**value, "dynamic_id": other_dynamic_id}, ) diff --git a/tests/integration/test_v2_catalog_publication_dynamic_parameters.py b/tests/integration/test_v2_catalog_publication_dynamic_parameters.py index a83b28613..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 @@ -146,7 +147,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( @@ -400,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], @@ -414,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() @@ -457,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 74c4ebe90..365c92c05 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,12 @@ 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, 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( sessions, @@ -269,14 +273,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 +289,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 +330,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 +381,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 +409,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 +992,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..4ed1945e9 100644 --- a/tests/integration/test_v2_dynamic_persistence.py +++ b/tests/integration/test_v2_dynamic_persistence.py @@ -39,6 +39,9 @@ ) from policyengine_api.services.v2.policies.services import V2PolicyService from policyengine_api.services.v2.policies.types import LegacyPolicySnapshot +from tests.integration.parameter_values_with_dynamics import ( + ParameterValueWithDynamic, +) if TYPE_CHECKING: from collections.abc import Callable, Iterator @@ -110,12 +113,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( @@ -239,9 +237,13 @@ def _stored_names(session: Session, *, policy_id=None, dynamic_id=None) -> set[s .where(ParameterValue.policy_id == policy_id) ) ) + # ParameterValue no longer maps the column, which the table keeps until + # C1 · 53 drops it. assert ( session.scalars( - select(ParameterValue.id).where(ParameterValue.dynamic_id == dynamic_id) + select(ParameterValueWithDynamic.id).where( + ParameterValueWithDynamic.dynamic_id == dynamic_id + ) ).all() == [] ) diff --git a/tests/unit/v2/test_catalog_publication.py b/tests/unit/v2/test_catalog_publication.py index 690f75e72..b76aeba46 100644 --- a/tests/unit/v2/test_catalog_publication.py +++ b/tests/unit/v2/test_catalog_publication.py @@ -22,6 +22,7 @@ from policyengine_api.data.v2.catalog import ( publication, publication_inserts, + publication_pruning, publication_reconciliation, publication_staging, publication_types, @@ -38,16 +39,20 @@ CatalogPublicationError, ) from policyengine_api.data.v2.migration_target import V2_ALEMBIC_HEAD_REVISION +from policyengine_api.data.v2.models import TaxBenefitModel, TaxBenefitModelVersion from policyengine_api.dynamic_parameters import ( is_dynamic_parameter, is_dynamic_parameter_path, ) +from tests.fixtures.database_sessions import recorded_statements, sqlite_v2_sessions from tests.fixtures.v2_catalog import ( catalog_with_dynamic_parameters, normalized_catalog, ) REPO = Path(__file__).parents[3] +# ``parameter_values.dynamic_id``, but not ``dynamic_parameter_values.dynamic_id``. +PARAMETER_VALUES_DYNAMIC_ID = re.compile(r"\bparameter_values\.dynamic_id\b") class FakeCopy: @@ -285,6 +290,45 @@ def execute(self, statement): assert str(publication.PUBLICATION_ADVISORY_LOCK_KEY) in compiled_lock +def test_publication_names_no_parameter_values_dynamic_id() -> None: + """Publication selects and writes current-law values by ``policy_id`` alone. + + C1 · 53 drops ``parameter_values.dynamic_id``, which no row has set since + C1 · 50 moved dynamics' values, and this release must go on publishing + afterwards, after a rollback for example. The insert, the comparison of + stored values, the uniqueness check and pruning name no such column. + """ + dialect = postgresql.dialect() + stored_values = next( + stored + for table_name, _staged, stored in publication_reconciliation._comparison_pairs( + normalized_catalog().country("us"), with_format_2=True + ) + if table_name == "parameter values" + ) + for statement in (publication_inserts.INSERT_PARAMETER_VALUES, stored_values): + compiled = str(statement.compile(dialect=dialect)) + assert "parameter_values" in compiled + assert "dynamic_id" not in compiled + + with sqlite_v2_sessions() as sessions, sessions() as session: + model = TaxBenefitModel(name="policyengine-us") + version = TaxBenefitModelVersion( + model=model, version="1.0.0", current_law_id=1, metadata_time_periods=[] + ) + session.add_all([model, version]) + session.flush() + with recorded_statements(session) as statements: + publication_reconciliation.assert_canonical_value_uniqueness(session) + pruned = publication_pruning.prune_catalog_version(session, version.id) + + assert pruned is not None + assert sum("FROM parameter_values" in statement for statement in statements) == 2 + assert not any( + PARAMETER_VALUES_DYNAMIC_ID.search(statement) for statement in statements + ) + + def test_completion_evidence_contains_only_reviewed_non_secret_fields() -> None: evidence = publication.PublicationEvidence( policyengine_version="4.20.3", diff --git a/tests/unit/v2/test_dynamic_table_models.py b/tests/unit/v2/test_dynamic_table_models.py index 544b2f70c..2e068ecf7 100644 --- a/tests/unit/v2/test_dynamic_table_models.py +++ b/tests/unit/v2/test_dynamic_table_models.py @@ -5,8 +5,10 @@ from collections.abc import Iterator from contextlib import contextmanager from datetime import UTC, datetime +from uuid import uuid4 import pytest +from sqlalchemy import insert from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import sessionmaker from sqlmodel import Session @@ -22,6 +24,9 @@ ) from tests.fixtures.database_sessions import sqlite_v2_sessions from tests.fixtures.v2_countries import add_listed_countries +from tests.integration.parameter_values_with_dynamics import ( + ParameterValueWithDynamic, +) from tests.unit.v2.v2_schema_reading import ( declared_index, model_columns, @@ -152,6 +157,11 @@ def test_identical_dynamic_content_is_stored_once() -> None: def test_a_dynamic_sets_one_value_per_parameter_and_start_date() -> None: + """The table keeps the rule while it keeps ``dynamic_id``. + + ``ParameterValue`` no longer maps the column, so the values are written + through the column-only ``ParameterValueWithDynamic``. + """ model, version, parameter = _catalog() with ( @@ -163,17 +173,22 @@ def test_a_dynamic_sets_one_value_per_parameter_and_start_date() -> None: 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, - ) + dynamic_value = { + "parameter_id": parameter.id, + "dynamic_id": dynamic.id, + "start_date": START_DATE, + } + session.execute( + insert(ParameterValueWithDynamic).values( + id=uuid4(), value_json=0.1, **dynamic_value ) + ) with pytest.raises(IntegrityError, match="UNIQUE constraint failed"): - session.commit() + session.execute( + insert(ParameterValueWithDynamic).values( + id=uuid4(), value_json=0.2, **dynamic_value + ) + ) def test_a_mapping_cannot_name_another_country_s_dynamic() -> None: diff --git a/tests/unit/v2/test_metadata_service.py b/tests/unit/v2/test_metadata_service.py index 831936739..1238ed356 100644 --- a/tests/unit/v2/test_metadata_service.py +++ b/tests/unit/v2/test_metadata_service.py @@ -3,6 +3,7 @@ from __future__ import annotations import ast +import re from datetime import UTC, datetime from pathlib import Path from uuid import uuid4 @@ -58,6 +59,9 @@ pytest_plugins = ("tests.fixtures.v2_metadata_service",) +# ``parameter_values.dynamic_id``, but not ``dynamic_parameter_values.dynamic_id``. +PARAMETER_VALUES_DYNAMIC_ID = re.compile(r"\bparameter_values\.dynamic_id\b") + def test_resource_collection_uses_bounded_pagination_without_counting( catalog_session: Session, @@ -169,6 +173,46 @@ def test_parameter_values_are_separate_canonical_resources( assert all(item.parameter_id == parameter.id for item in all_values.items) +def test_current_law_value_reads_name_no_parameter_values_dynamic_id( + catalog_session: Session, +) -> None: + """Current-law values are selected by ``policy_id`` alone. + + C1 · 53 drops ``parameter_values.dynamic_id`` while this release may still + serve; no row has one since C1 · 50 moved dynamics' values. The value + list, a value's detail and the model catalog's parameters (which read + values by parameter name) name no such column. + """ + service = catalog_service(catalog_session) + parameter = service.list_parameters("us").items[0] + + values, list_statements = recorded_statements( + catalog_session, + lambda: service.list_parameter_values( + "us", value_filter=ParameterValueFilter(parameter_id=parameter.id) + ), + ) + value, detail_statements = recorded_statements( + catalog_session, + lambda: service.get_parameter_value("us", values.items[0].id), + ) + catalog_parameters, catalog_statements = recorded_statements( + catalog_session, + lambda: service.get_catalog_parameters("us", names=[parameter.name]), + ) + + assert [item.value for item in values.items] == [0.2, 0.1] + assert value.item == values.items[0] + assert [ + [dated.value for dated in item.values] for item in catalog_parameters.parameters + ] == [[0.1, 0.2]] + statements = [*list_statements, *detail_statements, *catalog_statements] + assert sum("from parameter_values" in statement for statement in statements) == 3 + assert not any( + PARAMETER_VALUES_DYNAMIC_ID.search(statement) for statement in statements + ) + + @pytest.mark.parametrize( ("selected_time", "expected_value"), [ 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..7115cc621 100644 --- a/tests/unit/v2/test_model_persistence.py +++ b/tests/unit/v2/test_model_persistence.py @@ -4,7 +4,7 @@ from contextlib import contextmanager from datetime import UTC, datetime, timedelta from pathlib import Path -from uuid import UUID +from uuid import UUID, uuid4 import pytest import sqlalchemy as sa @@ -30,6 +30,9 @@ from policyengine_api.data.v2.models.base import DIRECT_SQLALCHEMY_EXCEPTIONS from tests.fixtures.database_sessions import sqlite_v2_sessions from tests.fixtures.v2_countries import add_listed_countries +from tests.integration.parameter_values_with_dynamics import ( + ParameterValueWithDynamic, +) @contextmanager @@ -278,16 +281,19 @@ def test_policy_parameter_value_owner_period_and_identity_constraints() -> None: 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() + # ParameterValue no longer maps dynamic_id, which the table keeps + # until C1 · 53 drops it with the check. + with pytest.raises(IntegrityError, match="ck_parameter_values_single_owner"): + session.execute( + sa.insert(ParameterValueWithDynamic).values( + id=uuid4(), + parameter_id=parameter.id, + policy_id=policy.id, + dynamic_id=dynamic.id, + value_json={"rate": 0.1}, + start_date=start, + ) + ) session.rollback() invalid_period = ParameterValue( diff --git a/tests/unit/v2/test_models.py b/tests/unit/v2/test_models.py index 8271ecceb..2233742f2 100644 --- a/tests/unit/v2/test_models.py +++ b/tests/unit/v2/test_models.py @@ -8,7 +8,7 @@ from uuid import uuid4 import sqlalchemy as sa -from sqlalchemy.dialects import postgresql +from sqlalchemy.dialects import postgresql, sqlite from sqlalchemy.orm import configure_mappers from sqlmodel.sql.sqltypes import AutoString @@ -531,6 +531,39 @@ def test_canonical_parameter_values_have_a_postgres_partial_unique_index() -> No assert predicate == "policy_id IS NULL AND dynamic_id IS NULL" +def test_parameter_values_keep_dynamic_id_which_the_model_no_longer_maps() -> None: + """API v1 names no ``parameter_values.dynamic_id``; the table keeps it for now. + + The deploy upgrades the schema before the new release takes traffic, so + the release still serving when C1 · 53 drops the column must not name it, + and a whole-row load names every mapped column. The table keeps the + column, its key to ``dynamics``, the single-owner check and both partial + indexes that name it until that revision. + """ + values = stored_v2_table("parameter_values") + + assert "dynamic_id" not in model_columns(ParameterValue) + assert "dynamic_id" not in sa.inspect(ParameterValue).attrs + assert "dynamic_id" in values.columns + assert [key.columns for key in values.foreign_keys_to("dynamics")] == [ + ("dynamic_id",) + ] + assert "ck_parameter_values_single_owner" in values.constraint_names + assert { + "uq_parameter_values_dynamic_parameter_start_date", + "uq_parameter_values_canonical_parameter_start_date", + } <= set(values.indexes) + + +def test_a_whole_parameter_value_read_names_no_dynamic_id() -> None: + statement = sa.select(ParameterValue) + + for dialect in (postgresql.dialect(), sqlite.dialect()): + compiled = str(statement.compile(dialect=dialect)) + assert "parameter_values.parameter_id" in compiled + assert "dynamic_id" not in compiled + + def test_complete_metadata_compiles_for_postgres_without_mutation() -> None: statements = [ statement diff --git a/tests/unit/v2/test_policy_persistence_statements.py b/tests/unit/v2/test_policy_persistence_statements.py index 6e03a11cf..3e98d2276 100644 --- a/tests/unit/v2/test_policy_persistence_statements.py +++ b/tests/unit/v2/test_policy_persistence_statements.py @@ -2,9 +2,24 @@ from __future__ import annotations +from datetime import UTC, datetime + from sqlalchemy.dialects import postgresql +from sqlmodel import col, select +from policyengine_api.data.v2.models import ( + Parameter, + ParameterValue, + Policy, + TaxBenefitModel, + TaxBenefitModelVersion, +) from policyengine_api.services.v2.policies.database_connectors import creates +from policyengine_api.services.v2.policies.types import ( + PolicyParameterValueInput, + ResolvedPolicyCreationInput, +) +from tests.fixtures.database_sessions import recorded_statements, sqlite_v2_sessions def test_policy_insert_uses_the_content_identity_constraint_and_returning() -> None: @@ -24,3 +39,54 @@ def test_policy_insert_uses_the_content_identity_constraint_and_returning() -> N assert "ON CONFLICT ON CONSTRAINT" in compiled assert "DO NOTHING" in compiled assert "RETURNING policies.id" in compiled + + +def test_a_policy_s_values_are_inserted_without_dynamic_id() -> None: + """The insert names no ``parameter_values.dynamic_id``, which C1 · 53 drops. + + It backs ``POST /v2/policies`` and the dual-write v1-to-v2 policy copy, so + it must go on working in the release serving while that revision runs. + """ + model = TaxBenefitModel(name="policyengine-us") + version = TaxBenefitModelVersion( + model=model, version="1.0.0", current_law_id=1, metadata_time_periods=[] + ) + parameter = Parameter(name="gov.example.rate", tax_benefit_model_version=version) + policy = Policy( + country_id="us", + tax_benefit_model=model, + tax_benefit_model_version=version, + canonicalization_version=1, + content_hash="a" * 64, + ) + with sqlite_v2_sessions() as sessions, sessions() as session: + session.add_all([model, version, parameter, policy]) + session.flush() + policy_input = ResolvedPolicyCreationInput( + country_id="us", + tax_benefit_model_id=model.id, + tax_benefit_model_version_id=version.id, + policyengine_version="1.0.0", + parameter_values=[ + PolicyParameterValueInput( + parameter_id=parameter.id, + value=0.2, + start_date=datetime(2026, 1, 1, tzinfo=UTC), + ) + ], + ) + with recorded_statements(session) as statements: + creates.create_parameter_values( + session, policy_id=policy.id, policy_input=policy_input + ) + stored = session.exec( + select(ParameterValue).where(col(ParameterValue.policy_id) == policy.id) + ).one() + + [value_insert] = [ + statement + for statement in statements + if statement.startswith("INSERT INTO parameter_values") + ] + assert "dynamic_id" not in value_insert + assert (stored.parameter_id, stored.value_json) == (parameter.id, 0.2) From 48d848c9b0849dc2a57275176b193b22a648a56b Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:11:56 +0400 Subject: [PATCH 2/4] =?UTF-8?q?C1=20=C2=B7=2051a:=20stop=20mapping=20param?= =?UTF-8?q?eter=5Fvalues.dynamic=5Fid=20in=20API=20v1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ParameterValue keeps dynamic_id as a SQLModel field with its foreign key, and the single-owner check and both partial indexes stay in __table_args__, so the table and alembic check don't change; there is no revision. __mapper_args__ = {"exclude_properties": ("dynamic_id",)} leaves the column out of the mapper, so a whole-row load selects it no more. No API v1 statement names it any longer: the policy insert (POST /v2/policies and the dual-write v1-to-v2 policy copy), the three current-law reads of the metadata routes, publication's insert, comparison and uniqueness check, and pruning. Since revision 7f7335f0eb31 no row has a dynamic_id, so dropping the filters changes no result. A release of this code keeps serving while C1 · 53's revision drops the column. The privilege manifest's comment on pruning is updated; no grant changes. The Alembic skill's C1 · 50 section and both pruning descriptions say so. Co-Authored-By: Claude Opus 5.5 --- ...meter-values-dynamic-id-unmapped.changed.md | 1 + docs/engineering/skills/alembic-migrations.md | 10 ++++++---- docs/migration/stage-9-v2-metadata.md | 4 ++-- .../data/v2/catalog/publication_inserts.py | 2 -- .../data/v2/catalog/publication_pruning.py | 5 ++--- .../v2/catalog/publication_reconciliation.py | 11 ++++------- policyengine_api/data/v2/models/metadata.py | 18 +++++++++++++----- policyengine_api/data/v2/privileges.py | 4 ++-- .../database_connectors/reads_parameters.py | 18 +++++++----------- .../v2/policies/database_connectors/creates.py | 1 - 10 files changed, 37 insertions(+), 37 deletions(-) create mode 100644 changelog.d/v2-parameter-values-dynamic-id-unmapped.changed.md diff --git a/changelog.d/v2-parameter-values-dynamic-id-unmapped.changed.md b/changelog.d/v2-parameter-values-dynamic-id-unmapped.changed.md new file mode 100644 index 000000000..dc1c90b50 --- /dev/null +++ b/changelog.d/v2-parameter-values-dynamic-id-unmapped.changed.md @@ -0,0 +1 @@ +API v1 no longer reads or writes `parameter_values.dynamic_id`, which no row has set since dynamics' values moved to `dynamic_parameter_values`; the table keeps the column until a later release drops it, and this release keeps serving once it does. diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 4a7c0268a..edf27fc14 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. @@ -1711,7 +1710,10 @@ 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` +map the column; API v1 stops mapping it from C1 · 51a's release (see +"Columns a mapper leaves out"), so the release serving while C1 · 53's +revision runs names none of what it drops. +`tests/integration/test_alembic_v2_dynamic_parameter_tables.py` 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` 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/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/models/metadata.py b/policyengine_api/data/v2/models/metadata.py index ca41b0097..cc517f40a 100644 --- a/policyengine_api/data/v2/models/metadata.py +++ b/policyengine_api/data/v2/models/metadata.py @@ -2,7 +2,7 @@ from datetime import datetime from enum import StrEnum -from typing import TYPE_CHECKING, Any, Literal, Optional +from typing import TYPE_CHECKING, Any, ClassVar, Literal, Optional from uuid import UUID import sqlalchemy as sa @@ -430,13 +430,19 @@ 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 since revision 7f7335f0eb31 moved them, so + no row has a ``dynamic_id``. The column stays a SQLModel field, as rule + ``api.data.orm-only`` requires of every column, and ``exclude_properties`` + leaves it out of the mapper, so API v1 neither loads nor writes it: a value + given to the constructor is never stored, and the class attribute is the + table's column, not a value to read. A release keeps working while C1 · 53 + drops the column, its check and its index, once no simulation service + release maps it either. """ __tablename__ = "parameter_values" + __mapper_args__: ClassVar[dict[str, Any]] = {"exclude_properties": ("dynamic_id",)} __table_args__ = ( sa.CheckConstraint( "policy_id IS NULL OR dynamic_id IS NULL", @@ -500,6 +506,8 @@ class ParameterValue(IdentifiedModel, table=True): foreign_key="policies.id", ondelete="CASCADE", ) + # In the table but left out of the mapper (``exclude_properties``) until a + # revision drops it. dynamic_id: UUID | None = Field( default=None, foreign_key="dynamics.id", 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 549c81dce72a6a7c7557cb3158112bfb225ba3a2 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:35:52 +0400 Subject: [PATCH 3/4] =?UTF-8?q?C1=20=C2=B7=2051a:=20expect=20the=20categor?= =?UTF-8?q?y=20for=20columns=20left=20out=20of=20a=20mapper=20(failing)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review round 1's code-quality finding: ParameterValue uses exclude_properties again, so DIRECT_SQLALCHEMY_EXCEPTIONS, the complete list of direct-SQLAlchemy categories of the v2 models, should list "columns_left_out_of_the_mapper" again, as it did while the report columns were left out of their mappers (C1 · 40a). The test now expects it and fails. Co-Authored-By: Claude Opus 5.5 --- tests/unit/v2/test_model_persistence.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/unit/v2/test_model_persistence.py b/tests/unit/v2/test_model_persistence.py index 7115cc621..569976731 100644 --- a/tests/unit/v2/test_model_persistence.py +++ b/tests/unit/v2/test_model_persistence.py @@ -98,6 +98,7 @@ def test_direct_sqlalchemy_categories_are_complete_and_documented() -> None: "named_constraints_and_indexes", "ambiguous_foreign_key_relationships", "transaction_conflict_recovery", + "columns_left_out_of_the_mapper", } assert all(DIRECT_SQLALCHEMY_EXCEPTIONS.values()) From 5ca9e3d553961b976bfc85699d39454faec51d10 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:36:46 +0400 Subject: [PATCH 4/4] =?UTF-8?q?C1=20=C2=B7=2051a:=20restore=20the=20catego?= =?UTF-8?q?ry=20for=20columns=20left=20out=20of=20a=20mapper=20(review=20r?= =?UTF-8?q?ound=201)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review round 1's code-quality findings: - DIRECT_SQLALCHEMY_EXCEPTIONS lists "columns_left_out_of_the_mapper" again, with C1 · 40a's text, since ParameterValue leaves dynamic_id out of its mapper. - The simulation role privilege tests' module docstring and their UNMAPPED_COLUMN_CLASSES comment said no model leaves a column out; they now say no model of the run tables does. - The Alembic skill's "Columns a mapper leaves out" names parameter_values.dynamic_id as the current case. Co-Authored-By: Claude Opus 5.5 --- docs/engineering/skills/alembic-migrations.md | 5 +++-- policyengine_api/data/v2/models/base.py | 6 ++++++ tests/integration/test_v2_simulation_role_privileges.py | 4 ++-- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index edf27fc14..9bf12388f 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -310,8 +310,9 @@ and `refused(session, ...)`. takes the Python value, such as `[2026]`, not its JSON text. - **Columns a mapper leaves out**: a column kept in its table but left out of the model's mapper (`exclude_properties`) until a revision drops it, as - the per-user and cliff columns of `reports`, `report_runs` and - `budget_window_runs` were until revision `4e30076d4b9f`, has no statement + `parameter_values.dynamic_id` is until C1 · 53's revision, and the per-user + and cliff columns of `reports`, `report_runs` and `budget_window_runs` were + until revision `4e30076d4b9f`, has no statement through the model: `update(Model).values(column=...)` raises `AttributeError`, a constructor value is never stored, and `Model.column` is the table's Core column, which the rule rules out even in a `select`. A diff --git a/policyengine_api/data/v2/models/base.py b/policyengine_api/data/v2/models/base.py index 82e171a54..3ea81a366 100644 --- a/policyengine_api/data/v2/models/base.py +++ b/policyengine_api/data/v2/models/base.py @@ -39,6 +39,12 @@ "Concurrent report idempotency requires a savepoint and bounded " "IntegrityError recovery around the database uniqueness constraint." ), + "columns_left_out_of_the_mapper": ( + "A column API v1 no longer uses stays a SQLModel field of its " + "table, left out of the mapper by exclude_properties, until other " + "writers have stopped and a later revision drops it; API v1 neither " + "loads nor writes it meanwhile." + ), } ) diff --git a/tests/integration/test_v2_simulation_role_privileges.py b/tests/integration/test_v2_simulation_role_privileges.py index 7f591fa4a..926f7e2e0 100644 --- a/tests/integration/test_v2_simulation_role_privileges.py +++ b/tests/integration/test_v2_simulation_role_privileges.py @@ -20,7 +20,7 @@ have no ``updated_at``. A column a model's mapper leaves out (``exclude_properties``) would have no statement through the model, so its writes and refusals would go through a class that maps it; since revision -``4e30076d4b9f`` no model leaves a column out. +``4e30076d4b9f`` no model of these tables leaves a column out. """ from __future__ import annotations @@ -612,7 +612,7 @@ def test_the_public_api_reads_runs_and_results_but_writes_neither( # The class that maps the columns each model's mapper leaves out. Since -# revision 4e30076d4b9f no model leaves a column out. +# revision 4e30076d4b9f no model of the run tables leaves a column out. UNMAPPED_COLUMN_CLASSES: dict[type[Any], type[Any]] = {}