From f3f69549e7d8351c5c0b49962eab0a104f72eeae Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:25:29 +0400 Subject: [PATCH 1/9] =?UTF-8?q?C1=20=C2=B7=2048:=20tests=20for=20UK=20gov.?= =?UTF-8?q?dynamic=20and=20splitting=20stored=20policy=20copies=20(failing?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Failing tests for tracker task C1 · 48 (API v1): - UK gov.dynamic. joins the model-assumption prefixes: /v2/policies refuses it, /v2/dynamics accepts it, and the v1-to-v2 copy puts it in the dynamic. - A command splits every stored policy that sets a model assumption into a policy and a dynamic on its own catalog version, re-points its legacy mappings and saved policies, gives each saved policy a saved dynamic with its name, and deletes the old copy once nothing names it. A copy that a simulation, report or household calculation names is split and re-pointed but kept; a mapping that already names a dynamic gets one merged dynamic. - The command runs as a temporary role holding only the grants it declares, and only lists what it would change unless given --apply. Co-Authored-By: Claude Opus 5.5 --- .../integration/test_v2_policy_copy_splits.py | 768 ++++++++++++++++++ tests/unit/test_dynamic_parameters.py | 32 +- .../test_split_v2_policy_copies_script.py | 311 +++++++ tests/unit/v2/test_dynamic_catalog.py | 106 ++- tests/unit/v2/test_policy_copy_split_rules.py | 314 +++++++ .../unit/v2/test_policy_copy_split_runbook.py | 75 ++ tests/unit/v2/test_policy_legacy_copy.py | 39 + tests/unit/v2/test_privilege_manifest.py | 83 ++ tests/unit/v2/test_settings.py | 27 + 9 files changed, 1752 insertions(+), 3 deletions(-) create mode 100644 tests/integration/test_v2_policy_copy_splits.py create mode 100644 tests/unit/test_split_v2_policy_copies_script.py create mode 100644 tests/unit/v2/test_policy_copy_split_rules.py create mode 100644 tests/unit/v2/test_policy_copy_split_runbook.py diff --git a/tests/integration/test_v2_policy_copy_splits.py b/tests/integration/test_v2_policy_copy_splits.py new file mode 100644 index 000000000..c369d6782 --- /dev/null +++ b/tests/integration/test_v2_policy_copy_splits.py @@ -0,0 +1,768 @@ +"""PostgreSQL tests for C1 · 48's split of stored policies holding model assumptions. + +The command runs as the temporary role C1 · 49 creates, holding exactly +``POLICY_COPY_SPLIT_PRIVILEGES``, so a statement those grants don't allow +fails here. Rows are written and removed as the disposable database's +superuser. Each test's catalog has a model of its own, and assertions look +only at the rows the test wrote, since the command reads every stored policy. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import UTC, datetime +from typing import TYPE_CHECKING +from uuid import UUID, uuid4 + +import pytest +from policyengine_api.services.v2.policy_copy_splits.database_session import ( + PolicyCopySplitDatabaseSession, +) +from policyengine_api.services.v2.policy_copy_splits.services import ( + V2PolicyCopySplitService, + read_policy_copy_ids, + split_policy_copy_in_session, +) +from policyengine_api.services.v2.policy_copy_splits.types import ( + PolicyCopyOutcome, + PolicyCopyRefusalReason, + PolicyCopySplit, +) +from sqlalchemy import create_engine, delete, or_ +from sqlalchemy.orm import sessionmaker +from sqlalchemy.pool import NullPool +from sqlmodel import Session, col, select + +from policyengine_api.data.v2.models import ( + Dynamic, + LegacyPolicyMapping, + Parameter, + ParameterValue, + Policy, + Report, + TaxBenefitModel, + TaxBenefitModelVersion, + User, + UserDynamic, + UserPolicy, +) +from policyengine_api.data.v2.privilege_reconciliation import ( + apply_declared_privileges, + create_missing_roles, +) +from policyengine_api.data.v2.privileges import ( + POLICY_COPY_SPLIT_PRIVILEGES, + POLICY_COPY_SPLIT_ROLE, +) +from policyengine_api.services.v2.dynamics.services import create_resolved_dynamic +from policyengine_api.services.v2.dynamics.types import ResolvedDynamicCreationInput +from policyengine_api.services.v2.policies.services import create_resolved_policy +from policyengine_api.services.v2.policies.types import ResolvedPolicyCreationInput + +if TYPE_CHECKING: + from collections.abc import Iterator + + from sqlalchemy import Engine + +CATALOG_VERSION = "6.17.1" +US_TAX_RATE = "gov.irs.income.rate" +US_INCOME_ELASTICITY = "gov.simulation.labor_supply_responses.elasticities.income" +US_MTR_DELTA = "simulation.marginal_tax_rate_delta" +UK_TAX_RATE = "gov.hmrc.income_tax.rates.uk[0].rate" +UK_INCOME_ELASTICITY = "gov.simulation.labour_supply_responses.income_elasticity" +UK_OBR_SWITCH = "gov.dynamic.obr_labour_supply_assumptions" +START_2026 = datetime(2026, 1, 1, tzinfo=UTC) +END_2026 = datetime(2026, 12, 31, tzinfo=UTC) + + +@pytest.fixture(scope="module") +def owner_engine(disposable_v2_database_url: str) -> Iterator[Engine]: + engine = create_engine(disposable_v2_database_url, poolclass=NullPool) + try: + yield engine + finally: + engine.dispose() + + +@pytest.fixture(scope="module") +def split_role_engine(owner_engine: Engine, v2_engine_as_role) -> Iterator[Engine]: + """Yield an engine acting as the temporary role, with only its declared grants.""" + with owner_engine.begin() as connection: + create_missing_roles(connection, [POLICY_COPY_SPLIT_ROLE]) + plan, _default_privileges = apply_declared_privileges( + connection, {POLICY_COPY_SPLIT_ROLE: POLICY_COPY_SPLIT_PRIVILEGES} + ) + assert plan.can_apply + engine = v2_engine_as_role(POLICY_COPY_SPLIT_ROLE, poolclass=NullPool) + try: + yield engine + finally: + engine.dispose() + + +def _service(engine: Engine, *, read_only: bool = False) -> V2PolicyCopySplitService: + bind = engine.execution_options(postgresql_readonly=True) if read_only else engine + return V2PolicyCopySplitService( + PolicyCopySplitDatabaseSession( + sessionmaker(bind=bind, class_=Session, expire_on_commit=False) + ) + ) + + +@dataclass +class Scenario: + """One test's model, catalog version and parameters, and what it stored.""" + + country_id: str + model_id: UUID + version_id: UUID + parameter_ids: dict[str, UUID] + user_ids: list[UUID] = field(default_factory=list) + legacy_policy_ids: list[int] = field(default_factory=list) + + def parameter_value( + self, name: str, *, value: object, end_date: datetime | None = END_2026 + ) -> dict[str, object]: + return { + "parameter_id": self.parameter_ids[name], + "value": value, + "start_date": START_2026, + "end_date": end_date, + } + + def content(self, *values: dict[str, object]) -> dict[str, object]: + return { + "country_id": self.country_id, + "tax_benefit_model_id": self.model_id, + "tax_benefit_model_version_id": self.version_id, + "policyengine_version": CATALOG_VERSION, + "parameter_values": list(values), + } + + +def _store_catalog(owner_engine: Engine, country_id: str, names: list[str]) -> Scenario: + with Session(owner_engine) as session: + model = TaxBenefitModel(name=f"policyengine-{country_id}-split-{uuid4().hex}") + version = TaxBenefitModelVersion( + model=model, + version=CATALOG_VERSION, + current_law_id=1, + metadata_time_periods=[2026], + ) + parameters = [ + Parameter(name=name, tax_benefit_model_version=version) for name in names + ] + session.add_all(parameters) + session.commit() + return Scenario( + country_id=country_id, + model_id=model.id, + version_id=version.id, + parameter_ids={parameter.name: parameter.id for parameter in parameters}, + ) + + +def _remove(owner_engine: Engine, scenario: Scenario) -> None: + policy_ids = select(Policy.id).where( + Policy.tax_benefit_model_id == scenario.model_id + ) + dynamic_ids = select(Dynamic.id).where( + Dynamic.tax_benefit_model_id == scenario.model_id + ) + with Session(owner_engine) as session: + session.execute( + delete(UserDynamic).where(col(UserDynamic.dynamic_id).in_(dynamic_ids)) + ) + session.execute( + delete(UserPolicy).where(col(UserPolicy.policy_id).in_(policy_ids)) + ) + session.execute(delete(User).where(col(User.id).in_(scenario.user_ids))) + session.execute( + delete(LegacyPolicyMapping).where( + or_( + col(LegacyPolicyMapping.policy_id).in_(policy_ids), + col(LegacyPolicyMapping.dynamic_id).in_(dynamic_ids), + ) + ) + ) + session.execute( + delete(Report).where(Report.tax_benefit_model_id == scenario.model_id) + ) + session.execute( + delete(Policy).where(Policy.tax_benefit_model_id == scenario.model_id) + ) + session.execute( + delete(Dynamic).where(Dynamic.tax_benefit_model_id == scenario.model_id) + ) + session.execute( + delete(ParameterValue).where( + col(ParameterValue.parameter_id).in_(scenario.parameter_ids.values()) + ) + ) + session.execute( + delete(Parameter).where( + Parameter.tax_benefit_model_version_id == scenario.version_id + ) + ) + session.execute( + delete(TaxBenefitModelVersion).where( + TaxBenefitModelVersion.id == scenario.version_id + ) + ) + session.execute( + delete(TaxBenefitModel).where(TaxBenefitModel.id == scenario.model_id) + ) + session.commit() + + +@pytest.fixture +def us_scenario(owner_engine: Engine) -> Iterator[Scenario]: + scenario = _store_catalog( + owner_engine, "us", [US_TAX_RATE, US_INCOME_ELASTICITY, US_MTR_DELTA] + ) + try: + yield scenario + finally: + _remove(owner_engine, scenario) + + +@pytest.fixture +def uk_scenario(owner_engine: Engine) -> Iterator[Scenario]: + scenario = _store_catalog( + owner_engine, "uk", [UK_TAX_RATE, UK_INCOME_ELASTICITY, UK_OBR_SWITCH] + ) + try: + yield scenario + finally: + _remove(owner_engine, scenario) + + +def _store_policy( + owner_engine: Engine, scenario: Scenario, *values: dict[str, object] +) -> UUID: + """Store a policy as the v1-to-v2 copy did before C1 · 36: no split.""" + with Session(owner_engine) as session: + result = create_resolved_policy( + session, + ResolvedPolicyCreationInput.model_validate(scenario.content(*values)), + ) + session.commit() + return result.policy_id + + +def _store_dynamic( + owner_engine: Engine, scenario: Scenario, *values: dict[str, object] +) -> UUID: + with Session(owner_engine) as session: + result = create_resolved_dynamic( + session, + ResolvedDynamicCreationInput.model_validate(scenario.content(*values)), + ) + session.commit() + return result.dynamic_id + + +def _store_mapping( + owner_engine: Engine, + scenario: Scenario, + *, + policy_id: UUID, + dynamic_id: UUID | None = None, +) -> int: + legacy_policy_id = 900_000_000 + uuid4().int % 100_000_000 + with Session(owner_engine) as session: + session.add( + LegacyPolicyMapping( + country_id=scenario.country_id, + legacy_policy_id=legacy_policy_id, + policy_id=policy_id, + dynamic_id=dynamic_id, + source_policy_hash=f"legacy-hash-{legacy_policy_id}", + ) + ) + session.commit() + scenario.legacy_policy_ids.append(legacy_policy_id) + return legacy_policy_id + + +def _store_user(owner_engine: Engine, scenario: Scenario) -> UUID: + with Session(owner_engine) as session: + user = User(user_type="unauthenticated") + session.add(user) + session.commit() + scenario.user_ids.append(user.id) + return user.id + + +def _store_saved_policy( + owner_engine: Engine, scenario: Scenario, **saved_policy_fields: object +) -> UUID: + """Store a saved policy with the given user, policy, name and other fields.""" + with Session(owner_engine) as session: + saved_policy = UserPolicy(country_id=scenario.country_id, **saved_policy_fields) + session.add(saved_policy) + session.commit() + return saved_policy.id + + +def _values(owner_engine: Engine, *, policy_id=None, dynamic_id=None) -> set: + """Each value a policy or dynamic sets: its parameter, value and end date.""" + with Session(owner_engine) as session: + owner_column = ( + ParameterValue.policy_id + if dynamic_id is None + else ParameterValue.dynamic_id + ) + rows = session.exec( + select(ParameterValue).where(owner_column == (policy_id or dynamic_id)) + ).all() + return {(row.parameter_id, row.value_json, row.end_date) for row in rows} + + +def _mapping(owner_engine: Engine, scenario: Scenario, legacy_policy_id: int): + with Session(owner_engine) as session: + return session.exec( + select(LegacyPolicyMapping).where( + LegacyPolicyMapping.country_id == scenario.country_id, + LegacyPolicyMapping.legacy_policy_id == legacy_policy_id, + ) + ).one() + + +def _saved_policy_target(owner_engine: Engine, saved_policy_id: UUID) -> UUID: + with Session(owner_engine) as session: + return session.get(UserPolicy, saved_policy_id).policy_id + + +def _saved_dynamics(owner_engine: Engine, user_id: UUID) -> list[UserDynamic]: + with Session(owner_engine) as session: + return list( + session.exec( + select(UserDynamic) + .where(UserDynamic.user_id == user_id) + .order_by(col(UserDynamic.created_at), col(UserDynamic.id)) + ).all() + ) + + +def _policy_exists(owner_engine: Engine, policy_id: UUID) -> bool: + with Session(owner_engine) as session: + return session.get(Policy, policy_id) is not None + + +def _result_for(splits, policy_id: UUID) -> PolicyCopySplit: + [split] = [split for split in splits if split.old_policy_id == policy_id] + return split + + +def test_a_us_copy_is_split_re_pointed_given_a_saved_dynamic_and_deleted( + owner_engine: Engine, split_role_engine: Engine, us_scenario: Scenario +) -> None: + scenario = us_scenario + old_copy_id = _store_policy( + owner_engine, + scenario, + scenario.parameter_value(US_TAX_RATE, value=0.3), + scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), + scenario.parameter_value(US_MTR_DELTA, value=0.01, end_date=None), + ) + legacy_policy_id = _store_mapping(owner_engine, scenario, policy_id=old_copy_id) + user_id = _store_user(owner_engine, scenario) + saved_policy_id = _store_saved_policy( + owner_engine, + scenario, + user_id=user_id, + policy_id=old_copy_id, + name="My reform", + legacy_policy_id=legacy_policy_id, + description="Raises the rate, with labour supply responses", + ) + + split = _result_for( + list(_service(split_role_engine).split_policy_copies()), old_copy_id + ) + + assert split.applied + assert split.outcome is PolicyCopyOutcome.DELETED + assert split.country_id == "us" + assert split.policyengine_version == CATALOG_VERSION + assert split.policy is not None + assert split.policy.created + assert split.dynamic is not None + assert split.dynamic.created + new_policy_id, new_dynamic_id = split.policy.id, split.dynamic.id + assert not _policy_exists(owner_engine, old_copy_id) + assert _values(owner_engine, policy_id=old_copy_id) == set() + assert _values(owner_engine, policy_id=new_policy_id) == { + (scenario.parameter_ids[US_TAX_RATE], 0.3, END_2026) + } + assert _values(owner_engine, dynamic_id=new_dynamic_id) == { + (scenario.parameter_ids[US_INCOME_ELASTICITY], 0.25, END_2026), + (scenario.parameter_ids[US_MTR_DELTA], 0.01, None), + } + mapping = _mapping(owner_engine, scenario, legacy_policy_id) + assert (mapping.policy_id, mapping.dynamic_id) == (new_policy_id, new_dynamic_id) + [repointed_mapping] = split.mappings + assert repointed_mapping.legacy_policy_id == legacy_policy_id + assert repointed_mapping.previous_dynamic_id is None + assert repointed_mapping.dynamic.id == new_dynamic_id + assert _saved_policy_target(owner_engine, saved_policy_id) == new_policy_id + [saved_dynamic] = _saved_dynamics(owner_engine, user_id) + assert (saved_dynamic.dynamic_id, saved_dynamic.country_id) == ( + new_dynamic_id, + "us", + ) + assert (saved_dynamic.name, saved_dynamic.description) == ("My reform", None) + [repointed_saved_policy] = split.saved_policies + assert repointed_saved_policy.user_policy_id == saved_policy_id + assert repointed_saved_policy.saved_dynamic_id == saved_dynamic.id + assert repointed_saved_policy.saved_dynamic_created + with Session(split_role_engine) as session: + assert old_copy_id not in read_policy_copy_ids(session) + + second_run = list(_service(split_role_engine).split_policy_copies()) + + assert old_copy_id not in {split.old_policy_id for split in second_run} + mapping_after = _mapping(owner_engine, scenario, legacy_policy_id) + assert (mapping_after.policy_id, mapping_after.dynamic_id) == ( + new_policy_id, + new_dynamic_id, + ) + assert _saved_policy_target(owner_engine, saved_policy_id) == new_policy_id + assert [row.id for row in _saved_dynamics(owner_engine, user_id)] == [ + saved_dynamic.id + ] + + +def test_a_uk_copy_of_only_model_assumptions_points_at_an_empty_policy( + owner_engine: Engine, split_role_engine: Engine, uk_scenario: Scenario +) -> None: + scenario = uk_scenario + old_copy_id = _store_policy( + owner_engine, scenario, scenario.parameter_value(UK_OBR_SWITCH, value=False) + ) + legacy_policy_id = _store_mapping(owner_engine, scenario, policy_id=old_copy_id) + + split = _result_for( + list(_service(split_role_engine).split_policy_copies()), old_copy_id + ) + + assert split.outcome is PolicyCopyOutcome.DELETED + mapping = _mapping(owner_engine, scenario, legacy_policy_id) + assert mapping.policy_id == split.policy.id + assert _values(owner_engine, policy_id=mapping.policy_id) == set() + with Session(owner_engine) as session: + empty_policy = session.get(Policy, mapping.policy_id) + assert empty_policy.tax_benefit_model_version_id == scenario.version_id + assert _values(owner_engine, dynamic_id=mapping.dynamic_id) == { + (scenario.parameter_ids[UK_OBR_SWITCH], False, END_2026) + } + assert not _policy_exists(owner_engine, old_copy_id) + + +def test_a_mapping_that_already_names_a_dynamic_gets_one_merged_dynamic( + owner_engine: Engine, split_role_engine: Engine, uk_scenario: Scenario +) -> None: + scenario = uk_scenario + old_copy_id = _store_policy( + owner_engine, + scenario, + scenario.parameter_value(UK_TAX_RATE, value=0.21), + scenario.parameter_value(UK_OBR_SWITCH, value=False), + ) + earlier_dynamic_id = _store_dynamic( + owner_engine, + scenario, + scenario.parameter_value(UK_INCOME_ELASTICITY, value=0.1), + ) + legacy_policy_id = _store_mapping( + owner_engine, scenario, policy_id=old_copy_id, dynamic_id=earlier_dynamic_id + ) + user_id = _store_user(owner_engine, scenario) + mapped_saved_policy_id = _store_saved_policy( + owner_engine, + scenario, + user_id=user_id, + policy_id=old_copy_id, + name="Copied from v1", + legacy_policy_id=legacy_policy_id, + ) + native_saved_policy_id = _store_saved_policy( + owner_engine, scenario, user_id=user_id, policy_id=old_copy_id, name="Native" + ) + + split = _result_for( + list(_service(split_role_engine).split_policy_copies()), old_copy_id + ) + + assert split.outcome is PolicyCopyOutcome.DELETED + mapping = _mapping(owner_engine, scenario, legacy_policy_id) + assert mapping.policy_id == split.policy.id + assert _values(owner_engine, policy_id=mapping.policy_id) == { + (scenario.parameter_ids[UK_TAX_RATE], 0.21, END_2026) + } + merged_dynamic_id = mapping.dynamic_id + assert merged_dynamic_id not in {earlier_dynamic_id, split.dynamic.id} + assert _values(owner_engine, dynamic_id=merged_dynamic_id) == { + (scenario.parameter_ids[UK_INCOME_ELASTICITY], 0.1, END_2026), + (scenario.parameter_ids[UK_OBR_SWITCH], False, END_2026), + } + assert _values(owner_engine, dynamic_id=split.dynamic.id) == { + (scenario.parameter_ids[UK_OBR_SWITCH], False, END_2026) + } + [repointed_mapping] = split.mappings + assert repointed_mapping.previous_dynamic_id == earlier_dynamic_id + assert repointed_mapping.dynamic.id == merged_dynamic_id + saved_dynamics = { + row.name: row.dynamic_id for row in _saved_dynamics(owner_engine, user_id) + } + assert saved_dynamics == { + "Copied from v1": merged_dynamic_id, + "Native": split.dynamic.id, + } + for saved_policy_id in (mapped_saved_policy_id, native_saved_policy_id): + assert _saved_policy_target(owner_engine, saved_policy_id) == mapping.policy_id + with Session(owner_engine) as session: + assert session.get(Dynamic, earlier_dynamic_id) is not None + + +def test_a_copy_a_report_names_is_split_and_re_pointed_but_kept( + owner_engine: Engine, split_role_engine: Engine, us_scenario: Scenario +) -> None: + scenario = us_scenario + old_copy_id = _store_policy( + owner_engine, + scenario, + scenario.parameter_value(US_TAX_RATE, value=0.3), + scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), + ) + legacy_policy_id = _store_mapping(owner_engine, scenario, policy_id=old_copy_id) + user_id = _store_user(owner_engine, scenario) + saved_policy_id = _store_saved_policy( + owner_engine, scenario, user_id=user_id, policy_id=old_copy_id, name="Kept" + ) + with Session(owner_engine) as session: + report = Report( + country="us", + tax_benefit_model_id=scenario.model_id, + policy_id=old_copy_id, + ) + session.add(report) + session.commit() + report_id = report.id + + split = _result_for( + list(_service(split_role_engine).split_policy_copies()), old_copy_id + ) + + assert split.outcome is PolicyCopyOutcome.KEPT + assert ( + split.references.simulations, + split.references.reports, + split.references.household_jobs, + ) == (0, 1, 0) + assert _policy_exists(owner_engine, old_copy_id) + assert len(_values(owner_engine, policy_id=old_copy_id)) == 2 + with Session(owner_engine) as session: + assert session.get(Report, report_id).policy_id == old_copy_id + mapping = _mapping(owner_engine, scenario, legacy_policy_id) + assert (mapping.policy_id, mapping.dynamic_id) == ( + split.policy.id, + split.dynamic.id, + ) + assert _saved_policy_target(owner_engine, saved_policy_id) == split.policy.id + [saved_dynamic] = _saved_dynamics(owner_engine, user_id) + with Session(split_role_engine) as session: + assert old_copy_id in read_policy_copy_ids(session) + + second_split = _result_for( + list(_service(split_role_engine).split_policy_copies()), old_copy_id + ) + + assert second_split.outcome is PolicyCopyOutcome.KEPT + assert second_split.mappings == () + assert second_split.saved_policies == () + assert [row.id for row in _saved_dynamics(owner_engine, user_id)] == [ + saved_dynamic.id + ] + with Session(owner_engine) as session: + session.execute(delete(Report).where(Report.id == report_id)) + session.commit() + + +def test_a_conflicting_merge_refuses_the_copy_and_changes_nothing( + owner_engine: Engine, split_role_engine: Engine, uk_scenario: Scenario +) -> None: + scenario = uk_scenario + old_copy_id = _store_policy( + owner_engine, + scenario, + scenario.parameter_value(UK_TAX_RATE, value=0.21), + scenario.parameter_value(UK_INCOME_ELASTICITY, value=0.2), + ) + earlier_dynamic_id = _store_dynamic( + owner_engine, + scenario, + scenario.parameter_value(UK_INCOME_ELASTICITY, value=0.1), + ) + legacy_policy_id = _store_mapping( + owner_engine, scenario, policy_id=old_copy_id, dynamic_id=earlier_dynamic_id + ) + user_id = _store_user(owner_engine, scenario) + saved_policy_id = _store_saved_policy( + owner_engine, + scenario, + user_id=user_id, + policy_id=old_copy_id, + name="Conflicting", + legacy_policy_id=legacy_policy_id, + ) + + split = _result_for( + list(_service(split_role_engine).split_policy_copies()), old_copy_id + ) + + assert split.outcome is PolicyCopyOutcome.REFUSED + assert split.refusal_reason is PolicyCopyRefusalReason.CONFLICTING_DYNAMIC_VALUES + assert _policy_exists(owner_engine, old_copy_id) + mapping = _mapping(owner_engine, scenario, legacy_policy_id) + assert (mapping.policy_id, mapping.dynamic_id) == (old_copy_id, earlier_dynamic_id) + assert _saved_policy_target(owner_engine, saved_policy_id) == old_copy_id + assert _saved_dynamics(owner_engine, user_id) == [] + with Session(owner_engine) as session: + stored = session.exec( + select(Policy.id).where(Policy.tax_benefit_model_id == scenario.model_id) + ).all() + assert list(stored) == [old_copy_id] + dynamics = session.exec( + select(Dynamic.id).where(Dynamic.tax_benefit_model_id == scenario.model_id) + ).all() + assert list(dynamics) == [earlier_dynamic_id] + + +def test_the_listing_reads_only_and_reports_what_would_change( + owner_engine: Engine, split_role_engine: Engine, us_scenario: Scenario +) -> None: + scenario = us_scenario + stored_policy_part_id = _store_policy( + owner_engine, scenario, scenario.parameter_value(US_TAX_RATE, value=0.3) + ) + old_copy_id = _store_policy( + owner_engine, + scenario, + scenario.parameter_value(US_TAX_RATE, value=0.3), + scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), + ) + legacy_policy_id = _store_mapping(owner_engine, scenario, policy_id=old_copy_id) + user_id = _store_user(owner_engine, scenario) + saved_policy_id = _store_saved_policy( + owner_engine, scenario, user_id=user_id, policy_id=old_copy_id, name="Listed" + ) + + split = _result_for( + _service(split_role_engine, read_only=True).list_policy_copy_splits(), + old_copy_id, + ) + + assert not split.applied + assert split.outcome is PolicyCopyOutcome.DELETED + assert (split.policy.id, split.policy.created) == (stored_policy_part_id, False) + assert (split.dynamic.id, split.dynamic.created) == (None, True) + [listed_mapping] = split.mappings + assert listed_mapping.legacy_policy_id == legacy_policy_id + assert listed_mapping.dynamic.content_hash == split.dynamic.content_hash + [listed_saved_policy] = split.saved_policies + assert listed_saved_policy.user_policy_id == saved_policy_id + assert listed_saved_policy.saved_dynamic_id is None + assert listed_saved_policy.saved_dynamic_created + assert _policy_exists(owner_engine, old_copy_id) + mapping = _mapping(owner_engine, scenario, legacy_policy_id) + assert (mapping.policy_id, mapping.dynamic_id) == (old_copy_id, None) + assert _saved_policy_target(owner_engine, saved_policy_id) == old_copy_id + assert _saved_dynamics(owner_engine, user_id) == [] + with Session(owner_engine) as session: + dynamics = session.exec( + select(Dynamic.id).where(Dynamic.tax_benefit_model_id == scenario.model_id) + ).all() + assert dynamics == [] + + +def test_an_identical_saved_dynamic_is_reused_and_another_name_gets_its_own( + owner_engine: Engine, split_role_engine: Engine, us_scenario: Scenario +) -> None: + scenario = us_scenario + old_copy_id = _store_policy( + owner_engine, + scenario, + scenario.parameter_value(US_TAX_RATE, value=0.3), + scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), + ) + user_id = _store_user(owner_engine, scenario) + first_id, second_id, other_id, unnamed_id, also_unnamed_id = ( + _store_saved_policy( + owner_engine, scenario, user_id=user_id, policy_id=old_copy_id, name=name + ) + for name in ("Reform A", "Reform A", "Reform B", None, None) + ) + + split = _result_for( + list(_service(split_role_engine).split_policy_copies()), old_copy_id + ) + + by_saved_policy = { + repointed.user_policy_id: repointed for repointed in split.saved_policies + } + assert by_saved_policy[first_id].saved_dynamic_created + assert not by_saved_policy[second_id].saved_dynamic_created + assert ( + by_saved_policy[second_id].saved_dynamic_id + == by_saved_policy[first_id].saved_dynamic_id + ) + assert by_saved_policy[other_id].saved_dynamic_created + assert by_saved_policy[unnamed_id].saved_dynamic_created + assert not by_saved_policy[also_unnamed_id].saved_dynamic_created + assert sorted( + (row.name or "") for row in _saved_dynamics(owner_engine, user_id) + ) == ["", "Reform A", "Reform B"] + + +def test_policies_setting_no_model_assumption_are_left_alone( + owner_engine: Engine, split_role_engine: Engine, us_scenario: Scenario +) -> None: + scenario = us_scenario + policy_id = _store_policy( + owner_engine, scenario, scenario.parameter_value(US_TAX_RATE, value=0.3) + ) + legacy_policy_id = _store_mapping(owner_engine, scenario, policy_id=policy_id) + + splits = list(_service(split_role_engine).split_policy_copies()) + + assert policy_id not in {split.old_policy_id for split in splits} + assert _policy_exists(owner_engine, policy_id) + assert _mapping(owner_engine, scenario, legacy_policy_id).dynamic_id is None + + +def test_one_copy_splits_in_a_caller_owned_transaction( + owner_engine: Engine, split_role_engine: Engine, uk_scenario: Scenario +) -> None: + """D4 · 1's migration reuses the split in a transaction of its own.""" + scenario = uk_scenario + old_copy_id = _store_policy( + owner_engine, + scenario, + scenario.parameter_value(UK_TAX_RATE, value=0.21), + scenario.parameter_value(UK_OBR_SWITCH, value=False), + ) + legacy_policy_id = _store_mapping(owner_engine, scenario, policy_id=old_copy_id) + + with Session(split_role_engine) as session: + split = split_policy_copy_in_session(session, old_copy_id) + session.rollback() + + assert split is not None + assert split.outcome is PolicyCopyOutcome.DELETED + assert _policy_exists(owner_engine, old_copy_id) + assert _mapping(owner_engine, scenario, legacy_policy_id).policy_id == old_copy_id + + with Session(split_role_engine) as session: + assert split_policy_copy_in_session(session, uuid4()) is None diff --git a/tests/unit/test_dynamic_parameters.py b/tests/unit/test_dynamic_parameters.py index 5e3935cdf..42293f61a 100644 --- a/tests/unit/test_dynamic_parameters.py +++ b/tests/unit/test_dynamic_parameters.py @@ -16,12 +16,13 @@ UK_OLD_INCOME_ELASTICITY = "gov.simulation.labor_supply_responses.income_elasticity" UK_INCOME_ELASTICITY = "gov.simulation.labour_supply_responses.income_elasticity" US_INCOME_ELASTICITY = "gov.simulation.labor_supply_responses.elasticities.income" +UK_OBR_LABOUR_SUPPLY_SWITCH = "gov.dynamic.obr_labour_supply_assumptions" def test_every_supported_country_lists_its_prefixes() -> None: assert set(DYNAMIC_PARAMETER_PREFIXES) == set(get_args(SupportedCountryId)) assert DYNAMIC_PARAMETER_PREFIXES["us"] == ("gov.simulation.", "simulation.") - assert DYNAMIC_PARAMETER_PREFIXES["uk"] == ("gov.simulation.",) + assert DYNAMIC_PARAMETER_PREFIXES["uk"] == ("gov.simulation.", "gov.dynamic.") @pytest.mark.parametrize( @@ -32,6 +33,7 @@ def test_every_supported_country_lists_its_prefixes() -> None: ("us", "simulation.marginal_tax_rate_delta"), ("uk", UK_INCOME_ELASTICITY), ("uk", "gov.simulation.marginal_tax_rate_delta"), + ("uk", UK_OBR_LABOUR_SUPPLY_SWITCH), ], ) def test_parameters_under_the_country_s_prefixes_are_dynamic( @@ -50,6 +52,9 @@ def test_parameters_under_the_country_s_prefixes_are_dynamic( # The UK has no top-level simulation tree. ("uk", "simulation.marginal_tax_rate_delta"), ("uk", "gov.hmrc.income_tax.allowances.personal_allowance.amount"), + ("uk", "gov.dynamics_count"), + # Only the UK keeps model assumptions under gov.dynamic. + ("us", "gov.dynamic.obr_labour_supply_assumptions"), ], ) def test_other_parameters_are_not_dynamic( @@ -145,3 +150,28 @@ def test_a_policy_with_no_dynamic_values_is_left_whole() -> None: assert split.policy_values == policy_json assert split.dynamic_values == {} assert split_legacy_policy_json("us", {}) == split_legacy_policy_json("uk", {}) + + +def test_a_uk_policy_s_gov_dynamic_values_go_into_its_dynamic() -> None: + split = split_legacy_policy_json( + "uk", + { + "gov.hmrc.income_tax.rates.uk[0].rate": {"2026": 0.21}, + UK_OBR_LABOUR_SUPPLY_SWITCH: {"2026": False}, + UK_INCOME_ELASTICITY: {"2026": 0.1}, + }, + ) + + assert split.policy_values == { + "gov.hmrc.income_tax.rates.uk[0].rate": {"2026": 0.21} + } + assert split.dynamic_values == { + UK_OBR_LABOUR_SUPPLY_SWITCH: {"2026": False}, + UK_INCOME_ELASTICITY: {"2026": 0.1}, + } + + +def test_gov_dynamic_has_one_spelling_and_is_never_rewritten() -> None: + assert canonical_parameter_name("uk", UK_OBR_LABOUR_SUPPLY_SWITCH) == ( + UK_OBR_LABOUR_SUPPLY_SWITCH + ) diff --git a/tests/unit/test_split_v2_policy_copies_script.py b/tests/unit/test_split_v2_policy_copies_script.py new file mode 100644 index 000000000..25bcfd34c --- /dev/null +++ b/tests/unit/test_split_v2_policy_copies_script.py @@ -0,0 +1,311 @@ +"""Tests for the command that splits stored policy copies holding model assumptions. + +The command only reads unless given ``--apply``. Each copy's report names the +old copy, its policy and dynamic, every legacy mapping and saved policy it +re-points and every saved dynamic it adds, so C1 · 49's operator can compare +the run with a backup. +""" + +from __future__ import annotations + +import subprocess +import sys +from contextlib import contextmanager +from typing import TYPE_CHECKING +from uuid import UUID + +import pytest +from policyengine_api.services.v2.policy_copy_splits.types import ( + CopyReferences, + PolicyCopyOutcome, + PolicyCopyRefusalReason, + PolicyCopySplit, + RepointedMapping, + RepointedSavedPolicy, + SplitContent, +) + +from policyengine_api.constants import REPO +from policyengine_api.data.v2.settings import ( + V2_POLICY_COPY_SPLIT_DATABASE_URL, + V2ConfigurationError, +) +from scripts import split_v2_policy_copies + +if TYPE_CHECKING: + from collections.abc import Iterator + +OLD_COPY_ID = UUID("00000000-0000-0000-0000-0000000c0001") +SPLIT_POLICY_ID = UUID("00000000-0000-0000-0000-0000000c0002") +SPLIT_DYNAMIC_ID = UUID("00000000-0000-0000-0000-0000000c0003") +EARLIER_DYNAMIC_ID = UUID("00000000-0000-0000-0000-0000000c0004") +MERGED_DYNAMIC_ID = UUID("00000000-0000-0000-0000-0000000c0005") +SAVED_POLICY_ID = UUID("00000000-0000-0000-0000-0000000c0006") +SAVED_DYNAMIC_ID = UUID("00000000-0000-0000-0000-0000000c0007") +POLICY_HASH = "1" * 64 +DYNAMIC_HASH = "2" * 64 +MERGED_HASH = "3" * 64 +NO_REFERENCES = CopyReferences(simulations=0, reports=0, household_jobs=0) + + +def _split( + *, + applied: bool, + outcome: PolicyCopyOutcome = PolicyCopyOutcome.DELETED, + references: CopyReferences = NO_REFERENCES, + refusal_reason: PolicyCopyRefusalReason | None = None, +) -> PolicyCopySplit: + """One UK copy: a mapping that already named a dynamic, and one saved policy.""" + if refusal_reason is not None: + return PolicyCopySplit( + old_policy_id=OLD_COPY_ID, + country_id="uk", + policyengine_version="2.174.1", + applied=applied, + outcome=PolicyCopyOutcome.REFUSED, + policy=None, + dynamic=None, + mappings=(), + saved_policies=(), + references=references, + refusal_reason=refusal_reason, + ) + merged = SplitContent( + id=MERGED_DYNAMIC_ID if applied else None, + content_hash=MERGED_HASH, + created=True, + ) + return PolicyCopySplit( + old_policy_id=OLD_COPY_ID, + country_id="uk", + policyengine_version="2.174.1", + applied=applied, + outcome=outcome, + policy=SplitContent( + id=SPLIT_POLICY_ID, content_hash=POLICY_HASH, created=False + ), + dynamic=SplitContent( + id=SPLIT_DYNAMIC_ID if applied else None, + content_hash=DYNAMIC_HASH, + created=True, + ), + mappings=( + RepointedMapping( + country_id="uk", + legacy_policy_id=1234, + previous_dynamic_id=EARLIER_DYNAMIC_ID, + dynamic=merged, + ), + ), + saved_policies=( + RepointedSavedPolicy( + user_policy_id=SAVED_POLICY_ID, + dynamic=merged, + saved_dynamic_id=SAVED_DYNAMIC_ID if applied else None, + saved_dynamic_created=True, + ), + ), + references=references, + refusal_reason=None, + ) + + +class FakeSplitter: + """Return the given splits and remaining count, recording each call.""" + + def __init__( + self, splits: tuple[PolicyCopySplit, ...], *, remaining_copies: int = 0 + ) -> None: + self.splits = splits + self.remaining_copies = remaining_copies + self.calls: list[str] = [] + + def list_policy_copy_splits(self) -> tuple[PolicyCopySplit, ...]: + self.calls.append("list") + return self.splits + + def split_policy_copies(self) -> Iterator[PolicyCopySplit]: + self.calls.append("split") + yield from self.splits + + def count_policy_copies(self) -> int: + self.calls.append("count") + return self.remaining_copies + + +class RecordingFactory: + """Build the fake splitter, recording whether the command asked to write.""" + + def __init__(self, splitter: FakeSplitter) -> None: + self.splitter = splitter + self.writable: list[bool] = [] + + @contextmanager + def __call__(self, *, writable: bool) -> Iterator[FakeSplitter]: + self.writable.append(writable) + yield self.splitter + + +def test_the_command_only_lists_without_apply(capsys) -> None: + factory = RecordingFactory(FakeSplitter((_split(applied=False),))) + + exit_status = split_v2_policy_copies.main([], splitter_factory=factory) + + output = capsys.readouterr().out + assert exit_status == 0 + assert factory.writable == [False] + assert factory.splitter.calls == ["list"] + assert "Read-only listing: nothing was changed." in output + assert f"Policy copy {OLD_COPY_ID} (uk, catalog version 2.174.1)" in output + assert "would be deleted" in output + assert f"policy {SPLIT_POLICY_ID} (already stored)" in output + assert f"dynamic: would be created (content hash {DYNAMIC_HASH[:12]})" in output + assert "legacy policy uk 1234" in output + assert f"was dynamic {EARLIER_DYNAMIC_ID}" in output + assert f"saved policy {SAVED_POLICY_ID}" in output + assert "1 policy copy sets a model assumption: 1 would be deleted" in output + + +def test_the_command_applies_and_names_every_row_it_changes(capsys) -> None: + factory = RecordingFactory(FakeSplitter((_split(applied=True),))) + + exit_status = split_v2_policy_copies.main(["--apply"], splitter_factory=factory) + + output = capsys.readouterr().out + assert exit_status == 0 + assert factory.writable == [True] + assert factory.splitter.calls == ["split", "count"] + assert f"Policy copy {OLD_COPY_ID} (uk, catalog version 2.174.1): deleted" in ( + output + ) + assert f"policy {SPLIT_POLICY_ID} (already stored)" in output + assert f"dynamic {SPLIT_DYNAMIC_ID} (created)" in output + assert ( + f"legacy policy uk 1234: now policy {SPLIT_POLICY_ID} and dynamic " + f"{MERGED_DYNAMIC_ID} (was dynamic {EARLIER_DYNAMIC_ID})" + ) in output + assert ( + f"saved policy {SAVED_POLICY_ID}: now policy {SPLIT_POLICY_ID}; " + f"saved dynamic {SAVED_DYNAMIC_ID} (created) for dynamic {MERGED_DYNAMIC_ID}" + ) in output + assert "0 stored policies still set a model assumption." in output + + +def test_a_kept_copy_is_reported_and_fails_the_run(capsys) -> None: + references = CopyReferences(simulations=1, reports=2, household_jobs=0) + factory = RecordingFactory( + FakeSplitter( + ( + _split( + applied=True, + outcome=PolicyCopyOutcome.KEPT, + references=references, + ), + ), + remaining_copies=1, + ) + ) + + exit_status = split_v2_policy_copies.main(["--apply"], splitter_factory=factory) + + output = capsys.readouterr().out + assert exit_status == 1 + assert ( + "kept: named by 1 simulation, 2 reports and 0 household calculations" + ) in output + assert "1 stored policy still sets a model assumption." in output + + +def test_a_listing_with_a_refused_copy_fails(capsys) -> None: + factory = RecordingFactory( + FakeSplitter( + ( + _split( + applied=False, + refusal_reason=PolicyCopyRefusalReason.CONFLICTING_DYNAMIC_VALUES, + ), + ) + ) + ) + + exit_status = split_v2_policy_copies.main([], splitter_factory=factory) + + output = capsys.readouterr().out + assert exit_status == 1 + assert f"Policy copy {OLD_COPY_ID}" in output + assert "would be refused" in output + assert "conflicting_dynamic_values" in output + + +def test_a_listing_with_a_copy_to_keep_fails(capsys) -> None: + factory = RecordingFactory( + FakeSplitter( + ( + _split( + applied=False, + outcome=PolicyCopyOutcome.KEPT, + references=CopyReferences( + simulations=1, reports=0, household_jobs=0 + ), + ), + ) + ) + ) + + assert split_v2_policy_copies.main([], splitter_factory=factory) == 1 + assert "would be kept" in capsys.readouterr().out + + +def test_the_command_says_when_no_policy_sets_a_model_assumption(capsys) -> None: + factory = RecordingFactory(FakeSplitter(())) + + exit_status = split_v2_policy_copies.main([], splitter_factory=factory) + + assert exit_status == 0 + assert "No stored policy sets a model assumption." in capsys.readouterr().out + + +def test_the_command_needs_its_own_database_url(monkeypatch) -> None: + monkeypatch.delenv(V2_POLICY_COPY_SPLIT_DATABASE_URL, raising=False) + + with ( + pytest.raises(V2ConfigurationError, match=V2_POLICY_COPY_SPLIT_DATABASE_URL), + split_v2_policy_copies.splitter_on_temporary_role(writable=False), + ): + pass + + +def test_the_command_refuses_unknown_arguments() -> None: + with pytest.raises(SystemExit) as exit_info: + split_v2_policy_copies.main( + ["--dry-run"], splitter_factory=RecordingFactory(FakeSplitter(())) + ) + + assert exit_info.value.code == 2 + + +def test_loading_the_command_leaves_the_observability_runtime_unbuilt() -> None: + """The command and what its splitter factory loads mustn't build the runtime. + + Importing ``policyengine_api.observability`` builds the process-wide + runtime, which adds a root log handler and writes to the command's output. + """ + import_check = ( + "import sys\n" + "import scripts.split_v2_policy_copies\n" + "import policyengine_api.data.v2.database\n" + "import policyengine_api.services.v2.policy_copy_splits.database_session\n" + "import policyengine_api.services.v2.policy_copy_splits.services\n" + "loaded = 'policyengine_api.observability' in sys.modules\n" + "assert not loaded, 'the observability runtime was imported'\n" + ) + + result = subprocess.run( + [sys.executable, "-c", import_check], + cwd=REPO, + capture_output=True, + text=True, + check=False, + ) + + assert result.returncode == 0, result.stderr diff --git a/tests/unit/v2/test_dynamic_catalog.py b/tests/unit/v2/test_dynamic_catalog.py index b53267f43..ad4a1d72a 100644 --- a/tests/unit/v2/test_dynamic_catalog.py +++ b/tests/unit/v2/test_dynamic_catalog.py @@ -1,8 +1,8 @@ """Binding dynamics and policies to a catalog, and keeping their parameters apart. A dynamic holds only parameters under ``gov.simulation.`` (plus the US's -``simulation.``), and a policy holds none of them; each is refused with the -parameter names it may not set. +``simulation.`` and the UK's ``gov.dynamic.``), and a policy holds none of +them; each is refused with the parameter names it may not set. """ from __future__ import annotations @@ -280,3 +280,105 @@ def test_a_dynamic_that_cannot_be_written_is_a_storage_error( ) assert isinstance(failure.value.__cause__, SQLAlchemyError) + + +UK_OBR_LABOUR_SUPPLY_SWITCH = "gov.dynamic.obr_labour_supply_assumptions" +UK_INCOME_ELASTICITY = "gov.simulation.labour_supply_responses.income_elasticity" +UK_TAX_RATE = "gov.hmrc.income_tax.rates.uk[0].rate" + + +class UkCatalog: + """A UK catalog version with two model assumptions and one policy parameter.""" + + def __init__(self, session: Session) -> None: + self.model = TaxBenefitModel(name="policyengine-uk") + self.version = TaxBenefitModelVersion( + model=self.model, + version=RUNNING_VERSION, + current_law_id=1, + metadata_time_periods=[2026], + ) + self.parameter_ids = {} + for name in (UK_OBR_LABOUR_SUPPLY_SWITCH, UK_INCOME_ELASTICITY, UK_TAX_RATE): + parameter = Parameter(name=name, tax_benefit_model_version=self.version) + session.add(parameter) + self.parameter_ids[name] = parameter.id + session.commit() + + +@pytest.fixture +def uk_catalog(session: Session) -> UkCatalog: + return UkCatalog(session) + + +def _uk_values(catalog: UkCatalog, *names: str) -> list[dict[str, object]]: + return [ + { + "parameter_id": catalog.parameter_ids[name], + "value": False if name == UK_OBR_LABOUR_SUPPLY_SWITCH else 0.25, + "start_date": "2026-01-01T00:00:00Z", + } + for name in names + ] + + +def test_a_uk_policy_setting_gov_dynamic_is_refused_naming_it( + session: Session, uk_catalog: UkCatalog +) -> None: + policy_input = PolicyCreationInput( + country_id="uk", + tax_benefit_model_id=uk_catalog.model.id, + parameter_values=_uk_values( + uk_catalog, UK_TAX_RATE, UK_OBR_LABOUR_SUPPLY_SWITCH + ), + ) + + with pytest.raises(PolicySetsDynamicParametersError) as refusal: + resolve_policy_creation_input( + session, policy_input, running_policyengine_version=RUNNING_VERSION + ) + + assert refusal.value.parameter_names == (UK_OBR_LABOUR_SUPPLY_SWITCH,) + assert "gov.dynamic" in str(refusal.value) + assert "/v2/dynamics" in str(refusal.value) + + +def test_a_uk_dynamic_may_set_gov_dynamic( + session: Session, uk_catalog: UkCatalog +) -> None: + resolved = resolve_dynamic_creation_input( + session, + DynamicCreationInput( + country_id="uk", + tax_benefit_model_id=uk_catalog.model.id, + parameter_values=_uk_values( + uk_catalog, UK_OBR_LABOUR_SUPPLY_SWITCH, UK_INCOME_ELASTICITY + ), + ), + running_policyengine_version=RUNNING_VERSION, + ) + + assert {value.parameter_id for value in resolved.parameter_values} == { + uk_catalog.parameter_ids[UK_OBR_LABOUR_SUPPLY_SWITCH], + uk_catalog.parameter_ids[UK_INCOME_ELASTICITY], + } + + +def test_a_uk_dynamic_setting_a_policy_parameter_names_gov_dynamic_as_allowed( + session: Session, uk_catalog: UkCatalog +) -> None: + with pytest.raises(DynamicSetsPolicyParametersError) as refusal: + resolve_dynamic_creation_input( + session, + DynamicCreationInput( + country_id="uk", + tax_benefit_model_id=uk_catalog.model.id, + parameter_values=_uk_values( + uk_catalog, UK_OBR_LABOUR_SUPPLY_SWITCH, UK_TAX_RATE + ), + ), + running_policyengine_version=RUNNING_VERSION, + ) + + assert refusal.value.parameter_names == (UK_TAX_RATE,) + assert "gov.dynamic" in str(refusal.value) diff --git a/tests/unit/v2/test_policy_copy_split_rules.py b/tests/unit/v2/test_policy_copy_split_rules.py new file mode 100644 index 000000000..eaa688ba4 --- /dev/null +++ b/tests/unit/v2/test_policy_copy_split_rules.py @@ -0,0 +1,314 @@ +"""Splitting a stored policy copy, and merging a mapping's dynamic, without a database. + +C1 · 48's command splits each stored policy that sets a model assumption into +a policy and a dynamic on the copy's own catalog version. When a legacy +mapping already names a dynamic, the split-off values join it (the user's +decision 4 of 2026-11-25). +""" + +from __future__ import annotations + +from datetime import UTC, datetime +from uuid import UUID + +import pytest +from policyengine_api.services.v2.policy_copy_splits.transformations import ( + split_stored_policy, +) +from policyengine_api.services.v2.policy_copy_splits.types import ( + PolicyCopyRefusalReason, +) +from policyengine_api.services.v2.policy_copy_splits.validators import ( + PolicyCopySplitRefusedError, + merge_dynamic_content, +) + +from policyengine_api.data.v2.models import ( + Dynamic, + ParameterValue, + Policy, + TaxBenefitModelVersion, +) +from policyengine_api.services.v2.dynamics.types import ResolvedDynamicCreationInput +from policyengine_api.services.v2.policies.transformations import ( + stored_policy_creation_input, +) +from policyengine_api.services.v2.policies.validators import ( + MAXIMUM_POLICY_PARAMETER_VALUES, +) + +MODEL_ID = UUID("00000000-0000-0000-0000-00000000a001") +MODEL_VERSION_ID = UUID("00000000-0000-0000-0000-00000000a002") +OTHER_MODEL_VERSION_ID = UUID("00000000-0000-0000-0000-00000000a003") +POLICY_ID = UUID("00000000-0000-0000-0000-00000000a004") +DYNAMIC_ID = UUID("00000000-0000-0000-0000-00000000a005") +TAX_RATE_ID = UUID("00000000-0000-0000-0000-00000000b001") +OBR_SWITCH_ID = UUID("00000000-0000-0000-0000-00000000b002") +INCOME_ELASTICITY_ID = UUID("00000000-0000-0000-0000-00000000b003") +TAX_RATE = "gov.hmrc.income_tax.rates.uk[0].rate" +OBR_SWITCH = "gov.dynamic.obr_labour_supply_assumptions" +INCOME_ELASTICITY = "gov.simulation.labour_supply_responses.income_elasticity" +START_2026 = datetime(2026, 1, 1, tzinfo=UTC) +END_2026 = datetime(2026, 12, 31, tzinfo=UTC) +CATALOG_VERSION = "2.174.1" + + +def _model_version(model_version_id: UUID = MODEL_VERSION_ID) -> TaxBenefitModelVersion: + return TaxBenefitModelVersion( + id=model_version_id, + model_id=MODEL_ID, + version=CATALOG_VERSION, + current_law_id=1, + metadata_time_periods=[2026], + ) + + +def _stored_policy(country_id: str = "uk") -> Policy: + return Policy( + id=POLICY_ID, + country_id=country_id, + tax_benefit_model_id=MODEL_ID, + tax_benefit_model_version_id=MODEL_VERSION_ID, + canonicalization_version=1, + content_hash="a" * 64, + ) + + +def _stored_value( + parameter_id: UUID, + *, + value: object, + start_date: datetime = START_2026, + end_date: datetime | None = END_2026, + dynamic_id: UUID | None = None, +) -> ParameterValue: + """Return a stored value of the old copy, or of the dynamic `dynamic_id` names.""" + return ParameterValue( + parameter_id=parameter_id, + value_json=value, + start_date=start_date, + end_date=end_date, + policy_id=None if dynamic_id is not None else POLICY_ID, + dynamic_id=dynamic_id, + ) + + +def _stored_dynamic(model_version_id: UUID = MODEL_VERSION_ID) -> Dynamic: + return Dynamic( + id=DYNAMIC_ID, + country_id="uk", + tax_benefit_model_id=MODEL_ID, + tax_benefit_model_version_id=model_version_id, + canonicalization_version=1, + content_hash="b" * 64, + ) + + +def _existing_dynamic( + *values: ParameterValue, model_version_id: UUID = MODEL_VERSION_ID +) -> object: + return stored_policy_creation_input( + _stored_dynamic(model_version_id), + _model_version(model_version_id), + list(values), + ) + + +def _uk_split_off_dynamic(*values: ParameterValue) -> ResolvedDynamicCreationInput: + split = split_stored_policy( + _stored_policy(), + _model_version(), + [(value, OBR_SWITCH) for value in values], + ) + assert split is not None + return split.dynamic + + +def _value_triples(content: object) -> set[tuple[UUID, object, datetime | None]]: + return { + (value.parameter_id, value.value, value.end_date) + for value in content.parameter_values + } + + +def test_a_copy_is_split_on_its_own_catalog_version_keeping_its_values() -> None: + split = split_stored_policy( + _stored_policy(), + _model_version(), + [ + (_stored_value(TAX_RATE_ID, value=0.21), TAX_RATE), + (_stored_value(OBR_SWITCH_ID, value=False), OBR_SWITCH), + ( + _stored_value(INCOME_ELASTICITY_ID, value=0.1, end_date=None), + INCOME_ELASTICITY, + ), + ], + ) + + assert split is not None + for content in (split.policy, split.dynamic): + assert content.country_id == "uk" + assert content.tax_benefit_model_id == MODEL_ID + assert content.tax_benefit_model_version_id == MODEL_VERSION_ID + assert content.policyengine_version == CATALOG_VERSION + assert _value_triples(split.policy) == {(TAX_RATE_ID, 0.21, END_2026)} + assert isinstance(split.dynamic, ResolvedDynamicCreationInput) + assert _value_triples(split.dynamic) == { + (OBR_SWITCH_ID, False, END_2026), + (INCOME_ELASTICITY_ID, 0.1, None), + } + assert {value.start_date for value in split.dynamic.parameter_values} == { + START_2026 + } + + +def test_a_copy_holding_only_model_assumptions_splits_into_an_empty_policy() -> None: + split = split_stored_policy( + _stored_policy(), + _model_version(), + [(_stored_value(OBR_SWITCH_ID, value=False), OBR_SWITCH)], + ) + + assert split is not None + assert split.policy.parameter_values == [] + assert _value_triples(split.dynamic) == {(OBR_SWITCH_ID, False, END_2026)} + + +def test_a_copy_setting_no_model_assumption_is_not_split() -> None: + assert ( + split_stored_policy( + _stored_policy(), + _model_version(), + [(_stored_value(TAX_RATE_ID, value=0.21), TAX_RATE)], + ) + is None + ) + + +SPLIT_OFF_SWITCH = {(OBR_SWITCH_ID, 1, END_2026)} + + +@pytest.mark.parametrize( + ("country_id", "parameter_name", "expected_dynamic_values"), + [ + ("us", "simulation.marginal_tax_rate_delta", SPLIT_OFF_SWITCH), + ( + "us", + "gov.simulation.labor_supply_responses.elasticities.income", + SPLIT_OFF_SWITCH, + ), + ("us", OBR_SWITCH, None), + ("uk", OBR_SWITCH, SPLIT_OFF_SWITCH), + ("uk", "simulation.marginal_tax_rate_delta", None), + ], +) +def test_each_country_s_prefixes_decide_what_is_split_off( + country_id: str, + parameter_name: str, + expected_dynamic_values: set[tuple[UUID, object, datetime]] | None, +) -> None: + split = split_stored_policy( + _stored_policy(country_id), + _model_version(), + [ + (_stored_value(TAX_RATE_ID, value=0.21), TAX_RATE), + (_stored_value(OBR_SWITCH_ID, value=1), parameter_name), + ], + ) + + if expected_dynamic_values is None: + assert split is None + else: + assert split is not None + assert _value_triples(split.dynamic) == expected_dynamic_values + + +def test_a_mapping_s_dynamic_and_the_split_off_values_merge_into_one() -> None: + merged = merge_dynamic_content( + _existing_dynamic( + _stored_value(INCOME_ELASTICITY_ID, value=0.1, dynamic_id=DYNAMIC_ID) + ), + _uk_split_off_dynamic(_stored_value(OBR_SWITCH_ID, value=False)), + ) + + assert isinstance(merged, ResolvedDynamicCreationInput) + assert merged.tax_benefit_model_version_id == MODEL_VERSION_ID + assert merged.policyengine_version == CATALOG_VERSION + assert _value_triples(merged) == { + (INCOME_ELASTICITY_ID, 0.1, END_2026), + (OBR_SWITCH_ID, False, END_2026), + } + + +def test_a_value_both_dynamics_set_identically_is_kept_once() -> None: + merged = merge_dynamic_content( + _existing_dynamic( + _stored_value(OBR_SWITCH_ID, value=False, dynamic_id=DYNAMIC_ID) + ), + _uk_split_off_dynamic(_stored_value(OBR_SWITCH_ID, value=False)), + ) + + assert _value_triples(merged) == {(OBR_SWITCH_ID, False, END_2026)} + + +@pytest.mark.parametrize( + ("existing_value", "existing_end_date"), + [ + pytest.param(True, END_2026, id="different-value"), + # JSON true and 0 or 1 are different values, though Python compares + # True equal to 1. + pytest.param(0, END_2026, id="integer-for-boolean"), + pytest.param(False, None, id="different-end-date"), + ], +) +def test_a_value_the_two_dynamics_set_differently_refuses_the_copy( + existing_value: object, existing_end_date: datetime | None +) -> None: + with pytest.raises(PolicyCopySplitRefusedError) as refusal: + merge_dynamic_content( + _existing_dynamic( + _stored_value( + OBR_SWITCH_ID, + value=existing_value, + end_date=existing_end_date, + dynamic_id=DYNAMIC_ID, + ) + ), + _uk_split_off_dynamic(_stored_value(OBR_SWITCH_ID, value=False)), + ) + + assert refusal.value.reason is PolicyCopyRefusalReason.CONFLICTING_DYNAMIC_VALUES + + +def test_a_mapping_s_dynamic_on_another_catalog_version_refuses_the_copy() -> None: + with pytest.raises(PolicyCopySplitRefusedError) as refusal: + merge_dynamic_content( + _existing_dynamic( + _stored_value(INCOME_ELASTICITY_ID, value=0.1, dynamic_id=DYNAMIC_ID), + model_version_id=OTHER_MODEL_VERSION_ID, + ), + _uk_split_off_dynamic(_stored_value(OBR_SWITCH_ID, value=False)), + ) + + assert refusal.value.reason is PolicyCopyRefusalReason.DYNAMIC_ON_ANOTHER_CATALOG + + +def test_a_merged_dynamic_over_the_value_limit_refuses_the_copy() -> None: + existing_values = [ + _stored_value( + INCOME_ELASTICITY_ID, + value=0.1, + start_date=datetime(2026, 1, 1, tzinfo=UTC).replace(year=1000 + index), + end_date=None, + dynamic_id=DYNAMIC_ID, + ) + for index in range(MAXIMUM_POLICY_PARAMETER_VALUES) + ] + + with pytest.raises(PolicyCopySplitRefusedError) as refusal: + merge_dynamic_content( + _existing_dynamic(*existing_values), + _uk_split_off_dynamic(_stored_value(OBR_SWITCH_ID, value=False)), + ) + + assert refusal.value.reason is PolicyCopyRefusalReason.TOO_MANY_VALUES diff --git a/tests/unit/v2/test_policy_copy_split_runbook.py b/tests/unit/v2/test_policy_copy_split_runbook.py new file mode 100644 index 000000000..c9d1b922d --- /dev/null +++ b/tests/unit/v2/test_policy_copy_split_runbook.py @@ -0,0 +1,75 @@ +"""The split command's runbook creates the role the command's grants declare. + +C1 · 49's operator creates a temporary role from the runbook's SQL in +``docs/migration/stage-10-v2-policies.md``, so its GRANTs must be exactly the +ones ``POLICY_COPY_SPLIT_PRIVILEGES`` declares. +""" + +from __future__ import annotations + +import re +from pathlib import Path + +from policyengine_api.data.v2.privilege_plans import ( + GrantedPrivileges, + grant_statements, + plan_reconciliation, +) +from policyengine_api.data.v2.privileges import ( + POLICY_COPY_SPLIT_PRIVILEGES, + POLICY_COPY_SPLIT_ROLE, +) + +RUNBOOK = Path(__file__).parents[3] / "docs/migration/stage-10-v2-policies.md" +SQL_BLOCK = re.compile(r"```sql\n(.*?)```", re.DOTALL) +TABLE_GRANT = re.compile(r"^\s*(GRANT .+ ON TABLE .+?);?\s*$") + + +def _runbook_sql_blocks() -> list[str]: + return SQL_BLOCK.findall(RUNBOOK.read_text(encoding="utf-8")) + + +def _block_containing(text: str) -> str: + [block] = [block for block in _runbook_sql_blocks() if text in block] + return block + + +def _declared_grants() -> list[str]: + plan = plan_reconciliation( + {POLICY_COPY_SPLIT_ROLE: POLICY_COPY_SPLIT_PRIVILEGES}, + GrantedPrivileges(tables={}, columns={}), + existing_roles={POLICY_COPY_SPLIT_ROLE}, + existing_tables=set(POLICY_COPY_SPLIT_PRIVILEGES), + ) + return sorted(grant_statements(plan, lambda identifier: identifier)) + + +def test_the_runbook_grants_the_role_exactly_its_declared_privileges() -> None: + creation = _block_containing(f"CREATE ROLE {POLICY_COPY_SPLIT_ROLE}") + + runbook_grants = sorted( + match.group(1) + for statement in creation.splitlines() + if (match := TABLE_GRANT.match(statement)) + ) + + assert runbook_grants == _declared_grants() + + +def test_the_runbook_creates_a_login_role_with_no_other_powers() -> None: + creation = _block_containing(f"CREATE ROLE {POLICY_COPY_SPLIT_ROLE}") + + assert ( + f"CREATE ROLE {POLICY_COPY_SPLIT_ROLE} LOGIN NOSUPERUSER NOCREATEDB " + "NOCREATEROLE NOREPLICATION NOBYPASSRLS NOINHERIT PASSWORD" + ) in creation + assert f"GRANT USAGE ON SCHEMA public TO {POLICY_COPY_SPLIT_ROLE};" in creation + assert creation.lstrip().startswith("DO $$") + + +def test_the_runbook_drops_the_role_and_its_grants() -> None: + removal = _block_containing(f"DROP ROLE {POLICY_COPY_SPLIT_ROLE}") + + assert f"DROP OWNED BY {POLICY_COPY_SPLIT_ROLE};" in removal + assert removal.index("DROP OWNED BY") < removal.index("DROP ROLE") + assert removal.lstrip().startswith("DO $$") diff --git a/tests/unit/v2/test_policy_legacy_copy.py b/tests/unit/v2/test_policy_legacy_copy.py index 7bf5b903a..dab6c6554 100644 --- a/tests/unit/v2/test_policy_legacy_copy.py +++ b/tests/unit/v2/test_policy_legacy_copy.py @@ -445,6 +445,45 @@ def test_a_uk_policy_with_only_old_spelling_assumptions_maps_to_an_empty_policy( ] +def test_a_uk_policy_s_gov_dynamic_values_are_copied_into_its_dynamic( + catalog_session: Session, recorded_writes: RecordedCopyWrites +) -> None: + uk_tax_rate = "gov.hmrc.income_tax.rates.uk[0].rate" + uk_obr_switch = "gov.dynamic.obr_labour_supply_assumptions" + _version, parameters = _add_running_catalog( + catalog_session, + country_id="uk", + parameter_names=[uk_tax_rate, uk_obr_switch, UK_INCOME_ELASTICITY], + ) + + result = _copy( + catalog_session, + _snapshot( + country_id="uk", + legacy_policy_id=503, + api_version="2.174.1", + policy_json={ + uk_tax_rate: {"2026": 0.21}, + uk_obr_switch: {"2026": False}, + UK_INCOME_ELASTICITY: {"2026": 0.1}, + }, + ), + ) + + assert result.dynamic_id == COPIED_DYNAMIC_ID + [copied_policy] = recorded_writes.created_policies + assert [value.parameter_id for value in copied_policy.parameter_values] == [ + parameters[uk_tax_rate].id + ] + [copied_dynamic] = recorded_writes.created_dynamics + assert { + (value.parameter_id, value.value) for value in copied_dynamic.parameter_values + } == { + (parameters[uk_obr_switch].id, False), + (parameters[UK_INCOME_ELASTICITY].id, 0.1), + } + + @pytest.mark.parametrize( ("policy_json", "reason"), [ diff --git a/tests/unit/v2/test_privilege_manifest.py b/tests/unit/v2/test_privilege_manifest.py index f577472c3..2bfed76fc 100644 --- a/tests/unit/v2/test_privilege_manifest.py +++ b/tests/unit/v2/test_privilege_manifest.py @@ -23,6 +23,8 @@ CATALOG_WRITER_ROLE, MODAL_WORKER_ROLE, NO_ACCESS, + POLICY_COPY_SPLIT_PRIVILEGES, + POLICY_COPY_SPLIT_ROLE, READ, READ_INSERT, READ_INSERT_DELETE, @@ -44,6 +46,9 @@ SERVICES_ROOT = PROJECT_ROOT / "policyengine_api" / "services" / "v2" PROOF_FIXTURES = PROJECT_ROOT / "rules/fixtures/api.v2.runtime-privileges-declared" STAGE12_PACKAGES = frozenset({"comparison_runs"}) +# Run once, by hand, as a temporary role the operator creates with +# POLICY_COPY_SPLIT_PRIVILEGES (C1 · 48 and C1 · 49), never as a managed role. +POLICY_COPY_SPLIT_PACKAGES = frozenset({"policy_copy_splits"}) TEST_ENVIRONMENT = "staging" # The rows the simulation service creates, and the run tables among them. SIMULATION_SERVICE_CREATES = frozenset( @@ -200,12 +205,24 @@ def _connector_modules(*, stage12: bool) -> list[str]: path.relative_to(SERVICES_ROOT).as_posix() for path in SERVICES_ROOT.glob("*/database_connectors/*.py") if path.name != "__init__.py" + and path.parts[-3] not in POLICY_COPY_SPLIT_PACKAGES and (path.parts[-3] in STAGE12_PACKAGES) is stage12 ) assert paths, "no connector modules found" return paths +def _policy_copy_split_connector_modules() -> list[str]: + paths = sorted( + path.relative_to(SERVICES_ROOT).as_posix() + for package in POLICY_COPY_SPLIT_PACKAGES + for path in (SERVICES_ROOT / package / "database_connectors").glob("*.py") + if path.name != "__init__.py" + ) + assert paths, "no policy copy split connector modules found" + return paths + + def _missing(relative_path: str, role: str) -> list[str]: requirements = required_privileges( SERVICES_ROOT / relative_path, _table_by_model(), connector=relative_path @@ -261,6 +278,72 @@ def test_stage12_connectors_need_only_declared_stage12_privileges( assert _missing(relative_path, stage12_role(TEST_ENVIRONMENT)) == [] +@pytest.mark.parametrize("relative_path", _policy_copy_split_connector_modules()) +def test_policy_copy_split_connectors_need_only_the_temporary_role_s_privileges( + relative_path: str, +) -> None: + requirements = required_privileges( + SERVICES_ROOT / relative_path, _table_by_model(), connector=relative_path + ) + + assert requirements, "the analysis found no table this connector uses" + assert [ + f"{missing.connector}: {missing.privilege} on {missing.table} " + f"({missing.reason})" + for missing in undeclared_requirements( + requirements, POLICY_COPY_SPLIT_PRIVILEGES + ) + ] == [] + + +def test_the_policy_copy_split_role_deletes_only_policies_and_is_not_managed() -> None: + """The split command's temporary role changes only what the split must change. + + It deletes old policy copies (their values go with them by the foreign + key's cascade), locks them, re-points legacy mappings and saved policies, + and inserts policies, dynamics, their values and saved dynamics. It reads + the catalog and the simulations, reports and household calculations that + may name a copy. No deploy grants it anything: the operator creates it for + C1 · 49 and drops it afterwards. + """ + write_privileges = { + table: privileges & WRITE_PRIVILEGES + for table, privileges in POLICY_COPY_SPLIT_PRIVILEGES.items() + if privileges & WRITE_PRIVILEGES + } + + assert write_privileges == { + "dynamics": {TablePrivilege.INSERT}, + "legacy_policy_mappings": {TablePrivilege.UPDATE}, + "parameter_values": {TablePrivilege.INSERT}, + "policies": { + TablePrivilege.INSERT, + TablePrivilege.UPDATE, + TablePrivilege.DELETE, + }, + "user_dynamics": {TablePrivilege.INSERT}, + "user_policies": {TablePrivilege.UPDATE}, + } + assert { + table + for table, privileges in POLICY_COPY_SPLIT_PRIVILEGES.items() + if privileges == READ + } == { + "household_jobs", + "parameters", + "reports", + "simulations", + "tax_benefit_model_versions", + } + assert set(POLICY_COPY_SPLIT_PRIVILEGES) <= set(TABLE_ACCESS) + assert all( + TablePrivilege.SELECT in privileges + for privileges in POLICY_COPY_SPLIT_PRIVILEGES.values() + ) + assert POLICY_COPY_SPLIT_ROLE == "policyengine_v2_policy_copy_split" + assert POLICY_COPY_SPLIT_ROLE not in declared_privileges(TEST_ENVIRONMENT) + + def test_stage12_role_name_follows_the_deployment_environment() -> None: assert stage12_role("staging") == "policyengine_stage12_staging" assert stage12_role("production") == "policyengine_stage12_production" diff --git a/tests/unit/v2/test_settings.py b/tests/unit/v2/test_settings.py index 8a0f03bb8..65d18f9b1 100644 --- a/tests/unit/v2/test_settings.py +++ b/tests/unit/v2/test_settings.py @@ -5,6 +5,7 @@ from policyengine_api.data.v2.settings import ( V2_DATA_WRITE_DATABASE_URL, V2_MIGRATION_DATABASE_URL, + V2_POLICY_COPY_SPLIT_DATABASE_URL, V2_RUNTIME_DATABASE_URL, V2_RUNTIME_DATABASE_URL_SECRET_RESOURCE, V2_SUPABASE_ENVIRONMENT, @@ -12,6 +13,7 @@ V2ConfigurationError, load_v2_data_write_database_settings, load_v2_migration_database_settings, + load_v2_policy_copy_split_database_settings, load_v2_runtime_database_settings, ) @@ -55,6 +57,27 @@ def test_runtime_migration_and_data_write_urls_are_explicit_and_separate() -> No assert runtime.target == migration.target == data_write.target +def test_the_policy_copy_split_url_is_its_own_setting() -> None: + """The split command connects as C1 · 49's temporary role, by its own URL.""" + split_url = ( + f"postgresql+psycopg://policy-copy-split:test-split-password@db.{PROJECT_REF}." + "supabase.co:5432/postgres?sslmode=require" + ) + environment = { + **TARGET_ENVIRONMENT, + V2_MIGRATION_DATABASE_URL: MIGRATION_URL, + V2_POLICY_COPY_SPLIT_DATABASE_URL: split_url, + } + + settings = load_v2_policy_copy_split_database_settings(environment) + + assert settings.connection.url.username == "policy-copy-split" + with pytest.raises(V2ConfigurationError, match=V2_POLICY_COPY_SPLIT_DATABASE_URL): + load_v2_policy_copy_split_database_settings( + {**TARGET_ENVIRONMENT, V2_MIGRATION_DATABASE_URL: MIGRATION_URL} + ) + + def test_postgres_password_is_hidden_from_string_and_repr() -> None: settings = load_v2_runtime_database_settings( {**TARGET_ENVIRONMENT, V2_RUNTIME_DATABASE_URL: RUNTIME_URL} @@ -174,6 +197,10 @@ def test_runtime_rejects_non_persistent_postgres_targets(url: str) -> None: (V2_RUNTIME_DATABASE_URL, load_v2_runtime_database_settings), (V2_MIGRATION_DATABASE_URL, load_v2_migration_database_settings), (V2_DATA_WRITE_DATABASE_URL, load_v2_data_write_database_settings), + ( + V2_POLICY_COPY_SPLIT_DATABASE_URL, + load_v2_policy_copy_split_database_settings, + ), ], ) def test_every_database_url_must_identify_the_configured_supabase_project( From d54f64dfa50a75783b59a4454fab1d1a79d350ae Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:38:06 +0400 Subject: [PATCH 2/9] =?UTF-8?q?C1=20=C2=B7=2048:=20UK=20gov.dynamic=20is?= =?UTF-8?q?=20a=20model=20assumption,=20and=20a=20command=20splits=20store?= =?UTF-8?q?d=20policy=20copies?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - DYNAMIC_PARAMETER_PREFIXES gains UK gov.dynamic., so /v2/policies refuses it with 422 dynamic_parameters, /v2/dynamics accepts it, and the v1-to-v2 copy puts it in the copy's dynamic. The errors, OpenAPI descriptions and docs that list the prefixes name it. - services/v2/policy_copy_split splits each stored policy that sets a model assumption into a policy and a dynamic on its own catalog version, through create_resolved_policy and create_resolved_dynamic. In one transaction per copy, which locks it first, it re-points the legacy mappings (merging a mapping's existing dynamic with the copy's assumptions) and saved policies, gives each saved policy's owner a saved dynamic with its name unless an identical one exists, and deletes the copy once nothing names it. A copy a simulation, report or household job names is kept; one whose mapping's dynamic conflicts is refused. split_policy_copy_in_session is D4 · 1's. - scripts/split_v2_policy_copies.py lists what would change in READ ONLY transactions, or with --apply makes the changes, as the temporary role policyengine_v2_policy_copy_split. POLICY_COPY_SPLIT_PRIVILEGES declares its grants, and docs/migration/stage-10-v2-policies.md gives the SQL that creates and drops it, with the deploy order. - The Postgres tests run in the cross-database integration job. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/v2-integration-check.yml | 4 +- changelog.d/v2-policy-copy-split.changed.md | 1 + docs/migration/stage-10-v2-policies.md | 143 ++++- policyengine_api/data/v2/database.py | 51 ++ policyengine_api/data/v2/models/policies.py | 3 +- policyengine_api/data/v2/privileges.py | 28 + policyengine_api/data/v2/settings.py | 18 + policyengine_api/dynamic_parameters.py | 21 +- .../v2/dynamics/request_models.py | 4 +- .../fastapi_routes/v2/dynamics/routes.py | 5 +- .../v2/policies/response_models.py | 5 +- .../fastapi_routes/v2/policies/routes.py | 5 +- .../services/v2/dynamics/types.py | 3 +- .../services/v2/dynamics/validators.py | 11 +- .../services/v2/policies/services.py | 3 +- .../services/v2/policies/validators.py | 11 +- .../services/v2/policy_copy_split/__init__.py | 1 + .../database_connectors/__init__.py | 1 + .../database_connectors/deletes.py | 25 + .../database_connectors/reads.py | 164 ++++++ .../database_connectors/updates.py | 38 ++ .../v2/policy_copy_split/database_session.py | 36 ++ .../services/v2/policy_copy_split/services.py | 489 ++++++++++++++++++ .../v2/policy_copy_split/transformations.py | 64 +++ .../services/v2/policy_copy_split/types.py | 183 +++++++ .../v2/policy_copy_split/validators.py | 112 ++++ pyproject.toml | 2 + scripts/split_v2_policy_copies.py | 252 +++++++++ .../integration/test_v2_policy_copy_splits.py | 28 +- .../test_split_v2_policy_copies_script.py | 18 +- tests/unit/test_v2_integration_workflow.py | 10 + tests/unit/v2/test_policy_copy_split_rules.py | 20 +- tests/unit/v2/test_privilege_manifest.py | 2 +- 33 files changed, 1692 insertions(+), 69 deletions(-) create mode 100644 changelog.d/v2-policy-copy-split.changed.md create mode 100644 policyengine_api/services/v2/policy_copy_split/__init__.py create mode 100644 policyengine_api/services/v2/policy_copy_split/database_connectors/__init__.py create mode 100644 policyengine_api/services/v2/policy_copy_split/database_connectors/deletes.py create mode 100644 policyengine_api/services/v2/policy_copy_split/database_connectors/reads.py create mode 100644 policyengine_api/services/v2/policy_copy_split/database_connectors/updates.py create mode 100644 policyengine_api/services/v2/policy_copy_split/database_session.py create mode 100644 policyengine_api/services/v2/policy_copy_split/services.py create mode 100644 policyengine_api/services/v2/policy_copy_split/transformations.py create mode 100644 policyengine_api/services/v2/policy_copy_split/types.py create mode 100644 policyengine_api/services/v2/policy_copy_split/validators.py create mode 100755 scripts/split_v2_policy_copies.py diff --git a/.github/workflows/v2-integration-check.yml b/.github/workflows/v2-integration-check.yml index 61d18738a..61d6020e5 100644 --- a/.github/workflows/v2-integration-check.yml +++ b/.github/workflows/v2-integration-check.yml @@ -75,8 +75,8 @@ jobs: run: uv run --frozen --extra dev python scripts/reconcile_v2_privileges.py verify - name: Test v2 metadata publication, resource routes, the countries list, reports, simulations and users' report runs run: uv run --frozen --extra dev coverage run --branch -m pytest -q tests/integration/test_v2_catalog_publication.py tests/integration/test_v2_catalog_publication_time_periods.py tests/integration/test_v2_catalog_publication_pruning.py tests/integration/test_v2_catalog_spm_availability.py tests/integration/test_v2_catalog_statistics.py tests/integration/test_v2_metadata_routes.py tests/integration/test_v2_country_routes.py tests/integration/test_v2_report_reads.py tests/integration/test_v2_report_creation.py tests/integration/test_v2_budget_window_report_reads.py tests/integration/test_v2_budget_window_report_creation.py tests/integration/test_v2_report_runs.py tests/integration/test_v2_report_reads_by_run.py tests/integration/test_v2_user_report_runs.py tests/integration/test_v2_user_report_run_requesters.py tests/integration/test_v2_user_budget_window_runs.py tests/integration/test_v2_forced_report_reruns.py tests/integration/test_v2_user_report_views.py - - name: Test v2 policy persistence and immediate v1 mirroring - run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_policy_persistence.py tests/integration/test_v1_policy_dual_write.py tests/integration/test_mysql_policy_dual_write.py tests/integration/test_v2_user_policy_mirroring.py tests/integration/test_v1_user_policy_dual_write.py + - name: Test v2 policy persistence, immediate v1 mirroring and the policy copy split + run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_policy_persistence.py tests/integration/test_v2_policy_copy_splits.py tests/integration/test_v1_policy_dual_write.py tests/integration/test_mysql_policy_dual_write.py tests/integration/test_v2_user_policy_mirroring.py tests/integration/test_v1_user_policy_dual_write.py - name: Test signed-in identity provisioning, user associations, saved detailed-save records and user types run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_user_identity_persistence.py tests/integration/test_v2_user_type_persistence.py tests/integration/test_v2_saved_detailed_save_records.py tests/integration/test_v2_saved_budget_window_reports.py - name: Test comparison-run persistence, the simulation API's roles, shared reports and runs, and privilege reconciliation as the managed roles diff --git a/changelog.d/v2-policy-copy-split.changed.md b/changelog.d/v2-policy-copy-split.changed.md new file mode 100644 index 000000000..04cbdf51a --- /dev/null +++ b/changelog.d/v2-policy-copy-split.changed.md @@ -0,0 +1 @@ +UK `gov.dynamic.` parameters (in policyengine-uk 2.174.1, the yes/no switch `gov.dynamic.obr_labour_supply_assumptions`) are now model assumptions, like `gov.simulation.`: `POST /v2/policies` refuses them with 422 `dynamic_parameters`, `POST /v2/dynamics` accepts them, and the v1-to-v2 policy copy puts them in the copy's dynamic. A new command, `scripts/split_v2_policy_copies.py`, splits every stored v2 policy that sets a model assumption into a policy and a dynamic on its own catalog version, re-points its legacy policy mappings and saved policies (giving each saved policy's owner a saved dynamic with its name), and deletes the old policy once nothing names it; it only lists what it would change unless given `--apply`, and runs as a temporary database role (`docs/migration/stage-10-v2-policies.md`). diff --git a/docs/migration/stage-10-v2-policies.md b/docs/migration/stage-10-v2-policies.md index ca5f2834e..0a0172304 100644 --- a/docs/migration/stage-10-v2-policies.md +++ b/docs/migration/stage-10-v2-policies.md @@ -137,8 +137,9 @@ parameter path it sets exists in the running catalog and its periods and values are valid. The copy splits off the v1 policy's model assumptions: every value under -`gov.simulation.`, and in the US also `simulation.` -(`policyengine_api/dynamic_parameters.py`). It stores them as a v2 dynamic, +`gov.simulation.`, plus `simulation.` in the US and `gov.dynamic.` in the UK +(`policyengine_api/dynamic_parameters.py`; UK `gov.dynamic.` joined on +C1 · 48's deploy). It stores them as a v2 dynamic, hashed and deduplicated as a policy is, and keeps the rest in the v2 policy, which is empty when the v1 policy set nothing else. Before looking up the parameters it rewrites the UK's old spelling @@ -148,8 +149,10 @@ v1 policy that sets one parameter under both spellings with different values fails as `conflicting_values`. The mapping in `legacy_policy_mappings` names the policy and the dynamic (`dynamic_id`), or no dynamic when the v1 policy sets no assumptions. A v1 policy copied before the split existed keeps its copy: its -assumptions stay policy values and its mapping names no dynamic, until the -one-time migration splits it again. Native `POST /v2/policies` refuses such +assumptions stay policy values and its mapping names no dynamic, and a UK +copy made before `gov.dynamic.` joined keeps those values in its policy too, +until the split command splits it (see "Splitting stored policies that hold +model assumptions" below). Native `POST /v2/policies` refuses such values with 422 instead (code `dynamic_parameters`), and they are created through `POST /v2/dynamics`. @@ -287,3 +290,135 @@ is deleted, and existing Cloud SQL `user_policies` rows are kept. The Public API also no longer serves Canada, Nigeria and Israel: their v1 policy requests are rejected as unknown countries before any write, so every v1 policy write is now for a country that v2 supports. + +## Splitting stored policies that hold model assumptions + +`scripts/split_v2_policy_copies.py` (C1 · 48, run as the operator step C1 · 49) +splits every stored v2 policy that sets a model assumption: a parameter under +`gov.simulation.`, US `simulation.` or UK `gov.dynamic.` +(`policyengine_api/dynamic_parameters.py`). The v1-to-v2 copy made such +policies before it split model assumptions off, and for UK `gov.dynamic.` +values until that prefix joined; a v1 policy is never copied again. C1 · 50's +revision, which moves dynamic parameters into their own tables, refuses to +run while any policy value names one, because the foreign key's cascade would +otherwise change those policies silently. + +For each such policy, in one transaction that first locks it (`SELECT … FOR +UPDATE`, so nothing can start naming it meanwhile), the command +(`policyengine_api/services/v2/policy_copy_split/services.py`): + +- finds or creates a policy holding the values that aren't model assumptions, + empty when there are none, and a dynamic holding the model assumptions, + both on the copy's own catalog version, with the same parameter IDs, values + and dates, through the services `POST /v2/policies` and `POST /v2/dynamics` + store them with; +- points each `legacy_policy_mappings` row that names the copy at that policy + and dynamic. A mapping that already names a dynamic (a UK copy made after + C1 · 36 holding `gov.dynamic.` values) gets one dynamic holding that + dynamic's values and the copy's model assumptions together; the earlier + dynamic is kept; +- points each `user_policies` row that names the copy at that policy, keeping + its name, description and label, and gives its owner a `user_dynamics` row + with the saved policy's name and no description, naming the dynamic the + saved policy's own v1 policy's mapping now names, or else the copy's + dynamic. When the owner already has a saved dynamic in that country naming + the same dynamic with the same name (two empty names count as the same), + that one is reused; +- deletes the copy, and its values with it, once nothing names it. + +A copy that a `simulations`, `reports` or `household_jobs` row names is +split and its mappings and saved policies are re-pointed, but the copy is +kept: those rows' keys hash the policy, and their `policy_id` is `ON DELETE +SET NULL`, so deleting the copy would silently make them current law. A copy +whose mapping's dynamic sets one of its model assumptions for the same start +date differently, is bound to another catalog version, or would hold more +than 1,000 values together with it, is refused, and nothing changes for it. +The user decided these cases on 2026-11-25. + +Running the command again changes nothing: a re-pointed mapping or saved +policy no longer names the copy, and the policy and dynamic are found by +their content hashes. A kept copy is listed as kept again. + +### Deploy order + +1. API v1's release containing C1 · 48 (and so C1 · 36 and C1 · 43) deploys + in the environment, so the v1-to-v2 copy there splits UK `gov.dynamic.` + values too and no new policy holding model assumptions is stored. +2. C1 · 49 runs the command there: the read-only listing, then `--apply`, + then the listing again, which must list nothing. +3. Only then does C1 · 50's revision run in that environment. + +### The temporary role + +The command connects as `policyengine_v2_policy_copy_split`, which holds only +the grants `POLICY_COPY_SPLIT_PRIVILEGES` declares +(`policyengine_api/data/v2/privileges.py`; a test checks the statements below +match it). No deploy grants, checks or reports the role. Create it in the +environment's v2 database, as a login that may grant on the migration role's +tables, with a SCRAM-SHA-256 verifier made locally in place of the password, +so the database never receives the password itself. Each block is one +statement, so `supabase db query` takes it in one call: + +```sql +DO $$ +BEGIN + CREATE ROLE policyengine_v2_policy_copy_split LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS NOINHERIT PASSWORD ''; + GRANT USAGE ON SCHEMA public TO policyengine_v2_policy_copy_split; + GRANT DELETE, INSERT, SELECT, UPDATE ON TABLE public.policies TO policyengine_v2_policy_copy_split; + GRANT INSERT, SELECT ON TABLE public.dynamics TO policyengine_v2_policy_copy_split; + GRANT INSERT, SELECT ON TABLE public.parameter_values TO policyengine_v2_policy_copy_split; + GRANT INSERT, SELECT ON TABLE public.user_dynamics TO policyengine_v2_policy_copy_split; + GRANT SELECT ON TABLE public.household_jobs TO policyengine_v2_policy_copy_split; + GRANT SELECT ON TABLE public.parameters TO policyengine_v2_policy_copy_split; + GRANT SELECT ON TABLE public.reports TO policyengine_v2_policy_copy_split; + GRANT SELECT ON TABLE public.simulations TO policyengine_v2_policy_copy_split; + GRANT SELECT ON TABLE public.tax_benefit_model_versions TO policyengine_v2_policy_copy_split; + GRANT SELECT, UPDATE ON TABLE public.legacy_policy_mappings TO policyengine_v2_policy_copy_split; + GRANT SELECT, UPDATE ON TABLE public.user_policies TO policyengine_v2_policy_copy_split; +END +$$; +``` + +Deleting a policy needs no privilege on `parameter_values`: PostgreSQL runs a +foreign key's cascade as the table's owner. After the run, drop the role and +its grants: + +```sql +DO $$ +BEGIN + DROP OWNED BY policyengine_v2_policy_copy_split; + DROP ROLE policyengine_v2_policy_copy_split; +END +$$; +``` + +### Running it + +From a checkout of the deployed release, with three variables set in the +shell for the run only: + +- `V2_POLICY_COPY_SPLIT_DATABASE_URL`: the temporary role's + `postgresql+psycopg://` URL with `sslmode=require` (or `verify-ca` or + `verify-full`), on the project's direct host or its pooler; +- `V2_SUPABASE_PROJECT_REF` and `V2_SUPABASE_ENVIRONMENT`: the values of the + GitHub Actions environment variables of the same names, which the command + checks the URL against. + +```bash +uv run --frozen python scripts/split_v2_policy_copies.py +uv run --frozen python scripts/split_v2_policy_copies.py --apply +``` + +Without `--apply`, every transaction is `READ ONLY`, and the command lists +for each copy the policy and dynamic it would point at (by ID when stored, +otherwise by content hash), each legacy mapping (country and v1 policy ID, +with the dynamic it named before) and saved policy it would re-point, each +saved dynamic it would add or reuse, and whether the copy would be deleted, +kept (with how many simulations, reports and household calculations name it) +or refused (with the reason). With `--apply` it reports the same with the IDs +of the rows it points at or creates, as each copy's transaction commits. It +prints no URL, saved-policy name or user ID. + +It exits with 0 when no stored policy sets a model assumption afterwards (for +the listing: when every listed copy would be deleted), and with 1 otherwise. +Missing settings or a failed connection raise, and also exit with 1. diff --git a/policyengine_api/data/v2/database.py b/policyengine_api/data/v2/database.py index f72524f5c..c47c8091b 100644 --- a/policyengine_api/data/v2/database.py +++ b/policyengine_api/data/v2/database.py @@ -4,12 +4,14 @@ import atexit import os +from contextlib import contextmanager from dataclasses import dataclass from threading import Lock from typing import TYPE_CHECKING from sqlalchemy import event from sqlalchemy.orm import sessionmaker +from sqlalchemy.pool import NullPool from sqlmodel import Session, create_engine from policyengine_api.data.v2.settings import ( @@ -19,7 +21,10 @@ ) if TYPE_CHECKING: + from collections.abc import Callable, Iterator + from sqlalchemy import Engine + from sqlalchemy.engine import URL DATABASE_POOL_RECYCLE_SECONDS = 1800 DATABASE_POOL_SIZE = 5 @@ -120,6 +125,52 @@ def build_v2_read_session_factory(engine: Engine) -> sessionmaker[Session]: return factory +@contextmanager +def _unpooled_sessions( + url: str | URL, build_factory: Callable[[Engine], sessionmaker[Session]] +) -> Iterator[sessionmaker[Session]]: + """Yield ``build_factory``'s Session factories on a new engine for ``url``. + + The engine keeps no connection pool, so no connection outlives its + Session, and is disposed of on exit. + """ + engine = create_engine(url, poolclass=NullPool) + try: + yield build_factory(engine) + finally: + engine.dispose() + + +@contextmanager +def unpooled_v2_sessions(url: str | URL) -> Iterator[sessionmaker[Session]]: + """Yield v2 Session factories for one command's work on the database at ``url``. + + For commands that run once, such as the policy copy split + (``scripts/split_v2_policy_copies.py --apply``), given + ``V2DatabaseSettings.connection.url``. Their engine keeps no connection + pool, so no connection outlives its Session, and is disposed of on exit. + """ + with _unpooled_sessions(url, build_v2_session_factory) as sessions: + yield sessions + + +def _build_read_only_session_factory(engine: Engine) -> sessionmaker[Session]: + return build_v2_session_factory(engine.execution_options(postgresql_readonly=True)) + + +@contextmanager +def unpooled_v2_read_only_sessions(url: str | URL) -> Iterator[sessionmaker[Session]]: + """Yield v2 Session factories whose transactions are all READ ONLY. + + For commands that only read, such as the policy copy split's listing: + PostgreSQL refuses any write in their transactions (psycopg's read-only + mode, set through SQLAlchemy's ``postgresql_readonly`` option). Like + ``unpooled_v2_sessions``, the engine keeps no pool. + """ + with _unpooled_sessions(url, _build_read_only_session_factory) as sessions: + yield sessions + + def _discard_inherited_state(current_pid: int) -> None: """Drop pool state inherited through a process fork without touching parent FDs.""" if _engine_state.engine is not None: diff --git a/policyengine_api/data/v2/models/policies.py b/policyengine_api/data/v2/models/policies.py index b2fead152..5b2ecb551 100644 --- a/policyengine_api/data/v2/models/policies.py +++ b/policyengine_api/data/v2/models/policies.py @@ -100,7 +100,8 @@ class Dynamic(TimestampedModel, table=True): A dynamic holds parameter values a simulation applies alongside its policy: every parameter under ``gov.simulation.``, plus the US's - top-level ``simulation.`` (``policyengine_api.dynamic_parameters``). It + top-level ``simulation.`` and the UK's ``gov.dynamic.`` + (``policyengine_api.dynamic_parameters``). It is stored and hashed as a policy is, bound to one catalog version, with no name or description: a user's saved dynamics (``user_dynamics``) name it. Its parameter values are deleted with it; dynamics that users have diff --git a/policyengine_api/data/v2/privileges.py b/policyengine_api/data/v2/privileges.py index c7ddcb0c7..f14e5829f 100644 --- a/policyengine_api/data/v2/privileges.py +++ b/policyengine_api/data/v2/privileges.py @@ -58,6 +58,13 @@ The migration role (``policyengine_v2_migrator``) owns every table, and Supabase's ``postgres`` role administers the project; neither is managed here. +``POLICY_COPY_SPLIT_PRIVILEGES`` declares what the policy copy split command +(``scripts/split_v2_policy_copies.py``) needs, for the temporary role +``policyengine_v2_policy_copy_split`` that an operator creates for one run +(C1 · 49) and drops afterwards. No deploy grants, checks or reports it: it is +not one of the managed roles, and ``docs/migration/stage-10-v2-policies.md`` +gives the statements that create and drop it. + Extra privileges a database holds beyond this manifest are reported, not revoked, with one exception: a privilege a role holds on a whole table that this manifest declares for named columns only is revoked, with the role's @@ -233,6 +240,27 @@ def _run_table( # The Modal workers write results, keyed by run, once each. +# The policy copy split's temporary role (see the module docstring). It locks +# and deletes the old copies (their values go with them by the foreign key's +# cascade), re-points legacy mappings and saved policies, inserts policies, +# dynamics, their values and saved dynamics, and reads the catalog and the +# rows that may name a copy. +POLICY_COPY_SPLIT_ROLE: Final = "policyengine_v2_policy_copy_split" +_READ_UPDATE: Final = frozenset({TablePrivilege.SELECT, TablePrivilege.UPDATE}) +POLICY_COPY_SPLIT_PRIVILEGES: Final[dict[str, frozenset[DeclaredPrivilege]]] = { + "dynamics": READ_INSERT, + "household_jobs": READ, + "legacy_policy_mappings": _READ_UPDATE, + "parameter_values": READ_INSERT, + "parameters": READ, + "policies": READ_WRITE, + "reports": READ, + "simulations": READ, + "tax_benefit_model_versions": READ, + "user_dynamics": READ_INSERT, + "user_policies": _READ_UPDATE, +} + _RESULT = _access(runtime=READ, modal_worker=READ_INSERT) # What a run needs from the Public API's policies, dynamics, households and # catalog. diff --git a/policyengine_api/data/v2/settings.py b/policyengine_api/data/v2/settings.py index 33d8fdfea..9749e2fef 100644 --- a/policyengine_api/data/v2/settings.py +++ b/policyengine_api/data/v2/settings.py @@ -23,6 +23,8 @@ V2_RUNTIME_DATABASE_URL_SECRET_RESOURCE = "V2_RUNTIME_DATABASE_URL_SECRET_RESOURCE" # noqa: S105 # an environment variable name, not a secret V2_MIGRATION_DATABASE_URL = "V2_MIGRATION_DATABASE_URL" V2_DATA_WRITE_DATABASE_URL = "V2_DATA_WRITE_DATABASE_URL" +# The temporary role C1 · 49 creates to run scripts/split_v2_policy_copies.py. +V2_POLICY_COPY_SPLIT_DATABASE_URL = "V2_POLICY_COPY_SPLIT_DATABASE_URL" V2_SUPABASE_PROJECT_REF = "V2_SUPABASE_PROJECT_REF" V2_SUPABASE_ENVIRONMENT = "V2_SUPABASE_ENVIRONMENT" @@ -267,6 +269,22 @@ def load_v2_migration_database_settings( ) +def load_v2_policy_copy_split_database_settings( + environ: Mapping[str, str] | None = None, +) -> V2DatabaseSettings: + """Load the policy copy split command's temporary Postgres identity explicitly. + + The operator creates the role for the run with the grants + ``privileges.POLICY_COPY_SPLIT_PRIVILEGES`` declares, and drops it after. + """ + values = _environment(environ) + return _database_settings( + _required(values, V2_POLICY_COPY_SPLIT_DATABASE_URL), + setting_name=V2_POLICY_COPY_SPLIT_DATABASE_URL, + environ=values, + ) + + def load_v2_data_write_database_settings( environ: Mapping[str, str] | None = None, ) -> V2DatabaseSettings: diff --git a/policyengine_api/dynamic_parameters.py b/policyengine_api/dynamic_parameters.py index 753e53a84..d25611307 100644 --- a/policyengine_api/dynamic_parameters.py +++ b/policyengine_api/dynamic_parameters.py @@ -1,11 +1,13 @@ """Which parameters a dynamic holds, and how a v1 policy's values are split. A dynamic holds the model's assumptions: every parameter under -``gov.simulation.``, in every country, and the US's top-level -``simulation.`` tree (C1 · 35, Q1). These are behavioural responses, model -settings and data assumptions, which a report applies alongside a policy. -Parameters a country package adds later under these prefixes belong to -dynamics with no code change. +``gov.simulation.``, in every country, the US's top-level ``simulation.`` +tree (C1 · 35, Q1) and the UK's ``gov.dynamic.`` (C1 · 46, Q6). These are +behavioural responses, model settings and data assumptions, which a report +applies alongside a policy. Parameters a country package adds later under +these prefixes belong to dynamics with no code change. In policyengine-uk +2.174.1, ``gov.dynamic.`` holds one parameter, +``gov.dynamic.obr_labour_supply_assumptions``, a yes/no switch. The rule is used in three places: @@ -14,8 +16,10 @@ - The copy of each v1 policy into v2 splits the v1 policy's values with ``split_legacy_policy_json``: these values become a dynamic and the rest the policy. -- The one-time migration splits v1 policies, and v2 copies made before the - split existed, with the same functions. +- The one-time migration splits v1 policies with the same functions, and + the policy copy split command + (``policyengine_api.services.v2.policy_copy_split``) splits the v2 copies + stored before a prefix applied to them. The UK renamed ``gov.simulation.labor_supply_responses`` to ``gov.simulation.labour_supply_responses`` on 2026-05-01. Its catalog has @@ -39,8 +43,9 @@ from policyengine_api.supported_countries import SupportedCountryId GOV_SIMULATION_PREFIX: Final = "gov.simulation." +UK_GOV_DYNAMIC_PREFIX: Final = "gov.dynamic." DYNAMIC_PARAMETER_PREFIXES: Final[Mapping[SupportedCountryId, tuple[str, ...]]] = { - "uk": (GOV_SIMULATION_PREFIX,), + "uk": (GOV_SIMULATION_PREFIX, UK_GOV_DYNAMIC_PREFIX), "us": (GOV_SIMULATION_PREFIX, "simulation."), } UK_OLD_LABOUR_SUPPLY_PREFIX: Final = "gov.simulation.labor_supply_responses." diff --git a/policyengine_api/fastapi_routes/v2/dynamics/request_models.py b/policyengine_api/fastapi_routes/v2/dynamics/request_models.py index 310d7e529..c54ea4390 100644 --- a/policyengine_api/fastapi_routes/v2/dynamics/request_models.py +++ b/policyengine_api/fastapi_routes/v2/dynamics/request_models.py @@ -9,6 +9,6 @@ class DynamicCreateRequest(DynamicCreationInput): """Native body containing immutable dynamic content only. A dynamic holds the model's assumptions: parameters under - ``gov.simulation``, and in the US also ``simulation``. Any other - parameter belongs in a policy (``POST /v2/policies``). + ``gov.simulation``, plus ``simulation`` in the US and ``gov.dynamic`` in + the UK. Any other parameter belongs in a policy (``POST /v2/policies``). """ diff --git a/policyengine_api/fastapi_routes/v2/dynamics/routes.py b/policyengine_api/fastapi_routes/v2/dynamics/routes.py index 72d5ff401..6c4d1246f 100644 --- a/policyengine_api/fastapi_routes/v2/dynamics/routes.py +++ b/policyengine_api/fastapi_routes/v2/dynamics/routes.py @@ -149,8 +149,9 @@ def build_v2_dynamic_router(dependencies: NativeRouteDependencies) -> APIRouter: "Binds the model assumptions to the catalog of policyengine_version, " "or of the running PolicyEngine.py version when it names none, and " "stores them once per content hash, as policies are stored. Every " - "parameter must be under gov.simulation, or in the US also " - "simulation; any other answers 422 with code policy_parameters. " + "parameter must be under gov.simulation, or also simulation in the " + "US and gov.dynamic in the UK; any other answers 422 with code " + "policy_parameters. " "Answers 201 when it creates the dynamic and 200 when identical " "content is already stored. There is no list route." ), diff --git a/policyengine_api/fastapi_routes/v2/policies/response_models.py b/policyengine_api/fastapi_routes/v2/policies/response_models.py index 45b88a983..27fcc7cf8 100644 --- a/policyengine_api/fastapi_routes/v2/policies/response_models.py +++ b/policyengine_api/fastapi_routes/v2/policies/response_models.py @@ -127,8 +127,9 @@ class V2DynamicParametersErrorResponse(V2ErrorResponse): """A refused policy that sets parameters only a dynamic may hold. ``dynamic_parameters`` names each of the model's assumptions the policy - sets, sorted: parameters under ``gov.simulation``, and in the US also - ``simulation``. Send them as a dynamic through ``POST /v2/dynamics``. + sets, sorted: parameters under ``gov.simulation``, plus ``simulation`` in + the US and ``gov.dynamic`` in the UK. Send them as a dynamic through + ``POST /v2/dynamics``. """ code: Literal["dynamic_parameters"] = "dynamic_parameters" diff --git a/policyengine_api/fastapi_routes/v2/policies/routes.py b/policyengine_api/fastapi_routes/v2/policies/routes.py index 14d57f665..d1a2f70e1 100644 --- a/policyengine_api/fastapi_routes/v2/policies/routes.py +++ b/policyengine_api/fastapi_routes/v2/policies/routes.py @@ -166,8 +166,9 @@ def build_v2_policy_router( "Binds the policy to the catalog of policyengine_version, or of the " "running PolicyEngine.py version when it names none, and stores it " "once per content hash. A policy may not set the model's " - "assumptions, the parameters under gov.simulation (and in the US " - "simulation): those answer 422 with code dynamic_parameters, and " + "assumptions, the parameters under gov.simulation (plus simulation " + "in the US and gov.dynamic in the UK): those answer 422 with code " + "dynamic_parameters, and " "go in a dynamic through POST /v2/dynamics. Answers 201 when it " "creates the policy and 200 when identical content is already " "stored." diff --git a/policyengine_api/services/v2/dynamics/types.py b/policyengine_api/services/v2/dynamics/types.py index aa173ef7c..68d275c42 100644 --- a/policyengine_api/services/v2/dynamics/types.py +++ b/policyengine_api/services/v2/dynamics/types.py @@ -34,7 +34,8 @@ min_length=1, description=( "The model assumptions the dynamic sets, by catalog parameter ID: " - "parameters under gov.simulation, and in the US also simulation. " + "parameters under gov.simulation, plus simulation in the US and " + "gov.dynamic in the UK. " "At least one: for none, send dynamic_id null." ), ), diff --git a/policyengine_api/services/v2/dynamics/validators.py b/policyengine_api/services/v2/dynamics/validators.py index b6557f298..66c78f37f 100644 --- a/policyengine_api/services/v2/dynamics/validators.py +++ b/policyengine_api/services/v2/dynamics/validators.py @@ -36,8 +36,9 @@ class DynamicSetsPolicyParametersError(ValueError): """Raised when a dynamic sets parameters that are not model assumptions. A dynamic holds only parameters under ``gov.simulation.``, plus the US's - ``simulation.`` (``policyengine_api.dynamic_parameters``); the others - belong in a policy. ``parameter_names`` lists them, sorted. + ``simulation.`` and the UK's ``gov.dynamic.`` + (``policyengine_api.dynamic_parameters``); the others belong in a policy. + ``parameter_names`` lists them, sorted. """ def __init__(self, parameter_names: tuple[str, ...]) -> None: @@ -49,9 +50,9 @@ def __str__(self) -> str: """Say which parameters to send as a policy, and where.""" return ( "A dynamic holds only the model's assumptions, the parameters under " - "gov.simulation (and, in the US, simulation): send the others as a " - "policy through POST /v2/policies. This dynamic sets: " - + ", ".join(self.parameter_names) + "gov.simulation (plus simulation in the US and gov.dynamic in the " + "UK): send the others as a policy through POST /v2/policies. This " + "dynamic sets: " + ", ".join(self.parameter_names) ) diff --git a/policyengine_api/services/v2/policies/services.py b/policyengine_api/services/v2/policies/services.py index 9327d7b85..bbe61a8c3 100644 --- a/policyengine_api/services/v2/policies/services.py +++ b/policyengine_api/services/v2/policies/services.py @@ -255,7 +255,8 @@ def mirror_legacy_policy_in_session( The policy is translated against the running catalog, whichever country package version it was saved under. Its model assumptions (every - ``gov.simulation.`` value, and the US's ``simulation.``) are copied into + ``gov.simulation.`` value, the US's ``simulation.`` and the UK's + ``gov.dynamic.``) are copied into a dynamic, with the UK's old labour-supply spelling rewritten, and the rest into the policy, which is empty when nothing else remains; the mapping names both. A v1 policy that sets no assumptions maps to no diff --git a/policyengine_api/services/v2/policies/validators.py b/policyengine_api/services/v2/policies/validators.py index cb1145832..03ff1d6e4 100644 --- a/policyengine_api/services/v2/policies/validators.py +++ b/policyengine_api/services/v2/policies/validators.py @@ -65,8 +65,9 @@ class PolicySetsDynamicParametersError(ValueError): """Raised when a policy sets parameters only a dynamic may hold. These are the model's assumptions, every parameter under - ``gov.simulation.`` plus the US's ``simulation.`` - (``policyengine_api.dynamic_parameters``), sent as a dynamic through + ``gov.simulation.`` plus the US's ``simulation.`` and the UK's + ``gov.dynamic.`` (``policyengine_api.dynamic_parameters``), sent as a + dynamic through ``POST /v2/dynamics``. ``parameter_names`` lists them, sorted. """ @@ -79,9 +80,9 @@ def __str__(self) -> str: """Say which parameters to send as a dynamic, and where.""" return ( "A policy cannot set the model's assumptions, the parameters under " - "gov.simulation (and, in the US, simulation): send them as a " - "dynamic through POST /v2/dynamics. This policy sets: " - + ", ".join(self.parameter_names) + "gov.simulation (plus simulation in the US and gov.dynamic in the " + "UK): send them as a dynamic through POST /v2/dynamics. This policy " + "sets: " + ", ".join(self.parameter_names) ) diff --git a/policyengine_api/services/v2/policy_copy_split/__init__.py b/policyengine_api/services/v2/policy_copy_split/__init__.py new file mode 100644 index 000000000..963318fea --- /dev/null +++ b/policyengine_api/services/v2/policy_copy_split/__init__.py @@ -0,0 +1 @@ +"""Split stored policies that set model assumptions into a policy and a dynamic.""" diff --git a/policyengine_api/services/v2/policy_copy_split/database_connectors/__init__.py b/policyengine_api/services/v2/policy_copy_split/database_connectors/__init__.py new file mode 100644 index 000000000..45d734f58 --- /dev/null +++ b/policyengine_api/services/v2/policy_copy_split/database_connectors/__init__.py @@ -0,0 +1 @@ +"""Database statements of the policy copy split.""" diff --git a/policyengine_api/services/v2/policy_copy_split/database_connectors/deletes.py b/policyengine_api/services/v2/policy_copy_split/database_connectors/deletes.py new file mode 100644 index 000000000..9592d0647 --- /dev/null +++ b/policyengine_api/services/v2/policy_copy_split/database_connectors/deletes.py @@ -0,0 +1,25 @@ +"""Database deletes used by the policy copy split.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from sqlalchemy import delete +from sqlmodel import col + +from policyengine_api.data.v2.models import Policy + +if TYPE_CHECKING: + from uuid import UUID + + from sqlmodel import Session + + +def delete_policy(session: Session, policy_id: UUID) -> None: + """Delete a policy that nothing names; its values go with it. + + ``parameter_values.policy_id`` cascades, and every other foreign key to + ``policies`` either refuses the delete or sets its column to null, so the + service checks first that nothing else names it. + """ + session.execute(delete(Policy).where(col(Policy.id) == policy_id)) diff --git a/policyengine_api/services/v2/policy_copy_split/database_connectors/reads.py b/policyengine_api/services/v2/policy_copy_split/database_connectors/reads.py new file mode 100644 index 000000000..89c90da4a --- /dev/null +++ b/policyengine_api/services/v2/policy_copy_split/database_connectors/reads.py @@ -0,0 +1,164 @@ +"""Database selections used by the policy copy split.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from sqlalchemy import and_, func, or_ +from sqlmodel import Session, col, select + +from policyengine_api.data.v2.models import ( + HouseholdJob, + LegacyPolicyMapping, + Parameter, + ParameterValue, + Policy, + Report, + Simulation, + UserDynamic, + UserPolicy, +) + +if TYPE_CHECKING: + from collections.abc import Mapping + from uuid import UUID + + from policyengine_api.supported_countries import SupportedCountryId + + +def read_policy_ids_setting_parameters( + session: Session, prefixes_by_country: Mapping[SupportedCountryId, tuple[str, ...]] +) -> list[UUID]: + """Return the stored policies that set a parameter under their country's prefixes. + + Oldest first. Only a policy's own values count, not current law's or a + dynamic's. + """ + sets_prefixed_parameter = or_( + *( + and_( + col(Policy.country_id) == country_id, + or_( + *( + col(Parameter.name).startswith(prefix, autoescape=True) + for prefix in prefixes + ) + ), + ) + for country_id, prefixes in prefixes_by_country.items() + ) + ) + policy_sets_prefixed_parameter = ( + select(ParameterValue.id) + .join(Parameter, col(Parameter.id) == col(ParameterValue.parameter_id)) + .where(col(ParameterValue.policy_id) == col(Policy.id), sets_prefixed_parameter) + .exists() + ) + return list( + session.exec( + select(Policy.id) + .where(policy_sets_prefixed_parameter) + .order_by(col(Policy.created_at), col(Policy.id)) + ).all() + ) + + +def read_policy_for_split( + session: Session, policy_id: UUID, *, lock: bool +) -> Policy | None: + """Return the stored policy, or None. + + With ``lock``, the row is selected FOR UPDATE, so until the transaction + ends no other transaction can add a row that names it (a foreign key's + check locks the row it names) or delete it. + """ + statement = select(Policy).where(Policy.id == policy_id) + if lock: + statement = statement.with_for_update() + return session.exec(statement).one_or_none() + + +def read_mappings_naming_policy( + session: Session, policy_id: UUID, *, lock: bool +) -> list[LegacyPolicyMapping]: + """Return the legacy policy mappings that name the policy, by v1 policy ID. + + With ``lock``, they are selected FOR UPDATE, as the v1-to-v2 copy selects + a mapping it reads. + """ + statement = ( + select(LegacyPolicyMapping) + .where(LegacyPolicyMapping.policy_id == policy_id) + .order_by( + col(LegacyPolicyMapping.country_id), + col(LegacyPolicyMapping.legacy_policy_id), + ) + ) + if lock: + statement = statement.with_for_update() + return list(session.exec(statement).all()) + + +def read_saved_policies_naming_policy( + session: Session, policy_id: UUID, *, lock: bool +) -> list[UserPolicy]: + """Return the saved policies that name the policy, oldest first. + + With ``lock``, they are selected FOR UPDATE. + """ + statement = ( + select(UserPolicy) + .where(UserPolicy.policy_id == policy_id) + .order_by(col(UserPolicy.created_at), col(UserPolicy.id)) + ) + if lock: + statement = statement.with_for_update() + return list(session.exec(statement).all()) + + +def count_rows_naming_policy(session: Session, policy_id: UUID) -> tuple[int, int, int]: + """Return how many simulations, reports and household jobs name the policy.""" + simulations = session.exec( + select(func.count()) + .select_from(Simulation) + .where(col(Simulation.policy_id) == policy_id) + ).one() + reports = session.exec( + select(func.count()) + .select_from(Report) + .where(col(Report.policy_id) == policy_id) + ).one() + household_jobs = session.exec( + select(func.count()) + .select_from(HouseholdJob) + .where(col(HouseholdJob.policy_id) == policy_id) + ).one() + return simulations, reports, household_jobs + + +def read_saved_dynamic_with_name( + session: Session, + *, + user_id: UUID, + country_id: str, + dynamic_id: UUID, + name: str | None, +) -> UserDynamic | None: + """Return the user's oldest saved dynamic of this dynamic with this name, or None. + + A null name matches only a null name. + """ + name_matches = ( + col(UserDynamic.name).is_(None) if name is None else UserDynamic.name == name + ) + return session.exec( + select(UserDynamic) + .where( + UserDynamic.user_id == user_id, + UserDynamic.country_id == country_id, + UserDynamic.dynamic_id == dynamic_id, + name_matches, + ) + .order_by(col(UserDynamic.created_at), col(UserDynamic.id)) + .limit(1) + ).first() diff --git a/policyengine_api/services/v2/policy_copy_split/database_connectors/updates.py b/policyengine_api/services/v2/policy_copy_split/database_connectors/updates.py new file mode 100644 index 000000000..a20b29b44 --- /dev/null +++ b/policyengine_api/services/v2/policy_copy_split/database_connectors/updates.py @@ -0,0 +1,38 @@ +"""Database updates used by the policy copy split.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from sqlalchemy import update +from sqlmodel import col + +from policyengine_api.data.v2.models import LegacyPolicyMapping, UserPolicy +from policyengine_api.data.v2.models.base import utc_now + +if TYPE_CHECKING: + from uuid import UUID + + from sqlmodel import Session + + +def repoint_legacy_policy_mapping( + session: Session, mapping_id: UUID, *, policy_id: UUID, dynamic_id: UUID +) -> None: + """Point a legacy policy mapping at a policy and a dynamic.""" + session.execute( + update(LegacyPolicyMapping) + .where(col(LegacyPolicyMapping.id) == mapping_id) + .values(policy_id=policy_id, dynamic_id=dynamic_id, updated_at=utc_now()) + ) + + +def repoint_saved_policy( + session: Session, saved_policy_id: UUID, *, policy_id: UUID +) -> None: + """Point a saved policy at another policy; its name and description stay.""" + session.execute( + update(UserPolicy) + .where(col(UserPolicy.id) == saved_policy_id) + .values(policy_id=policy_id, updated_at=utc_now()) + ) diff --git a/policyengine_api/services/v2/policy_copy_split/database_session.py b/policyengine_api/services/v2/policy_copy_split/database_session.py new file mode 100644 index 000000000..38ca3b696 --- /dev/null +++ b/policyengine_api/services/v2/policy_copy_split/database_session.py @@ -0,0 +1,36 @@ +"""Database session lifetime management for the policy copy split.""" + +from __future__ import annotations + +from contextlib import contextmanager +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Iterator + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + +class PolicyCopySplitDatabaseSession: + """Open read sessions and transaction-scoped sessions for the split. + + The command builds it on read-only Session factories for its listing, so + the database itself refuses any write there. + """ + + def __init__(self, session_factory: sessionmaker[Session]) -> None: + """Use ``session_factory`` to open every session.""" + self._session_factory = session_factory + + @contextmanager + def read(self) -> Iterator[Session]: + """Yield a session for reads; nothing is committed.""" + with self._session_factory() as session: + yield session + + @contextmanager + def transaction(self) -> Iterator[Session]: + """Yield a session whose transaction commits on exit and rolls back on error.""" + with self._session_factory.begin() as session: + yield session diff --git a/policyengine_api/services/v2/policy_copy_split/services.py b/policyengine_api/services/v2/policy_copy_split/services.py new file mode 100644 index 000000000..e26dcd7ac --- /dev/null +++ b/policyengine_api/services/v2/policy_copy_split/services.py @@ -0,0 +1,489 @@ +"""Split stored policies that set model assumptions into a policy and a dynamic. + +The v1-to-v2 copy kept a v1 policy's model assumptions in its v2 policy until +C1 · 36, and UK ``gov.dynamic.`` values until C1 · 48, and a v1 policy is +never copied again. For each stored policy that sets a model assumption +(``policyengine_api.dynamic_parameters``), the split: + +- finds or creates the policy without the assumptions (empty when the copy + set nothing else) and the dynamic holding them, on the copy's own catalog + version, through C1 · 36's ``create_resolved_policy`` and + ``create_resolved_dynamic``; +- points each legacy mapping that names the copy at them. A mapping that + already names a dynamic gets one dynamic holding that dynamic's values and + the copy's assumptions together; +- points each saved policy that names the copy at the policy, and gives its + owner a saved dynamic with the saved policy's name and no description, + naming the dynamic its v1 policy's mapping now names (or the copy's own + dynamic), unless the owner already has an identical one; +- deletes the copy, its values with it, once nothing names it. A copy that a + simulation, report or household calculation names is kept: their keys + hash the policy, and deleting it would set their policy to null. + +A copy whose mapping's dynamic can't take its assumptions is refused, and +nothing changes for it. ``scripts/split_v2_policy_copies.py`` runs this as a +temporary role (C1 · 49), and D4 · 1's migration reuses +``split_policy_copy_in_session``. The user's decisions are recorded in +``docs/migration/stage-10-v2-policies.md``. +""" + +from __future__ import annotations + +from dataclasses import replace +from typing import TYPE_CHECKING + +from policyengine_api.dynamic_parameters import DYNAMIC_PARAMETER_PREFIXES +from policyengine_api.services.v2.dynamics.database_connectors.reads import ( + read_dynamic_by_content_identity, + read_dynamic_parameter_values, + read_dynamic_row, +) +from policyengine_api.services.v2.policies.database_connectors.reads import ( + read_model_version, + read_parameter_values_with_names, + read_policy_by_content_identity, +) +from policyengine_api.services.v2.policies.transformations import ( + canonicalize_policy, + stored_policy_creation_input, +) +from policyengine_api.services.v2.policy_copy_split.database_connectors.deletes import ( + delete_policy, +) +from policyengine_api.services.v2.policy_copy_split.database_connectors.reads import ( + count_rows_naming_policy, + read_mappings_naming_policy, + read_policy_for_split, + read_policy_ids_setting_parameters, + read_saved_dynamic_with_name, + read_saved_policies_naming_policy, +) +from policyengine_api.services.v2.policy_copy_split.database_connectors.updates import ( + repoint_legacy_policy_mapping, + repoint_saved_policy, +) +from policyengine_api.services.v2.policy_copy_split.transformations import ( + split_stored_policy, +) +from policyengine_api.services.v2.policy_copy_split.types import ( + CopyReferences, + MappingTarget, + PolicyCopyOutcome, + PolicyCopySplit, + PreparedPolicyCopySplit, + RepointedMapping, + RepointedSavedPolicy, + SavedPolicyTarget, + SplitContent, +) +from policyengine_api.services.v2.policy_copy_split.validators import ( + PolicyCopySplitRefusedError, + merge_dynamic_content, + require_stored_row, +) +from policyengine_api.services.v2.user_dynamics.types import UserDynamicCreationInput + +if TYPE_CHECKING: + from collections.abc import Iterator + from uuid import UUID + + from sqlmodel import Session + + from policyengine_api.data.v2.models import LegacyPolicyMapping + from policyengine_api.services.v2.dynamics.types import ( + ResolvedDynamicCreationInput, + ) + from policyengine_api.services.v2.policies.types import ( + ResolvedPolicyCreationInput, + ) + from policyengine_api.services.v2.policy_copy_split.database_session import ( + PolicyCopySplitDatabaseSession, + ) + from policyengine_api.services.v2.policy_copy_split.types import ( + StoredPolicySplit, + ) + + +def read_policy_copy_ids(session: Session) -> tuple[UUID, ...]: + """Return every stored policy that sets a model assumption, oldest first.""" + return tuple( + read_policy_ids_setting_parameters(session, DYNAMIC_PARAMETER_PREFIXES) + ) + + +def _mapping_dynamic( + session: Session, mapping: LegacyPolicyMapping, split: StoredPolicySplit +) -> ResolvedDynamicCreationInput: + """Return the dynamic the mapping will name: the copy's, or merged with its own. + + Raise PolicyCopySplitRefusedError when the mapping's dynamic can't take + the copy's assumptions. + """ + if mapping.dynamic_id is None: + return split.dynamic + existing = require_stored_row( + read_dynamic_row( + session, country_id=mapping.country_id, dynamic_id=mapping.dynamic_id + ), + f"dynamic {mapping.dynamic_id} of legacy policy {mapping.legacy_policy_id}", + ) + model_version = require_stored_row( + read_model_version(session, existing.tax_benefit_model_version_id), + f"model version of dynamic {existing.id}", + ) + return merge_dynamic_content( + stored_policy_creation_input( + existing, model_version, read_dynamic_parameter_values(session, existing.id) + ), + split.dynamic, + ) + + +def _prepare( + session: Session, policy_id: UUID, *, lock: bool +) -> PreparedPolicyCopySplit | None: + """Read what the split of one copy needs, locking it first with ``lock``. + + Return None when the policy is no longer stored or sets no model + assumption. + """ + policy = read_policy_for_split(session, policy_id, lock=lock) + if policy is None: + return None + model_version = require_stored_row( + read_model_version(session, policy.tax_benefit_model_version_id), + f"model version of policy {policy.id}", + ) + split = split_stored_policy( + policy, model_version, read_parameter_values_with_names(session, [policy.id]) + ) + if split is None: + return None + simulations, reports, household_jobs = count_rows_naming_policy(session, policy.id) + prepared = PreparedPolicyCopySplit( + policy_id=policy.id, + country_id=policy.country_id, + policyengine_version=model_version.version, + split=split, + mapping_targets=(), + saved_policy_targets=(), + references=CopyReferences( + simulations=simulations, reports=reports, household_jobs=household_jobs + ), + refusal_reason=None, + ) + mappings = read_mappings_naming_policy(session, policy.id, lock=lock) + try: + mapping_targets = tuple( + MappingTarget( + mapping_id=mapping.id, + country_id=mapping.country_id, + legacy_policy_id=mapping.legacy_policy_id, + previous_dynamic_id=mapping.dynamic_id, + dynamic=_mapping_dynamic(session, mapping, split), + ) + for mapping in mappings + ) + except PolicyCopySplitRefusedError as refusal: + return replace(prepared, refusal_reason=refusal.reason) + dynamics_by_legacy_policy = { + (target.country_id, target.legacy_policy_id): target.dynamic + for target in mapping_targets + } + saved_policy_targets = tuple( + SavedPolicyTarget( + user_policy_id=saved_policy.id, + user_id=saved_policy.user_id, + country_id=saved_policy.country_id, + name=saved_policy.name, + dynamic=( + split.dynamic + if saved_policy.legacy_policy_id is None + else dynamics_by_legacy_policy.get( + (saved_policy.country_id, saved_policy.legacy_policy_id), + split.dynamic, + ) + ), + ) + for saved_policy in read_saved_policies_naming_policy( + session, policy.id, lock=lock + ) + ) + return replace( + prepared, + mapping_targets=mapping_targets, + saved_policy_targets=saved_policy_targets, + ) + + +def _content_hash(content: ResolvedPolicyCreationInput) -> str: + return canonicalize_policy(content).content_hash + + +def _refused(prepared: PreparedPolicyCopySplit, *, applied: bool) -> PolicyCopySplit: + return PolicyCopySplit( + old_policy_id=prepared.policy_id, + country_id=prepared.country_id, + policyengine_version=prepared.policyengine_version, + applied=applied, + outcome=PolicyCopyOutcome.REFUSED, + policy=None, + dynamic=None, + mappings=(), + saved_policies=(), + references=prepared.references, + refusal_reason=prepared.refusal_reason, + ) + + +def _remaining_outcome(prepared: PreparedPolicyCopySplit) -> PolicyCopyOutcome: + """Return the copy's outcome: deleted, unless a simulation or report names it.""" + if prepared.references.total: + return PolicyCopyOutcome.KEPT + return PolicyCopyOutcome.DELETED + + +def plan_policy_copy_split(session: Session, policy_id: UUID) -> PolicyCopySplit | None: + """Return what splitting one copy would change, reading only. + + Rows that don't exist yet have no ID. Return None when the policy is no + longer stored or sets no model assumption. + """ + prepared = _prepare(session, policy_id, lock=False) + if prepared is None: + return None + if prepared.refusal_reason is not None: + return _refused(prepared, applied=False) + + listed_dynamics: dict[str, SplitContent] = {} + + def listed_dynamic(content: ResolvedDynamicCreationInput) -> SplitContent: + canonical = canonicalize_policy(content) + content_hash = canonical.content_hash + if content_hash not in listed_dynamics: + stored = read_dynamic_by_content_identity( + session, + canonicalization_version=canonical.version, + content_hash=content_hash, + ) + listed_dynamics[content_hash] = SplitContent( + id=None if stored is None else stored.id, + content_hash=content_hash, + created=stored is None, + ) + return listed_dynamics[content_hash] + + policy_content = canonicalize_policy(prepared.split.policy) + stored_policy = read_policy_by_content_identity( + session, + canonicalization_version=policy_content.version, + content_hash=policy_content.content_hash, + ) + plain_dynamic = listed_dynamic(prepared.split.dynamic) + mappings = tuple( + RepointedMapping( + country_id=target.country_id, + legacy_policy_id=target.legacy_policy_id, + previous_dynamic_id=target.previous_dynamic_id, + dynamic=listed_dynamic(target.dynamic), + ) + for target in prepared.mapping_targets + ) + saved_policies = [] + planned_saved_dynamics: set[tuple[UUID, str, str, str | None]] = set() + for target in prepared.saved_policy_targets: + dynamic = listed_dynamic(target.dynamic) + existing = ( + None + if dynamic.id is None + else read_saved_dynamic_with_name( + session, + user_id=target.user_id, + country_id=target.country_id, + dynamic_id=dynamic.id, + name=target.name, + ) + ) + identity = ( + target.user_id, + target.country_id, + dynamic.content_hash, + target.name, + ) + saved_policies.append( + RepointedSavedPolicy( + user_policy_id=target.user_policy_id, + dynamic=dynamic, + saved_dynamic_id=None if existing is None else existing.id, + saved_dynamic_created=existing is None + and identity not in planned_saved_dynamics, + ) + ) + planned_saved_dynamics.add(identity) + return PolicyCopySplit( + old_policy_id=prepared.policy_id, + country_id=prepared.country_id, + policyengine_version=prepared.policyengine_version, + applied=False, + outcome=_remaining_outcome(prepared), + policy=SplitContent( + id=None if stored_policy is None else stored_policy.id, + content_hash=policy_content.content_hash, + created=stored_policy is None, + ), + dynamic=plain_dynamic, + mappings=mappings, + saved_policies=tuple(saved_policies), + references=prepared.references, + refusal_reason=None, + ) + + +def split_policy_copy_in_session( + session: Session, policy_id: UUID +) -> PolicyCopySplit | None: + """Split one copy in the caller's transaction, which commits it. + + The copy is locked first, so nothing can start naming it before the + transaction ends. Return None when the policy is no longer stored or sets + no model assumption. Raise PolicyCopyIntegrityError, and the policy and + dynamic creation errors, for stored rows that contradict their keys. + """ + from policyengine_api.services.v2.dynamics.services import ( + create_resolved_dynamic, + ) + from policyengine_api.services.v2.policies.services import ( + create_resolved_policy, + ) + from policyengine_api.services.v2.user_dynamics.services import ( + create_user_dynamic_in_session, + ) + + prepared = _prepare(session, policy_id, lock=True) + if prepared is None: + return None + if prepared.refusal_reason is not None: + return _refused(prepared, applied=True) + + stored_dynamics: dict[str, SplitContent] = {} + + def stored_dynamic(content: ResolvedDynamicCreationInput) -> SplitContent: + content_hash = _content_hash(content) + if content_hash not in stored_dynamics: + result = create_resolved_dynamic(session, content) + stored_dynamics[content_hash] = SplitContent( + id=result.dynamic_id, content_hash=content_hash, created=result.created + ) + return stored_dynamics[content_hash] + + policy_result = create_resolved_policy(session, prepared.split.policy) + plain_dynamic = stored_dynamic(prepared.split.dynamic) + mappings = [] + for mapping_target in prepared.mapping_targets: + dynamic = stored_dynamic(mapping_target.dynamic) + repoint_legacy_policy_mapping( + session, + mapping_target.mapping_id, + policy_id=policy_result.policy_id, + dynamic_id=require_stored_row(dynamic.id, "a stored dynamic's ID"), + ) + mappings.append( + RepointedMapping( + country_id=mapping_target.country_id, + legacy_policy_id=mapping_target.legacy_policy_id, + previous_dynamic_id=mapping_target.previous_dynamic_id, + dynamic=dynamic, + ) + ) + saved_policies = [] + for saved_policy_target in prepared.saved_policy_targets: + dynamic = stored_dynamic(saved_policy_target.dynamic) + dynamic_id = require_stored_row(dynamic.id, "a stored dynamic's ID") + repoint_saved_policy( + session, + saved_policy_target.user_policy_id, + policy_id=policy_result.policy_id, + ) + existing = read_saved_dynamic_with_name( + session, + user_id=saved_policy_target.user_id, + country_id=saved_policy_target.country_id, + dynamic_id=dynamic_id, + name=saved_policy_target.name, + ) + saved_dynamic_id = ( + existing.id + if existing is not None + else create_user_dynamic_in_session( + session, + UserDynamicCreationInput.model_validate( + { + "country_id": saved_policy_target.country_id, + "user_id": saved_policy_target.user_id, + "dynamic_id": dynamic_id, + "name": saved_policy_target.name, + "description": None, + } + ), + ).id + ) + saved_policies.append( + RepointedSavedPolicy( + user_policy_id=saved_policy_target.user_policy_id, + dynamic=dynamic, + saved_dynamic_id=saved_dynamic_id, + saved_dynamic_created=existing is None, + ) + ) + outcome = _remaining_outcome(prepared) + if outcome is PolicyCopyOutcome.DELETED: + delete_policy(session, prepared.policy_id) + return PolicyCopySplit( + old_policy_id=prepared.policy_id, + country_id=prepared.country_id, + policyengine_version=prepared.policyengine_version, + applied=True, + outcome=outcome, + policy=SplitContent( + id=policy_result.policy_id, + content_hash=_content_hash(prepared.split.policy), + created=policy_result.created, + ), + dynamic=plain_dynamic, + mappings=tuple(mappings), + saved_policies=tuple(saved_policies), + references=prepared.references, + refusal_reason=None, + ) + + +class V2PolicyCopySplitService: + """List or apply the split of every stored copy, one transaction per copy.""" + + def __init__(self, database_session: PolicyCopySplitDatabaseSession) -> None: + """Open sessions through ``database_session``.""" + self._database_session = database_session + + def list_policy_copy_splits(self) -> tuple[PolicyCopySplit, ...]: + """Return what splitting every copy would change, in one read session.""" + with self._database_session.read() as session: + planned = ( + plan_policy_copy_split(session, policy_id) + for policy_id in read_policy_copy_ids(session) + ) + return tuple(split for split in planned if split is not None) + + def split_policy_copies(self) -> Iterator[PolicyCopySplit]: + """Split each copy in its own transaction, yielding each as it commits.""" + with self._database_session.read() as session: + policy_ids = read_policy_copy_ids(session) + for policy_id in policy_ids: + with self._database_session.transaction() as session: + split = split_policy_copy_in_session(session, policy_id) + if split is not None: + yield split + + def count_policy_copies(self) -> int: + """Return how many stored policies still set a model assumption.""" + with self._database_session.read() as session: + return len(read_policy_copy_ids(session)) diff --git a/policyengine_api/services/v2/policy_copy_split/transformations.py b/policyengine_api/services/v2/policy_copy_split/transformations.py new file mode 100644 index 000000000..2e835871a --- /dev/null +++ b/policyengine_api/services/v2/policy_copy_split/transformations.py @@ -0,0 +1,64 @@ +"""Pure representation transformations for the policy copy split. + +A stored copy is split on its own catalog version: its values keep their +parameter IDs, values and dates, and only move to a policy or a dynamic by +``policyengine_api.dynamic_parameters``. Its content hash is a policy's +(``policies.transformations.canonicalize_policy``). +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from policyengine_api.dynamic_parameters import is_dynamic_parameter +from policyengine_api.services.v2.dynamics.types import ResolvedDynamicCreationInput +from policyengine_api.services.v2.policies.transformations import ( + stored_policy_creation_input, +) +from policyengine_api.services.v2.policies.types import ResolvedPolicyCreationInput +from policyengine_api.services.v2.policy_copy_split.types import StoredPolicySplit + +if TYPE_CHECKING: + from collections.abc import Sequence + + from policyengine_api.data.v2.models import ( + ParameterValue, + Policy, + TaxBenefitModelVersion, + ) + + +def split_stored_policy( + policy: Policy, + model_version: TaxBenefitModelVersion, + values: Sequence[tuple[ParameterValue, str]], +) -> StoredPolicySplit | None: + """Split a stored policy's values, each with its parameter's name, in two. + + The model assumptions go into the dynamic and the rest into the policy, + which is empty when the copy set only assumptions. Both are bound to the + copy's own model and catalog version. Return None when the policy sets + no model assumption. + """ + whole = stored_policy_creation_input( + policy, model_version, [value for value, _parameter_name in values] + ) + names_by_parameter_id = {value.parameter_id: name for value, name in values} + policy_values = [] + dynamic_values = [] + for value in whole.parameter_values: + parameter_name = names_by_parameter_id[value.parameter_id] + if is_dynamic_parameter(whole.country_id, parameter_name): + dynamic_values.append(value) + else: + policy_values.append(value) + if not dynamic_values: + return None + return StoredPolicySplit( + policy=ResolvedPolicyCreationInput.model_validate( + {**dict(whole), "parameter_values": policy_values} + ), + dynamic=ResolvedDynamicCreationInput.model_validate( + {**dict(whole), "parameter_values": dynamic_values} + ), + ) diff --git a/policyengine_api/services/v2/policy_copy_split/types.py b/policyengine_api/services/v2/policy_copy_split/types.py new file mode 100644 index 000000000..ed9e4585e --- /dev/null +++ b/policyengine_api/services/v2/policy_copy_split/types.py @@ -0,0 +1,183 @@ +"""Framework-independent data exchanged by the layers of the policy copy split. + +A policy copy here is a stored v2 policy that sets a model assumption +(``policyengine_api.dynamic_parameters``): the v1-to-v2 copy made such +policies before it split model assumptions off (C1 · 36), and for UK +``gov.dynamic.`` values until that prefix joined (C1 · 48). +""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import StrEnum +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from uuid import UUID + + from policyengine_api.services.v2.dynamics.types import ( + ResolvedDynamicCreationInput, + ) + from policyengine_api.services.v2.policies.types import ( + ResolvedPolicyCreationInput, + ) + + +class PolicyCopyOutcome(StrEnum): + """What happens to the old copy once its split is stored.""" + + # Nothing names it any more, so it is deleted with its values. + DELETED = "deleted" + # A simulation, report or household calculation still names it, so it is + # kept, although its legacy mappings and saved policies are re-pointed. + KEPT = "kept" + # It can't be split as decided, so nothing changes for it. + REFUSED = "refused" + + +class PolicyCopyRefusalReason(StrEnum): + """Why a copy is refused: a mapping's dynamic can't take its assumptions.""" + + # The mapping's dynamic sets one of the copy's assumptions, for the same + # start date, to another value or end date. + CONFLICTING_DYNAMIC_VALUES = "conflicting_dynamic_values" + # The mapping's dynamic is bound to another model or catalog version. + DYNAMIC_ON_ANOTHER_CATALOG = "dynamic_on_another_catalog" + # Together they hold more values than a dynamic may. + TOO_MANY_VALUES = "too_many_values" + + +@dataclass(frozen=True) +class StoredPolicySplit: + """A stored copy's values, split on its own catalog version. + + ``policy`` holds the values that aren't model assumptions, and may be + empty; ``dynamic`` holds the model assumptions. + """ + + policy: ResolvedPolicyCreationInput + dynamic: ResolvedDynamicCreationInput + + +@dataclass(frozen=True) +class MappingTarget: + """A legacy mapping naming the copy, and the dynamic it will name. + + ``previous_dynamic_id`` is read before the mapping changes. + """ + + mapping_id: UUID + country_id: str + legacy_policy_id: int + previous_dynamic_id: UUID | None + dynamic: ResolvedDynamicCreationInput + + +@dataclass(frozen=True) +class SavedPolicyTarget: + """A saved policy naming the copy, and the dynamic its saved dynamic will name.""" + + user_policy_id: UUID + user_id: UUID + country_id: str + name: str | None + dynamic: ResolvedDynamicCreationInput + + +@dataclass(frozen=True) +class PreparedPolicyCopySplit: + """Everything the split of one copy reads before it writes anything. + + ``refusal_reason`` is set when the copy can't be split; the targets are + then empty. + """ + + policy_id: UUID + country_id: str + policyengine_version: str + split: StoredPolicySplit + mapping_targets: tuple[MappingTarget, ...] + saved_policy_targets: tuple[SavedPolicyTarget, ...] + references: CopyReferences + refusal_reason: PolicyCopyRefusalReason | None + + +@dataclass(frozen=True) +class SplitContent: + """A policy or dynamic the split points a row at, found by its content hash. + + ``id`` is the stored row's ID. It is None only in a read-only listing, + for a row that doesn't exist yet. ``created`` says whether this run + created the row, or in a listing would. + """ + + id: UUID | None + content_hash: str + created: bool + + +@dataclass(frozen=True) +class CopyReferences: + """How many simulations, reports and household calculations name a copy.""" + + simulations: int + reports: int + household_jobs: int + + @property + def total(self) -> int: + """All three counts together; any of them keeps the copy.""" + return self.simulations + self.reports + self.household_jobs + + +@dataclass(frozen=True) +class RepointedMapping: + """A legacy policy mapping moved from the old copy to its split. + + ``previous_dynamic_id`` is the dynamic the mapping named before; when it + named one, ``dynamic`` holds that dynamic's values and the copy's model + assumptions together. + """ + + country_id: str + legacy_policy_id: int + previous_dynamic_id: UUID | None + dynamic: SplitContent + + +@dataclass(frozen=True) +class RepointedSavedPolicy: + """A saved policy moved from the old copy to its split, and its saved dynamic. + + The saved dynamic belongs to the saved policy's owner, names ``dynamic`` + and takes the saved policy's name. ``saved_dynamic_created`` is false when + the owner already had an identical one, which is then reused. + ``saved_dynamic_id`` is None only in a listing, for one that doesn't + exist yet. + """ + + user_policy_id: UUID + dynamic: SplitContent + saved_dynamic_id: UUID | None + saved_dynamic_created: bool + + +@dataclass(frozen=True) +class PolicyCopySplit: + """What the split did to one stored copy, or in a listing would do. + + ``applied`` is false for a read-only listing. ``policy`` and ``dynamic`` + are the plain split of the copy, None only when it is refused. + """ + + old_policy_id: UUID + country_id: str + policyengine_version: str + applied: bool + outcome: PolicyCopyOutcome + policy: SplitContent | None + dynamic: SplitContent | None + mappings: tuple[RepointedMapping, ...] + saved_policies: tuple[RepointedSavedPolicy, ...] + references: CopyReferences + refusal_reason: PolicyCopyRefusalReason | None diff --git a/policyengine_api/services/v2/policy_copy_split/validators.py b/policyengine_api/services/v2/policy_copy_split/validators.py new file mode 100644 index 000000000..e4e48b88c --- /dev/null +++ b/policyengine_api/services/v2/policy_copy_split/validators.py @@ -0,0 +1,112 @@ +"""Database-independent validation for the policy copy split.""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, TypeVar + +from policyengine_api.services.v2.dynamics.types import ResolvedDynamicCreationInput +from policyengine_api.services.v2.policies.validators import ( + MAXIMUM_POLICY_PARAMETER_VALUES, +) +from policyengine_api.services.v2.policy_copy_split.types import ( + PolicyCopyRefusalReason, +) + +if TYPE_CHECKING: + from datetime import datetime + from uuid import UUID + + from policyengine_api.services.v2.policies.types import ( + PolicyParameterValueInput, + ResolvedPolicyCreationInput, + ) + +StoredRow = TypeVar("StoredRow") + + +class PolicyCopySplitRefusedError(ValueError): + """Raised when a copy can't be split as decided; nothing changes for it. + + ``reason`` says why, as the command reports it. + """ + + def __init__(self, reason: PolicyCopyRefusalReason) -> None: + """Keep the reason, which the command's report names.""" + self.reason = reason + super().__init__(reason) + + def __str__(self) -> str: + """Name the reason.""" + return f"the policy copy can't be split: {self.reason.value}" + + +class PolicyCopyIntegrityError(RuntimeError): + """Raised when a row the split reads is missing although a key requires it.""" + + +def require_stored_row(row: StoredRow | None, description: str) -> StoredRow: + """Return the row, or raise PolicyCopyIntegrityError naming what is missing.""" + if row is None: + msg = f"{description} is missing although a foreign key requires it" + raise PolicyCopyIntegrityError(msg) + return row + + +def _same_value( + earlier: PolicyParameterValueInput, later: PolicyParameterValueInput +) -> bool: + """Return whether two values for one parameter and start date are identical. + + The JSON values are compared as JSON, so ``true`` differs from ``1``, which + Python would count as equal. + """ + return earlier.end_date == later.end_date and json.dumps( + earlier.value, sort_keys=True + ) == json.dumps(later.value, sort_keys=True) + + +def merge_dynamic_content( + existing: ResolvedPolicyCreationInput, + split_off: ResolvedDynamicCreationInput, +) -> ResolvedDynamicCreationInput: + """Return one dynamic holding a mapping's dynamic and a copy's assumptions. + + ``existing`` is the dynamic a legacy mapping already names, rebuilt from + its stored rows, and ``split_off`` the model assumptions split from the + copy the mapping names. A value both set identically for the same + parameter and start date is kept once. Raise PolicyCopySplitRefusedError + when they are bound to different models or catalog versions, set one + parameter for the same start date differently, or hold more values + together than a dynamic may. + """ + if ( + existing.country_id, + existing.tax_benefit_model_id, + existing.tax_benefit_model_version_id, + ) != ( + split_off.country_id, + split_off.tax_benefit_model_id, + split_off.tax_benefit_model_version_id, + ): + raise PolicyCopySplitRefusedError( + PolicyCopyRefusalReason.DYNAMIC_ON_ANOTHER_CATALOG + ) + merged: dict[tuple[UUID, datetime], PolicyParameterValueInput] = { + (value.parameter_id, value.start_date): value + for value in existing.parameter_values + } + for value in split_off.parameter_values: + identity = (value.parameter_id, value.start_date) + earlier = merged.get(identity) + if earlier is None: + merged[identity] = value + elif not _same_value(earlier, value): + raise PolicyCopySplitRefusedError( + PolicyCopyRefusalReason.CONFLICTING_DYNAMIC_VALUES + ) + if len(merged) > MAXIMUM_POLICY_PARAMETER_VALUES: + raise PolicyCopySplitRefusedError(PolicyCopyRefusalReason.TOO_MANY_VALUES) + return ResolvedDynamicCreationInput.model_validate( + {**dict(split_off), "parameter_values": list(merged.values())} + ) diff --git a/pyproject.toml b/pyproject.toml index 04bc603f7..6fa965261 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -415,6 +415,8 @@ banned-module-level-imports = [ "policyengine_api.services.v2.metadata.services", "policyengine_api.services.v2.policies.database_session", "policyengine_api.services.v2.policies.services", + "policyengine_api.services.v2.policy_copy_split.database_session", + "policyengine_api.services.v2.policy_copy_split.services", "policyengine_api.services.v2.report_run_records.database_session", "policyengine_api.services.v2.report_run_records.services", "policyengine_api.services.v2.simulation_service.services", diff --git a/scripts/split_v2_policy_copies.py b/scripts/split_v2_policy_copies.py new file mode 100755 index 000000000..433734808 --- /dev/null +++ b/scripts/split_v2_policy_copies.py @@ -0,0 +1,252 @@ +#!/usr/bin/env python3 +"""Split each stored v2 policy that sets a model assumption into a policy and dynamic. + +Usage:: + + split_v2_policy_copies.py # list what would change; change nothing + split_v2_policy_copies.py --apply # make the changes + +Without ``--apply`` it reads in one READ ONLY transaction and lists, for each +stored policy that sets a model assumption (``gov.simulation.``, US +``simulation.``, UK ``gov.dynamic.``), the policy and dynamic it would split +into, the legacy mappings and saved policies it would re-point, the saved +dynamics it would add, and whether the old copy would be deleted, kept or +refused. With ``--apply`` it makes those changes, one transaction per copy, +and reports the IDs of every row it points at or creates. +``policyengine_api.services.v2.policy_copy_split.services`` describes the +split. + +It exits with 0 when, afterwards, no stored policy sets a model assumption +(for the listing: when every copy would be deleted), and with 1 otherwise, +such as when a copy is kept because a simulation, report or household +calculation names it, or refused. Any other failure, such as missing +settings or an unreachable database, raises, so Python prints its traceback +and also exits with 1. + +It connects as the temporary role ``policyengine_v2_policy_copy_split``, +which the operator creates with the grants in +``docs/migration/stage-10-v2-policies.md`` and drops afterwards: +``V2_POLICY_COPY_SPLIT_DATABASE_URL`` names it, and ``V2_SUPABASE_PROJECT_REF`` +and ``V2_SUPABASE_ENVIRONMENT`` the Supabase project the URL must name. +""" + +from __future__ import annotations + +import argparse +from contextlib import contextmanager +from typing import TYPE_CHECKING, Protocol + +from policyengine_api.data.v2.settings import ( + load_v2_policy_copy_split_database_settings, +) +from policyengine_api.services.v2.policy_copy_split.types import ( + PolicyCopyOutcome, +) + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Iterator, Sequence + from contextlib import AbstractContextManager + + from policyengine_api.services.v2.policy_copy_split.types import ( + CopyReferences, + PolicyCopySplit, + RepointedSavedPolicy, + SplitContent, + ) + + +class PolicyCopySplitter(Protocol): + """The split service operations this command calls.""" + + def list_policy_copy_splits(self) -> tuple[PolicyCopySplit, ...]: + """Return what splitting every copy would change.""" + ... + + def split_policy_copies(self) -> Iterator[PolicyCopySplit]: + """Split each copy in its own transaction, yielding each as it commits.""" + ... + + def count_policy_copies(self) -> int: + """Return how many stored policies still set a model assumption.""" + ... + + +@contextmanager +def splitter_on_temporary_role(*, writable: bool) -> Iterator[PolicyCopySplitter]: + """Yield the split service on the temporary role's database connection. + + Without ``writable``, every transaction is READ ONLY, so the database + refuses any write. Raise V2ConfigurationError for missing or invalid + settings. + """ + settings = load_v2_policy_copy_split_database_settings() + # These modules are imported only when the command runs, as they need the + # connection. + from policyengine_api.data.v2.database import ( + unpooled_v2_read_only_sessions, + unpooled_v2_sessions, + ) + from policyengine_api.services.v2.policy_copy_split.database_session import ( + PolicyCopySplitDatabaseSession, + ) + from policyengine_api.services.v2.policy_copy_split.services import ( + V2PolicyCopySplitService, + ) + + open_sessions = unpooled_v2_sessions if writable else unpooled_v2_read_only_sessions + with open_sessions(settings.connection.url) as session_factory: + yield V2PolicyCopySplitService(PolicyCopySplitDatabaseSession(session_factory)) + + +def _parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description=( + "Split every stored v2 policy that sets a model assumption into a " + "policy and a dynamic. Without --apply, only list what would change." + ) + ) + parser.add_argument( + "--apply", + action="store_true", + help="make the changes; without it, nothing is changed", + ) + return parser + + +def _plural(count: int, singular: str, plural: str | None = None) -> str: + return f"{count} {singular if count == 1 else plural or singular + 's'}" + + +def _content(kind: str, content: SplitContent) -> str: + """Name a policy or dynamic: its ID, or its content hash if it is still to come.""" + if content.id is None: + return f"{kind}: would be created (content hash {content.content_hash[:12]})" + return f"{kind} {content.id} ({'created' if content.created else 'already stored'})" + + +def _dynamic_name(content: SplitContent) -> str: + if content.id is None: + return f"a new dynamic (content hash {content.content_hash[:12]})" + return f"dynamic {content.id}" + + +def _references(references: CopyReferences) -> str: + return ( + f"named by {_plural(references.simulations, 'simulation')}, " + f"{_plural(references.reports, 'report')} and " + f"{_plural(references.household_jobs, 'household calculation')}" + ) + + +def _outcome(split: PolicyCopySplit) -> str: + if split.outcome is PolicyCopyOutcome.REFUSED: + refused = "refused" if split.applied else "would be refused" + reason = split.refusal_reason.value if split.refusal_reason else "unknown" + return f"{refused} ({reason}); nothing changes for it" + if split.outcome is PolicyCopyOutcome.KEPT: + kept = "kept" if split.applied else "would be kept" + return f"{kept}: {_references(split.references)}" + return "deleted" if split.applied else "would be deleted" + + +def _describe(split: PolicyCopySplit) -> list[str]: + """Return the report on one copy: one heading, then one entry per change.""" + report = [ + f"Policy copy {split.old_policy_id} ({split.country_id}, catalog version " + f"{split.policyengine_version}): {_outcome(split)}" + ] + if split.policy is None or split.dynamic is None: + return report + policy_name = ( + "the new policy" if split.policy.id is None else f"policy {split.policy.id}" + ) + report += [ + " " + _content("policy", split.policy), + " " + _content("dynamic", split.dynamic), + ] + now = "now" if split.applied else "would point at" + for mapping in split.mappings: + report.append( + f" legacy policy {mapping.country_id} {mapping.legacy_policy_id}: " + f"{now} {policy_name} and {_dynamic_name(mapping.dynamic)} " + f"(was dynamic {mapping.previous_dynamic_id or 'none'})" + ) + for saved_policy in split.saved_policies: + report.append( + f" saved policy {saved_policy.user_policy_id}: {now} {policy_name}; " + f"{_saved_dynamic(saved_policy)} for {_dynamic_name(saved_policy.dynamic)}" + ) + return report + + +def _saved_dynamic(saved_policy: RepointedSavedPolicy) -> str: + """Name the saved dynamic a saved policy's owner gets, or would get.""" + if saved_policy.saved_dynamic_id is None: + if saved_policy.saved_dynamic_created: + return "saved dynamic: would be created" + return "saved dynamic: an identical one listed above would be reused" + if saved_policy.saved_dynamic_created: + return f"saved dynamic {saved_policy.saved_dynamic_id} (created)" + return f"saved dynamic {saved_policy.saved_dynamic_id} (already saved)" + + +def _counts(splits: Iterable[PolicyCopySplit]) -> dict[PolicyCopyOutcome, int]: + counts = dict.fromkeys(PolicyCopyOutcome, 0) + for split in splits: + counts[split.outcome] += 1 + return counts + + +def _list(splitter: PolicyCopySplitter) -> int: + print("Read-only listing: nothing was changed. Run with --apply to change it.") + splits = splitter.list_policy_copy_splits() + for split in splits: + print("\n".join(_describe(split))) + if not splits: + print("No stored policy sets a model assumption.") + return 0 + counts = _counts(splits) + print( + f"{_plural(len(splits), 'policy copy', 'policy copies')} " + f"{'sets' if len(splits) == 1 else 'set'} a model assumption: " + f"{counts[PolicyCopyOutcome.DELETED]} would be deleted, " + f"{counts[PolicyCopyOutcome.KEPT]} would be kept and " + f"{counts[PolicyCopyOutcome.REFUSED]} would be refused." + ) + return 0 if len(splits) == counts[PolicyCopyOutcome.DELETED] else 1 + + +def _apply(splitter: PolicyCopySplitter) -> int: + print("Applying: each policy copy is changed in its own transaction.") + splits = [] + for split in splitter.split_policy_copies(): + splits.append(split) + print("\n".join(_describe(split)), flush=True) + remaining = splitter.count_policy_copies() + counts = _counts(splits) + print( + f"{_plural(len(splits), 'policy copy', 'policy copies')}: " + f"{counts[PolicyCopyOutcome.DELETED]} deleted, " + f"{counts[PolicyCopyOutcome.KEPT]} kept and " + f"{counts[PolicyCopyOutcome.REFUSED]} refused. " + f"{_plural(remaining, 'stored policy', 'stored policies')} still " + f"{'sets' if remaining == 1 else 'set'} a model assumption." + ) + return 0 if remaining == 0 else 1 + + +def main( + argv: Sequence[str] | None = None, + *, + splitter_factory: Callable[..., AbstractContextManager[PolicyCopySplitter]] = ( + splitter_on_temporary_role + ), +) -> int: + """List or apply the split; return 0 when no copy is left, and 1 otherwise.""" + arguments = _parser().parse_args(argv) + with splitter_factory(writable=arguments.apply) as splitter: + return _apply(splitter) if arguments.apply else _list(splitter) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/integration/test_v2_policy_copy_splits.py b/tests/integration/test_v2_policy_copy_splits.py index c369d6782..bd5e9b794 100644 --- a/tests/integration/test_v2_policy_copy_splits.py +++ b/tests/integration/test_v2_policy_copy_splits.py @@ -15,19 +15,6 @@ from uuid import UUID, uuid4 import pytest -from policyengine_api.services.v2.policy_copy_splits.database_session import ( - PolicyCopySplitDatabaseSession, -) -from policyengine_api.services.v2.policy_copy_splits.services import ( - V2PolicyCopySplitService, - read_policy_copy_ids, - split_policy_copy_in_session, -) -from policyengine_api.services.v2.policy_copy_splits.types import ( - PolicyCopyOutcome, - PolicyCopyRefusalReason, - PolicyCopySplit, -) from sqlalchemy import create_engine, delete, or_ from sqlalchemy.orm import sessionmaker from sqlalchemy.pool import NullPool @@ -58,6 +45,19 @@ from policyengine_api.services.v2.dynamics.types import ResolvedDynamicCreationInput from policyengine_api.services.v2.policies.services import create_resolved_policy from policyengine_api.services.v2.policies.types import ResolvedPolicyCreationInput +from policyengine_api.services.v2.policy_copy_split.database_session import ( + PolicyCopySplitDatabaseSession, +) +from policyengine_api.services.v2.policy_copy_split.services import ( + V2PolicyCopySplitService, + read_policy_copy_ids, + split_policy_copy_in_session, +) +from policyengine_api.services.v2.policy_copy_split.types import ( + PolicyCopyOutcome, + PolicyCopyRefusalReason, + PolicyCopySplit, +) if TYPE_CHECKING: from collections.abc import Iterator @@ -142,7 +142,7 @@ def content(self, *values: dict[str, object]) -> dict[str, object]: def _store_catalog(owner_engine: Engine, country_id: str, names: list[str]) -> Scenario: with Session(owner_engine) as session: - model = TaxBenefitModel(name=f"policyengine-{country_id}-split-{uuid4().hex}") + model = TaxBenefitModel(name=f"split-{country_id}-{uuid4().hex[:16]}") version = TaxBenefitModelVersion( model=model, version=CATALOG_VERSION, diff --git a/tests/unit/test_split_v2_policy_copies_script.py b/tests/unit/test_split_v2_policy_copies_script.py index 25bcfd34c..422fdc58b 100644 --- a/tests/unit/test_split_v2_policy_copies_script.py +++ b/tests/unit/test_split_v2_policy_copies_script.py @@ -15,7 +15,13 @@ from uuid import UUID import pytest -from policyengine_api.services.v2.policy_copy_splits.types import ( + +from policyengine_api.constants import REPO +from policyengine_api.data.v2.settings import ( + V2_POLICY_COPY_SPLIT_DATABASE_URL, + V2ConfigurationError, +) +from policyengine_api.services.v2.policy_copy_split.types import ( CopyReferences, PolicyCopyOutcome, PolicyCopyRefusalReason, @@ -24,12 +30,6 @@ RepointedSavedPolicy, SplitContent, ) - -from policyengine_api.constants import REPO -from policyengine_api.data.v2.settings import ( - V2_POLICY_COPY_SPLIT_DATABASE_URL, - V2ConfigurationError, -) from scripts import split_v2_policy_copies if TYPE_CHECKING: @@ -294,8 +294,8 @@ def test_loading_the_command_leaves_the_observability_runtime_unbuilt() -> None: "import sys\n" "import scripts.split_v2_policy_copies\n" "import policyengine_api.data.v2.database\n" - "import policyengine_api.services.v2.policy_copy_splits.database_session\n" - "import policyengine_api.services.v2.policy_copy_splits.services\n" + "import policyengine_api.services.v2.policy_copy_split.database_session\n" + "import policyengine_api.services.v2.policy_copy_split.services\n" "loaded = 'policyengine_api.observability' in sys.modules\n" "assert not loaded, 'the observability runtime was imported'\n" ) diff --git a/tests/unit/test_v2_integration_workflow.py b/tests/unit/test_v2_integration_workflow.py index 88f2dd866..c61cba46b 100644 --- a/tests/unit/test_v2_integration_workflow.py +++ b/tests/unit/test_v2_integration_workflow.py @@ -89,3 +89,13 @@ def test_the_job_publishes_selected_folders_of_the_installed_models() -> None: "uv run --frozen --extra dev python scripts/reconcile_v2_privileges.py verify" ) < commands.index(step["run"]) assert (REPO / INSTALLED_FOLDERS_TEST).exists() + + +def test_the_job_runs_the_policy_copy_split_as_its_temporary_role() -> None: + """The split command's Postgres tests run, as the role C1 · 49 creates.""" + commands = _step_commands(_runtime_job()) + + assert any( + "tests/integration/test_v2_policy_copy_splits.py" in command + for command in commands + ) diff --git a/tests/unit/v2/test_policy_copy_split_rules.py b/tests/unit/v2/test_policy_copy_split_rules.py index eaa688ba4..1fa066473 100644 --- a/tests/unit/v2/test_policy_copy_split_rules.py +++ b/tests/unit/v2/test_policy_copy_split_rules.py @@ -12,16 +12,6 @@ from uuid import UUID import pytest -from policyengine_api.services.v2.policy_copy_splits.transformations import ( - split_stored_policy, -) -from policyengine_api.services.v2.policy_copy_splits.types import ( - PolicyCopyRefusalReason, -) -from policyengine_api.services.v2.policy_copy_splits.validators import ( - PolicyCopySplitRefusedError, - merge_dynamic_content, -) from policyengine_api.data.v2.models import ( Dynamic, @@ -36,6 +26,16 @@ from policyengine_api.services.v2.policies.validators import ( MAXIMUM_POLICY_PARAMETER_VALUES, ) +from policyengine_api.services.v2.policy_copy_split.transformations import ( + split_stored_policy, +) +from policyengine_api.services.v2.policy_copy_split.types import ( + PolicyCopyRefusalReason, +) +from policyengine_api.services.v2.policy_copy_split.validators import ( + PolicyCopySplitRefusedError, + merge_dynamic_content, +) MODEL_ID = UUID("00000000-0000-0000-0000-00000000a001") MODEL_VERSION_ID = UUID("00000000-0000-0000-0000-00000000a002") diff --git a/tests/unit/v2/test_privilege_manifest.py b/tests/unit/v2/test_privilege_manifest.py index 2bfed76fc..c3f941df7 100644 --- a/tests/unit/v2/test_privilege_manifest.py +++ b/tests/unit/v2/test_privilege_manifest.py @@ -48,7 +48,7 @@ STAGE12_PACKAGES = frozenset({"comparison_runs"}) # Run once, by hand, as a temporary role the operator creates with # POLICY_COPY_SPLIT_PRIVILEGES (C1 · 48 and C1 · 49), never as a managed role. -POLICY_COPY_SPLIT_PACKAGES = frozenset({"policy_copy_splits"}) +POLICY_COPY_SPLIT_PACKAGES = frozenset({"policy_copy_split"}) TEST_ENVIRONMENT = "staging" # The rows the simulation service creates, and the run tables among them. SIMULATION_SERVICE_CREATES = frozenset( From 6056ebe405f43e9c1a965df5997ed1ac2750c1d7 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:58:42 +0400 Subject: [PATCH 3/9] =?UTF-8?q?C1=20=C2=B7=2048:=20tests=20for=20review=20?= =?UTF-8?q?round=201's=20bugs=20(failing)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The split deadlocks with API v1's copy of a v1 saved policy, which locks the mapping and then inserts a saved policy naming the copy: the split locks the copy first, then the mapping. - The read-only listing says a later copy's dynamic and saved dynamic would be created when --apply reuses the ones an earlier copy created. - The command's connection has no connection, lock or statement timeout. Also covers a copy a simulation names, and the listing's READ ONLY sessions refusing a write. Co-Authored-By: Claude Opus 5.5 --- .../integration/test_v2_policy_copy_splits.py | 177 ++++++++++++++++++ .../test_split_v2_policy_copies_script.py | 50 +++++ 2 files changed, 227 insertions(+) diff --git a/tests/integration/test_v2_policy_copy_splits.py b/tests/integration/test_v2_policy_copy_splits.py index bd5e9b794..c84ea40d2 100644 --- a/tests/integration/test_v2_policy_copy_splits.py +++ b/tests/integration/test_v2_policy_copy_splits.py @@ -9,6 +9,8 @@ from __future__ import annotations +import threading +import time from dataclasses import dataclass, field from datetime import UTC, datetime from typing import TYPE_CHECKING @@ -16,17 +18,21 @@ import pytest from sqlalchemy import create_engine, delete, or_ +from sqlalchemy.exc import DBAPIError from sqlalchemy.orm import sessionmaker from sqlalchemy.pool import NullPool from sqlmodel import Session, col, select +from policyengine_api.data.v2.database import unpooled_v2_read_only_sessions from policyengine_api.data.v2.models import ( + Dataset, Dynamic, LegacyPolicyMapping, Parameter, ParameterValue, Policy, Report, + Simulation, TaxBenefitModel, TaxBenefitModelVersion, User, @@ -188,6 +194,16 @@ def _remove(owner_engine: Engine, scenario: Scenario) -> None: session.execute( delete(Report).where(Report.tax_benefit_model_id == scenario.model_id) ) + session.execute( + delete(Simulation).where( + Simulation.tax_benefit_model_version_id == scenario.version_id + ) + ) + session.execute( + delete(Dataset).where( + Dataset.tax_benefit_model_version_id == scenario.version_id + ) + ) session.execute( delete(Policy).where(Policy.tax_benefit_model_id == scenario.model_id) ) @@ -766,3 +782,164 @@ def test_one_copy_splits_in_a_caller_owned_transaction( with Session(split_role_engine) as session: assert split_policy_copy_in_session(session, uuid4()) is None + + +def test_a_copy_a_simulation_names_is_kept( + owner_engine: Engine, split_role_engine: Engine, us_scenario: Scenario +) -> None: + scenario = us_scenario + old_copy_id = _store_policy( + owner_engine, + scenario, + scenario.parameter_value(US_TAX_RATE, value=0.3), + scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), + ) + with Session(owner_engine) as session: + dataset = Dataset( + name="split-test-dataset", + year=2026, + is_output_dataset=False, + tax_benefit_model_version_id=scenario.version_id, + ) + session.add(dataset) + session.flush() + simulation = Simulation( + dataset_id=dataset.id, + tax_benefit_model_version_id=scenario.version_id, + policy_id=old_copy_id, + ) + session.add(simulation) + session.commit() + simulation_id = simulation.id + + split = _result_for( + list(_service(split_role_engine).split_policy_copies()), old_copy_id + ) + + assert split.outcome is PolicyCopyOutcome.KEPT + assert ( + split.references.simulations, + split.references.reports, + split.references.household_jobs, + ) == (1, 0, 0) + assert _policy_exists(owner_engine, old_copy_id) + with Session(owner_engine) as session: + assert session.get(Simulation, simulation_id).policy_id == old_copy_id + + +def test_the_split_waits_for_a_live_saved_policy_copy_instead_of_deadlocking( + owner_engine: Engine, split_role_engine: Engine, us_scenario: Scenario +) -> None: + """API v1's copy of a v1 saved policy locks the mapping, then names the copy. + + It holds the mapping row FOR UPDATE, then inserts a saved policy naming + the mapped copy, whose foreign-key check locks the copy's row. The split + takes the same two locks in the same order, so it waits for the copy to + commit, and then re-points the saved policy the copy added. + """ + scenario = us_scenario + old_copy_id = _store_policy( + owner_engine, + scenario, + scenario.parameter_value(US_TAX_RATE, value=0.3), + scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), + ) + legacy_policy_id = _store_mapping(owner_engine, scenario, policy_id=old_copy_id) + user_id = _store_user(owner_engine, scenario) + split_results: list[PolicyCopySplit] = [] + split_errors: list[Exception] = [] + + def run_split() -> None: + try: + split_results.extend(_service(split_role_engine).split_policy_copies()) + except DBAPIError as error: + split_errors.append(error) + + split_thread = threading.Thread(target=run_split) + with Session(owner_engine) as live_copy: + live_copy.exec( + select(LegacyPolicyMapping) + .where( + LegacyPolicyMapping.country_id == scenario.country_id, + LegacyPolicyMapping.legacy_policy_id == legacy_policy_id, + ) + .with_for_update() + ).one() + split_thread.start() + # Give the split time to reach its locks while the mapping is held. + time.sleep(0.5) + saved_policy = UserPolicy( + user_id=user_id, + country_id=scenario.country_id, + policy_id=old_copy_id, + legacy_policy_id=legacy_policy_id, + name="Saved while splitting", + ) + live_copy.add(saved_policy) + live_copy.commit() + saved_policy_id = saved_policy.id + split_thread.join(timeout=60) + + assert not split_thread.is_alive() + assert split_errors == [] + split = _result_for(split_results, old_copy_id) + assert split.outcome is PolicyCopyOutcome.DELETED + assert [repointed.user_policy_id for repointed in split.saved_policies] == [ + saved_policy_id + ] + assert _saved_policy_target(owner_engine, saved_policy_id) == split.policy.id + assert not _policy_exists(owner_engine, old_copy_id) + + +def test_the_listing_reports_rows_an_earlier_copy_creates_as_reused( + owner_engine: Engine, split_role_engine: Engine, uk_scenario: Scenario +) -> None: + """Applying commits each copy before the next, so later copies reuse its rows. + + The listing reports what applying then does: the second copy's dynamic + and saved dynamic are the first copy's. + """ + scenario = uk_scenario + copy_ids = [ + _store_policy( + owner_engine, + scenario, + scenario.parameter_value(UK_TAX_RATE, value=tax_rate), + scenario.parameter_value(UK_OBR_SWITCH, value=False), + ) + for tax_rate in (0.21, 0.22) + ] + user_id = _store_user(owner_engine, scenario) + for copy_id in copy_ids: + _store_saved_policy( + owner_engine, scenario, user_id=user_id, policy_id=copy_id, name=None + ) + + listed = _service(split_role_engine, read_only=True).list_policy_copy_splits() + applied = list(_service(split_role_engine).split_policy_copies()) + + def created_rows(split: PolicyCopySplit) -> tuple[bool, bool, list[bool]]: + return ( + split.policy.created, + split.dynamic.created, + [saved.saved_dynamic_created for saved in split.saved_policies], + ) + + assert [created_rows(_result_for(listed, copy_id)) for copy_id in copy_ids] == [ + (True, True, [True]), + (True, False, [False]), + ] + assert [created_rows(_result_for(applied, copy_id)) for copy_id in copy_ids] == [ + created_rows(_result_for(listed, copy_id)) for copy_id in copy_ids + ] + assert len(_saved_dynamics(owner_engine, user_id)) == 1 + + +def test_the_listing_s_sessions_refuse_writes(disposable_v2_database_url: str) -> None: + with ( + unpooled_v2_read_only_sessions(disposable_v2_database_url) as sessions, + sessions() as session, + ): + session.add(User(user_type="unauthenticated")) + with pytest.raises(DBAPIError, match="read-only transaction"): + session.flush() diff --git a/tests/unit/test_split_v2_policy_copies_script.py b/tests/unit/test_split_v2_policy_copies_script.py index 422fdc58b..a22c2b898 100644 --- a/tests/unit/test_split_v2_policy_copies_script.py +++ b/tests/unit/test_split_v2_policy_copies_script.py @@ -15,10 +15,13 @@ from uuid import UUID import pytest +from sqlalchemy.orm import sessionmaker from policyengine_api.constants import REPO from policyengine_api.data.v2.settings import ( V2_POLICY_COPY_SPLIT_DATABASE_URL, + V2_SUPABASE_ENVIRONMENT, + V2_SUPABASE_PROJECT_REF, V2ConfigurationError, ) from policyengine_api.services.v2.policy_copy_split.types import ( @@ -275,6 +278,53 @@ def test_the_command_needs_its_own_database_url(monkeypatch) -> None: pass +@pytest.mark.parametrize( + ("run", "expected_opener"), + [("listing", "unpooled_v2_read_only_sessions"), ("apply", "unpooled_v2_sessions")], +) +def test_the_command_lists_read_only_and_bounds_its_waits( + monkeypatch, run: str, expected_opener: str +) -> None: + """The listing's transactions are READ ONLY, and no wait lasts indefinitely. + + The URL gains a connection timeout, and a lock and statement timeout, so + a lock wait can't hold the copy's row lock indefinitely. + """ + from policyengine_api.data.v2 import database + + project_ref = "abcdefghijklmnopqrst" + monkeypatch.setenv( + V2_POLICY_COPY_SPLIT_DATABASE_URL, + f"postgresql+psycopg://policy-copy-split:password@db.{project_ref}." + "supabase.co:5432/postgres?sslmode=require", + ) + monkeypatch.setenv(V2_SUPABASE_PROJECT_REF, project_ref) + monkeypatch.setenv(V2_SUPABASE_ENVIRONMENT, "staging") + opened: list[tuple[str, object]] = [] + + def recording_opener(name: str): + @contextmanager + def open_sessions(url): + opened.append((name, url)) + yield sessionmaker() + + return open_sessions + + for name in ("unpooled_v2_read_only_sessions", "unpooled_v2_sessions"): + monkeypatch.setattr(database, name, recording_opener(name)) + + with split_v2_policy_copies.splitter_on_temporary_role( + writable=run == "apply" + ) as splitter: + assert hasattr(splitter, "split_policy_copies") + + [(opener, url)] = opened + assert opener == expected_opener + assert url.query["connect_timeout"] == "10" + assert url.query["options"] == "-c lock_timeout=10000 -c statement_timeout=60000" + assert url.query["sslmode"] == "require" + + def test_the_command_refuses_unknown_arguments() -> None: with pytest.raises(SystemExit) as exit_info: split_v2_policy_copies.main( From 6dc55162d2f50aa954a2bb6eab11c4fc329c36b3 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:01:26 +0400 Subject: [PATCH 4/9] =?UTF-8?q?C1=20=C2=B7=2048:=20fix=20review=20round=20?= =?UTF-8?q?1's=20findings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The split locks the legacy mappings and saved policies naming a copy before the copy, and reads them again once it is locked, so it waits for API v1's copy of a v1 saved policy (which locks a mapping, then names the copy) instead of deadlocking with it. - The listing carries the rows it reports across copies, so a dynamic or saved dynamic an earlier copy would create is reported as reused, as --apply then does; the command says "the one listed above would be reused" for such a row. - The command adds a 10-second connection timeout, a 10-second lock timeout and a 60-second statement timeout to its URL. - The runbook says what the repeat listing may show and what the operator does about kept and refused copies, names the saved policy's baseline and provenance instead of a label, and describes the lock order and the timeouts. A comment in privileges moves back above _RESULT. Co-Authored-By: Claude Opus 5.5 --- docs/migration/stage-10-v2-policies.md | 33 ++++- policyengine_api/data/v2/privileges.py | 2 +- .../services/v2/policy_copy_split/services.py | 138 ++++++++++++------ .../services/v2/policy_copy_split/types.py | 26 +++- scripts/split_v2_policy_copies.py | 48 +++++- .../integration/test_v2_policy_copy_splits.py | 18 ++- 6 files changed, 208 insertions(+), 57 deletions(-) diff --git a/docs/migration/stage-10-v2-policies.md b/docs/migration/stage-10-v2-policies.md index 0a0172304..084282eab 100644 --- a/docs/migration/stage-10-v2-policies.md +++ b/docs/migration/stage-10-v2-policies.md @@ -303,9 +303,12 @@ revision, which moves dynamic parameters into their own tables, refuses to run while any policy value names one, because the foreign key's cascade would otherwise change those policies silently. -For each such policy, in one transaction that first locks it (`SELECT … FOR -UPDATE`, so nothing can start naming it meanwhile), the command -(`policyengine_api/services/v2/policy_copy_split/services.py`): +For each such policy, in one transaction, the command +(`policyengine_api/services/v2/policy_copy_split/services.py`) locks the +legacy mappings and saved policies that name it, then the policy itself +(`SELECT … FOR UPDATE`, so nothing can start naming it meanwhile), in the +order API v1's copy of a v1 saved policy takes the same locks, so the two +wait for each other instead of deadlocking. It then: - finds or creates a policy holding the values that aren't model assumptions, empty when there are none, and a dynamic holding the model assumptions, @@ -318,7 +321,7 @@ UPDATE`, so nothing can start naming it meanwhile), the command dynamic's values and the copy's model assumptions together; the earlier dynamic is kept; - points each `user_policies` row that names the copy at that policy, keeping - its name, description and label, and gives its owner a `user_dynamics` row + its name, description, `baseline` and `provenance`, and gives its owner a `user_dynamics` row with the saved policy's name and no description, naming the dynamic the saved policy's own v1 policy's mapping now names, or else the copy's dynamic. When the owner already has a saved dynamic in that country naming @@ -337,7 +340,8 @@ The user decided these cases on 2026-11-25. Running the command again changes nothing: a re-pointed mapping or saved policy no longer names the copy, and the policy and dynamic are found by -their content hashes. A kept copy is listed as kept again. +their content hashes. A kept copy is listed as kept again, and a refused +copy as refused. ### Deploy order @@ -345,8 +349,13 @@ their content hashes. A kept copy is listed as kept again. in the environment, so the v1-to-v2 copy there splits UK `gov.dynamic.` values too and no new policy holding model assumptions is stored. 2. C1 · 49 runs the command there: the read-only listing, then `--apply`, - then the listing again, which must list nothing. -3. Only then does C1 · 50's revision run in that environment. + then the listing again. That listing lists nothing and exits with 0, or + lists only kept and refused copies and exits with 1. Each of those still + holds model assumptions as policy values, so the operator settles it by + hand first (for example by deleting the test simulations, reports or + household calculations that name it), with the user's approval. +3. Only then, once a listing lists nothing, does C1 · 50's revision run in + that environment. ### The temporary role @@ -419,6 +428,14 @@ or refused (with the reason). With `--apply` it reports the same with the IDs of the rows it points at or creates, as each copy's transaction commits. It prints no URL, saved-policy name or user ID. +The listing reports a row that an earlier copy in the same run would create +as reused, since `--apply` commits each copy before the next. + It exits with 0 when no stored policy sets a model assumption afterwards (for the listing: when every listed copy would be deleted), and with 1 otherwise. -Missing settings or a failed connection raise, and also exit with 1. +Missing settings or a failed connection raise, and also exit with 1. The +command adds a 10-second connection timeout, a 10-second lock timeout and a +60-second statement timeout to the URL, so a wait for a lock that a live +write holds ends with an error rather than holding the copy's lock +indefinitely; the copies already reported have committed, and running the +command again carries on. diff --git a/policyengine_api/data/v2/privileges.py b/policyengine_api/data/v2/privileges.py index f14e5829f..34dded6ef 100644 --- a/policyengine_api/data/v2/privileges.py +++ b/policyengine_api/data/v2/privileges.py @@ -239,7 +239,6 @@ def _run_table( ) -# The Modal workers write results, keyed by run, once each. # The policy copy split's temporary role (see the module docstring). It locks # and deletes the old copies (their values go with them by the foreign key's # cascade), re-points legacy mappings and saved policies, inserts policies, @@ -261,6 +260,7 @@ def _run_table( "user_policies": _READ_UPDATE, } +# The Modal workers write results, keyed by run, once each. _RESULT = _access(runtime=READ, modal_worker=READ_INSERT) # What a run needs from the Public API's policies, dynamics, households and # catalog. diff --git a/policyengine_api/services/v2/policy_copy_split/services.py b/policyengine_api/services/v2/policy_copy_split/services.py index e26dcd7ac..e89ebb513 100644 --- a/policyengine_api/services/v2/policy_copy_split/services.py +++ b/policyengine_api/services/v2/policy_copy_split/services.py @@ -67,12 +67,14 @@ ) from policyengine_api.services.v2.policy_copy_split.types import ( CopyReferences, + ListedRows, MappingTarget, PolicyCopyOutcome, PolicyCopySplit, PreparedPolicyCopySplit, RepointedMapping, RepointedSavedPolicy, + SavedDynamicIdentity, SavedPolicyTarget, SplitContent, ) @@ -84,7 +86,7 @@ from policyengine_api.services.v2.user_dynamics.types import UserDynamicCreationInput if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterator from uuid import UUID from sqlmodel import Session @@ -142,11 +144,20 @@ def _mapping_dynamic( def _prepare( session: Session, policy_id: UUID, *, lock: bool ) -> PreparedPolicyCopySplit | None: - """Read what the split of one copy needs, locking it first with ``lock``. - - Return None when the policy is no longer stored or sets no model - assumption. + """Read what the split of one copy needs, locking the rows it changes with ``lock``. + + The locks are taken in the order API v1's copies take them, so the split + waits for a copy instead of deadlocking with it: the copy of a v1 saved + policy locks the legacy mapping, then saves a policy naming the mapped + copy, whose foreign-key check locks the copy's row. So the mappings and + saved policies naming the copy are locked before the copy, and read + again once it is locked, since one committed meanwhile can name it and + none can be added after. Return None when the policy is no longer stored + or sets no model assumption. """ + if lock: + read_mappings_naming_policy(session, policy_id, lock=True) + read_saved_policies_naming_policy(session, policy_id, lock=True) policy = read_policy_for_split(session, policy_id, lock=lock) if policy is None: return None @@ -237,47 +248,94 @@ def _refused(prepared: PreparedPolicyCopySplit, *, applied: bool) -> PolicyCopyS def _remaining_outcome(prepared: PreparedPolicyCopySplit) -> PolicyCopyOutcome: - """Return the copy's outcome: deleted, unless a simulation or report names it.""" + """Return deleted, unless a simulation, report or household job names the copy.""" if prepared.references.total: return PolicyCopyOutcome.KEPT return PolicyCopyOutcome.DELETED -def plan_policy_copy_split(session: Session, policy_id: UUID) -> PolicyCopySplit | None: +def plan_policy_copy_split( + session: Session, policy_id: UUID, listed: ListedRows | None = None +) -> PolicyCopySplit | None: """Return what splitting one copy would change, reading only. - Rows that don't exist yet have no ID. Return None when the policy is no - longer stored or sets no model assumption. + Rows that don't exist yet have no ID. ``listed`` holds what the listing + reported for earlier copies: applying commits each copy before the next, + so a row an earlier copy creates is reused, and is reported so. Return + None when the policy is no longer stored or sets no model assumption. """ + listed = ListedRows() if listed is None else listed prepared = _prepare(session, policy_id, lock=False) if prepared is None: return None if prepared.refusal_reason is not None: return _refused(prepared, applied=False) - listed_dynamics: dict[str, SplitContent] = {} - - def listed_dynamic(content: ResolvedDynamicCreationInput) -> SplitContent: + copy_policies: dict[str, SplitContent] = {} + copy_dynamics: dict[str, SplitContent] = {} + + def listed_row( + content: ResolvedPolicyCreationInput, + *, + copy_rows: dict[str, SplitContent], + run_rows: dict[str, SplitContent], + stored_id: Callable[[int, str], UUID | None], + ) -> SplitContent: + """Report one policy or dynamic as applying this copy would find or create it. + + Within one copy, applying reports a row the same way each time it + meets it; a later copy finds the row an earlier copy created. + """ canonical = canonicalize_policy(content) - content_hash = canonical.content_hash - if content_hash not in listed_dynamics: - stored = read_dynamic_by_content_identity( - session, - canonicalization_version=canonical.version, - content_hash=content_hash, + if canonical.content_hash in copy_rows: + return copy_rows[canonical.content_hash] + earlier = run_rows.get(canonical.content_hash) + if earlier is not None: + row = SplitContent( + id=earlier.id, content_hash=canonical.content_hash, created=False ) - listed_dynamics[content_hash] = SplitContent( - id=None if stored is None else stored.id, - content_hash=content_hash, - created=stored is None, + else: + row_id = stored_id(canonical.version, canonical.content_hash) + row = SplitContent( + id=row_id, content_hash=canonical.content_hash, created=row_id is None ) - return listed_dynamics[content_hash] + run_rows[canonical.content_hash] = row + copy_rows[canonical.content_hash] = row + return row + + def stored_policy_id( + canonicalization_version: int, content_hash: str + ) -> UUID | None: + stored = read_policy_by_content_identity( + session, + canonicalization_version=canonicalization_version, + content_hash=content_hash, + ) + return None if stored is None else stored.id + + def stored_dynamic_id( + canonicalization_version: int, content_hash: str + ) -> UUID | None: + stored = read_dynamic_by_content_identity( + session, + canonicalization_version=canonicalization_version, + content_hash=content_hash, + ) + return None if stored is None else stored.id + + def listed_dynamic(content: ResolvedDynamicCreationInput) -> SplitContent: + return listed_row( + content, + copy_rows=copy_dynamics, + run_rows=listed.dynamics, + stored_id=stored_dynamic_id, + ) - policy_content = canonicalize_policy(prepared.split.policy) - stored_policy = read_policy_by_content_identity( - session, - canonicalization_version=policy_content.version, - content_hash=policy_content.content_hash, + policy = listed_row( + prepared.split.policy, + copy_rows=copy_policies, + run_rows=listed.policies, + stored_id=stored_policy_id, ) plain_dynamic = listed_dynamic(prepared.split.dynamic) mappings = tuple( @@ -290,7 +348,6 @@ def listed_dynamic(content: ResolvedDynamicCreationInput) -> SplitContent: for target in prepared.mapping_targets ) saved_policies = [] - planned_saved_dynamics: set[tuple[UUID, str, str, str | None]] = set() for target in prepared.saved_policy_targets: dynamic = listed_dynamic(target.dynamic) existing = ( @@ -304,11 +361,11 @@ def listed_dynamic(content: ResolvedDynamicCreationInput) -> SplitContent: name=target.name, ) ) - identity = ( - target.user_id, - target.country_id, - dynamic.content_hash, - target.name, + identity = SavedDynamicIdentity( + user_id=target.user_id, + country_id=target.country_id, + dynamic_content_hash=dynamic.content_hash, + name=target.name, ) saved_policies.append( RepointedSavedPolicy( @@ -316,21 +373,17 @@ def listed_dynamic(content: ResolvedDynamicCreationInput) -> SplitContent: dynamic=dynamic, saved_dynamic_id=None if existing is None else existing.id, saved_dynamic_created=existing is None - and identity not in planned_saved_dynamics, + and identity not in listed.saved_dynamics, ) ) - planned_saved_dynamics.add(identity) + listed.saved_dynamics.add(identity) return PolicyCopySplit( old_policy_id=prepared.policy_id, country_id=prepared.country_id, policyengine_version=prepared.policyengine_version, applied=False, outcome=_remaining_outcome(prepared), - policy=SplitContent( - id=None if stored_policy is None else stored_policy.id, - content_hash=policy_content.content_hash, - created=stored_policy is None, - ), + policy=policy, dynamic=plain_dynamic, mappings=mappings, saved_policies=tuple(saved_policies), @@ -466,9 +519,10 @@ def __init__(self, database_session: PolicyCopySplitDatabaseSession) -> None: def list_policy_copy_splits(self) -> tuple[PolicyCopySplit, ...]: """Return what splitting every copy would change, in one read session.""" + listed = ListedRows() with self._database_session.read() as session: planned = ( - plan_policy_copy_split(session, policy_id) + plan_policy_copy_split(session, policy_id, listed) for policy_id in read_policy_copy_ids(session) ) return tuple(split for split in planned if split is not None) diff --git a/policyengine_api/services/v2/policy_copy_split/types.py b/policyengine_api/services/v2/policy_copy_split/types.py index ed9e4585e..9cf7133ba 100644 --- a/policyengine_api/services/v2/policy_copy_split/types.py +++ b/policyengine_api/services/v2/policy_copy_split/types.py @@ -8,7 +8,7 @@ from __future__ import annotations -from dataclasses import dataclass +from dataclasses import dataclass, field from enum import StrEnum from typing import TYPE_CHECKING @@ -181,3 +181,27 @@ class PolicyCopySplit: saved_policies: tuple[RepointedSavedPolicy, ...] references: CopyReferences refusal_reason: PolicyCopyRefusalReason | None + + +@dataclass(frozen=True) +class SavedDynamicIdentity: + """What makes two saved dynamics identical: owner, country, dynamic and name.""" + + user_id: UUID + country_id: str + dynamic_content_hash: str + name: str | None + + +@dataclass +class ListedRows: + """What a listing has reported so far, across copies, by content hash. + + Applying commits each copy before the next, so a later copy finds the + policies, dynamics and saved dynamics an earlier copy created; the + listing reports those as found, as applying will. + """ + + policies: dict[str, SplitContent] = field(default_factory=dict) + dynamics: dict[str, SplitContent] = field(default_factory=dict) + saved_dynamics: set[SavedDynamicIdentity] = field(default_factory=set) diff --git a/scripts/split_v2_policy_copies.py b/scripts/split_v2_policy_copies.py index 433734808..37754226d 100755 --- a/scripts/split_v2_policy_copies.py +++ b/scripts/split_v2_policy_copies.py @@ -20,8 +20,10 @@ (for the listing: when every copy would be deleted), and with 1 otherwise, such as when a copy is kept because a simulation, report or household calculation names it, or refused. Any other failure, such as missing -settings or an unreachable database, raises, so Python prints its traceback -and also exits with 1. +settings, an unreachable database (after 10 seconds) or a lock wait of more +than 10 seconds, raises, so Python prints its traceback and also exits with +1; the copies already reported have committed, and running it again +carries on. It connects as the temporary role ``policyengine_v2_policy_copy_split``, which the operator creates with the grants in @@ -47,6 +49,8 @@ from collections.abc import Callable, Iterable, Iterator, Sequence from contextlib import AbstractContextManager + from sqlalchemy.engine import URL + from policyengine_api.services.v2.policy_copy_split.types import ( CopyReferences, PolicyCopySplit, @@ -55,6 +59,11 @@ ) +CONNECT_TIMEOUT_SECONDS = 10 +LOCK_TIMEOUT_MILLISECONDS = 10_000 +STATEMENT_TIMEOUT_MILLISECONDS = 60_000 + + class PolicyCopySplitter(Protocol): """The split service operations this command calls.""" @@ -80,6 +89,7 @@ def splitter_on_temporary_role(*, writable: bool) -> Iterator[PolicyCopySplitter settings. """ settings = load_v2_policy_copy_split_database_settings() + url = with_time_limits(settings.connection.url) # These modules are imported only when the command runs, as they need the # connection. from policyengine_api.data.v2.database import ( @@ -94,10 +104,35 @@ def splitter_on_temporary_role(*, writable: bool) -> Iterator[PolicyCopySplitter ) open_sessions = unpooled_v2_sessions if writable else unpooled_v2_read_only_sessions - with open_sessions(settings.connection.url) as session_factory: + with open_sessions(url) as session_factory: yield V2PolicyCopySplitService(PolicyCopySplitDatabaseSession(session_factory)) +def with_time_limits(url: URL) -> URL: + """Return the URL with a connection timeout, and lock and statement timeouts. + + A lock wait then fails after a while instead of lasting indefinitely + while the split holds a copy's row lock, which blocks a live write that + names the copy. Earlier copies' transactions have committed by then, and + running the command again carries on. + """ + time_limits = ( + f"-c lock_timeout={LOCK_TIMEOUT_MILLISECONDS} " + f"-c statement_timeout={STATEMENT_TIMEOUT_MILLISECONDS}" + ) + existing_options = url.query.get("options") + return url.update_query_dict( + { + "connect_timeout": str(CONNECT_TIMEOUT_SECONDS), + "options": ( + time_limits + if existing_options is None + else f"{existing_options} {time_limits}" + ), + } + ) + + def _parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( description=( @@ -119,8 +154,13 @@ def _plural(count: int, singular: str, plural: str | None = None) -> str: def _content(kind: str, content: SplitContent) -> str: """Name a policy or dynamic: its ID, or its content hash if it is still to come.""" - if content.id is None: + if content.id is None and content.created: return f"{kind}: would be created (content hash {content.content_hash[:12]})" + if content.id is None: + return ( + f"{kind}: the one listed above would be reused " + f"(content hash {content.content_hash[:12]})" + ) return f"{kind} {content.id} ({'created' if content.created else 'already stored'})" diff --git a/tests/integration/test_v2_policy_copy_splits.py b/tests/integration/test_v2_policy_copy_splits.py index c84ea40d2..fc7a532c5 100644 --- a/tests/integration/test_v2_policy_copy_splits.py +++ b/tests/integration/test_v2_policy_copy_splits.py @@ -17,7 +17,8 @@ from uuid import UUID, uuid4 import pytest -from sqlalchemy import create_engine, delete, or_ +from sqlalchemy import create_engine, delete, func, or_ +from sqlalchemy.engine import make_url from sqlalchemy.exc import DBAPIError from sqlalchemy.orm import sessionmaker from sqlalchemy.pool import NullPool @@ -64,6 +65,7 @@ PolicyCopyRefusalReason, PolicyCopySplit, ) +from scripts.split_v2_policy_copies import with_time_limits if TYPE_CHECKING: from collections.abc import Iterator @@ -943,3 +945,17 @@ def test_the_listing_s_sessions_refuse_writes(disposable_v2_database_url: str) - session.add(User(user_type="unauthenticated")) with pytest.raises(DBAPIError, match="read-only transaction"): session.flush() + + +def test_the_command_s_time_limits_reach_its_sessions( + disposable_v2_database_url: str, +) -> None: + url = with_time_limits(make_url(disposable_v2_database_url)) + + with unpooled_v2_read_only_sessions(url) as sessions, sessions() as session: + lock_timeout = session.exec(select(func.current_setting("lock_timeout"))) + assert lock_timeout.one() == "10s" + statement_timeout = session.exec( + select(func.current_setting("statement_timeout")) + ) + assert statement_timeout.one() == "1min" From e267573f991849dd0e918c7511a8af0b60e95c85 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:28:57 +0400 Subject: [PATCH 5/9] =?UTF-8?q?C1=20=C2=B7=2048:=20tests=20for=20review=20?= =?UTF-8?q?round=202's=20bugs=20(failing)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The split deadlocks with API v1's sign-in merge, which locks the browser's user and then moves its saved policies, while the split holds a saved policy's lock and waits for the user's to save its dynamic. The split should give way: a lock timeout shorter than PostgreSQL's one-second deadlock_timeout (500 ms), then the copy tried again. - The runbook's DROP OWNED BY fails for a login that isn't a superuser; it should revoke each grant, then drop the role. - The split's URL accepts Supavisor's transaction-mode port 6543, where the lock and statement timeouts don't apply. Also covers a refusal for a mapping's dynamic on another catalog version, the listing of a merged dynamic, and a copy kept by a household calculation. Co-Authored-By: Claude Opus 5.5 --- .../integration/test_v2_policy_copy_splits.py | 284 +++++++++++++++++- .../test_split_v2_policy_copies_script.py | 4 +- .../unit/v2/test_policy_copy_split_retries.py | 116 +++++++ .../unit/v2/test_policy_copy_split_runbook.py | 23 +- tests/unit/v2/test_settings.py | 15 + 5 files changed, 427 insertions(+), 15 deletions(-) create mode 100644 tests/unit/v2/test_policy_copy_split_retries.py diff --git a/tests/integration/test_v2_policy_copy_splits.py b/tests/integration/test_v2_policy_copy_splits.py index ac206d947..9e1034f79 100644 --- a/tests/integration/test_v2_policy_copy_splits.py +++ b/tests/integration/test_v2_policy_copy_splits.py @@ -18,15 +18,20 @@ from uuid import UUID, uuid4 import pytest -from sqlalchemy import delete, func, or_ +from sqlalchemy import delete, func, or_, update from sqlalchemy.engine import make_url from sqlalchemy.exc import DBAPIError from sqlmodel import Session, col, select -from policyengine_api.data.v2.database import unpooled_v2_read_only_sessions +from policyengine_api.data.v2.database import ( + unpooled_v2_read_only_sessions, + unpooled_v2_sessions, +) from policyengine_api.data.v2.models import ( Dataset, Dynamic, + Household, + HouseholdJob, LegacyPolicyMapping, Parameter, ParameterValue, @@ -119,23 +124,44 @@ def listing_sessions( yield sessions -class ListingAsTheSplitRole(PolicyCopySplitDatabaseSession): - """Act as the temporary role in each of the listing's READ ONLY sessions.""" +@pytest.fixture(scope="module") +def time_limited_sessions( + disposable_v2_database_url: str, split_role_sessions: sessionmaker[Session] +) -> Iterator[sessionmaker[Session]]: + """Yield the owner's Session factories with the command's time limits. + + Their URL is the command's (``with_time_limits``), so a lock wait ends as + the command's does. ``split_role_sessions`` creates the temporary role. + """ + url = with_time_limits(make_url(disposable_v2_database_url)) + with unpooled_v2_sessions(url) as sessions: + yield sessions + + +class ActingAsTheSplitRole(PolicyCopySplitDatabaseSession): + """Act as the temporary role in each of the owner's sessions (SET LOCAL ROLE).""" @contextmanager def read(self) -> Iterator[Session]: - """Yield a READ ONLY session acting as the temporary role.""" + """Yield a session acting as the temporary role.""" with super().read() as session: act_as(session, POLICY_COPY_SPLIT_ROLE) yield session + @contextmanager + def transaction(self) -> Iterator[Session]: + """Yield a transaction acting as the temporary role.""" + with super().transaction() as session: + act_as(session, POLICY_COPY_SPLIT_ROLE) + yield session + def _service(sessions: sessionmaker[Session]) -> V2PolicyCopySplitService: return V2PolicyCopySplitService(PolicyCopySplitDatabaseSession(sessions)) def _listing_service(sessions: sessionmaker[Session]) -> V2PolicyCopySplitService: - return V2PolicyCopySplitService(ListingAsTheSplitRole(sessions)) + return V2PolicyCopySplitService(ActingAsTheSplitRole(sessions)) @dataclass @@ -146,8 +172,10 @@ class Scenario: model_id: UUID version_id: UUID parameter_ids: dict[str, UUID] + policyengine_version: str = CATALOG_VERSION user_ids: list[UUID] = field(default_factory=list) legacy_policy_ids: list[int] = field(default_factory=list) + household_ids: list[UUID] = field(default_factory=list) def parameter_value( self, name: str, *, value: object, end_date: datetime | None = END_2026 @@ -164,7 +192,7 @@ def content(self, *values: dict[str, object]) -> dict[str, object]: "country_id": self.country_id, "tax_benefit_model_id": self.model_id, "tax_benefit_model_version_id": self.version_id, - "policyengine_version": CATALOG_VERSION, + "policyengine_version": self.policyengine_version, "parameter_values": list(values), } @@ -235,19 +263,33 @@ def _remove(owner_sessions: sessionmaker[Session], scenario: Scenario) -> None: session.execute( delete(Dynamic).where(Dynamic.tax_benefit_model_id == scenario.model_id) ) + version_ids = select(TaxBenefitModelVersion.id).where( + TaxBenefitModelVersion.model_id == scenario.model_id + ) + session.execute( + delete(HouseholdJob).where( + col(HouseholdJob.tax_benefit_model_version_id).in_(version_ids) + ) + ) + session.execute( + delete(Household).where(col(Household.id).in_(scenario.household_ids)) + ) + parameter_ids = select(Parameter.id).where( + col(Parameter.tax_benefit_model_version_id).in_(version_ids) + ) session.execute( delete(ParameterValue).where( - col(ParameterValue.parameter_id).in_(scenario.parameter_ids.values()) + col(ParameterValue.parameter_id).in_(parameter_ids) ) ) session.execute( delete(Parameter).where( - Parameter.tax_benefit_model_version_id == scenario.version_id + col(Parameter.tax_benefit_model_version_id).in_(version_ids) ) ) session.execute( delete(TaxBenefitModelVersion).where( - TaxBenefitModelVersion.id == scenario.version_id + TaxBenefitModelVersion.model_id == scenario.model_id ) ) session.execute( @@ -278,6 +320,31 @@ def uk_scenario(owner_sessions: sessionmaker[Session]) -> Iterator[Scenario]: _remove(owner_sessions, scenario) +def _store_other_version( + owner_sessions: sessionmaker[Session], scenario: Scenario, names: list[str] +) -> Scenario: + """Store another catalog version of the scenario's model, with these parameters.""" + with owner_sessions() as session: + version = TaxBenefitModelVersion( + model_id=scenario.model_id, + version="6.20.0", + current_law_id=1, + metadata_time_periods=[2026], + ) + parameters = [ + Parameter(name=name, tax_benefit_model_version=version) for name in names + ] + session.add_all(parameters) + session.commit() + return Scenario( + country_id=scenario.country_id, + model_id=scenario.model_id, + version_id=version.id, + parameter_ids={parameter.name: parameter.id for parameter in parameters}, + policyengine_version="6.20.0", + ) + + def _store_policy( owner_sessions: sessionmaker[Session], scenario: Scenario, @@ -1019,8 +1086,203 @@ def test_the_command_s_time_limits_reach_its_sessions( with unpooled_v2_read_only_sessions(url) as sessions, sessions() as session: lock_timeout = session.exec(select(func.current_setting("lock_timeout"))) - assert lock_timeout.one() == "10s" + assert lock_timeout.one() == "500ms" statement_timeout = session.exec( select(func.current_setting("statement_timeout")) ) assert statement_timeout.one() == "1min" + + +def test_the_split_gives_way_to_a_live_sign_in_merge( + owner_sessions: sessionmaker[Session], + time_limited_sessions: sessionmaker[Session], + us_scenario: Scenario, +) -> None: + """API v1's sign-in merge locks the browser's user, then moves its saved policies. + + The split holds a saved policy's lock while saving its owner's dynamic, + whose foreign-key check waits for the user's lock: a lock cycle. The + split's wait ends first (its lock timeout is shorter than PostgreSQL's + deadlock_timeout), so it rolls back, the merge commits, and the split + tries the copy again, for the account the saved policy now belongs to. + """ + scenario = us_scenario + old_copy_id = _store_policy( + owner_sessions, + scenario, + scenario.parameter_value(US_TAX_RATE, value=0.3), + scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), + ) + browser_user_id = _store_user(owner_sessions, scenario) + account_user_id = _store_user(owner_sessions, scenario) + saved_policy_id = _store_saved_policy( + owner_sessions, + scenario, + user_id=browser_user_id, + policy_id=old_copy_id, + name="Saved before signing in", + ) + service = V2PolicyCopySplitService( + ActingAsTheSplitRole(time_limited_sessions), + attempts=10, + retry_delay_seconds=0.2, + ) + split_results: list[PolicyCopySplit] = [] + split_errors: list[Exception] = [] + + def run_split() -> None: + try: + split_results.extend(service.split_policy_copies()) + except DBAPIError as error: + split_errors.append(error) + + split_thread = threading.Thread(target=run_split) + with owner_sessions() as sign_in: + sign_in.exec( + select(User).where(User.id == browser_user_id).with_for_update() + ).one() + split_thread.start() + # Give the split time to wait for the browser user's lock. + time.sleep(0.3) + sign_in.execute( + update(UserPolicy) + .where(col(UserPolicy.user_id) == browser_user_id) + .values(user_id=account_user_id) + ) + sign_in.commit() + split_thread.join(timeout=60) + + assert not split_thread.is_alive() + assert split_errors == [] + split = _result_for(split_results, old_copy_id) + assert split.outcome is PolicyCopyOutcome.DELETED + with owner_sessions() as session: + saved_policy = session.get(UserPolicy, saved_policy_id) + assert (saved_policy.user_id, saved_policy.policy_id) == ( + account_user_id, + split.policy.id, + ) + [saved_dynamic] = _saved_dynamics(owner_sessions, account_user_id) + assert saved_dynamic.dynamic_id == split.dynamic.id + assert _saved_dynamics(owner_sessions, browser_user_id) == [] + + +def test_a_mapping_s_dynamic_on_another_catalog_version_refuses_the_copy( + owner_sessions: sessionmaker[Session], + split_role_sessions: sessionmaker[Session], + uk_scenario: Scenario, +) -> None: + scenario = uk_scenario + old_copy_id = _store_policy( + owner_sessions, + scenario, + scenario.parameter_value(UK_TAX_RATE, value=0.21), + scenario.parameter_value(UK_OBR_SWITCH, value=False), + ) + other_version = _store_other_version( + owner_sessions, scenario, [UK_INCOME_ELASTICITY] + ) + earlier_dynamic_id = _store_dynamic( + owner_sessions, + other_version, + other_version.parameter_value(UK_INCOME_ELASTICITY, value=0.1), + ) + legacy_policy_id = _store_mapping( + owner_sessions, scenario, policy_id=old_copy_id, dynamic_id=earlier_dynamic_id + ) + + split = _result_for( + list(_service(split_role_sessions).split_policy_copies()), old_copy_id + ) + + assert split.outcome is PolicyCopyOutcome.REFUSED + assert split.refusal_reason is PolicyCopyRefusalReason.DYNAMIC_ON_ANOTHER_CATALOG + assert _policy_exists(owner_sessions, old_copy_id) + mapping = _mapping(owner_sessions, scenario, legacy_policy_id) + assert (mapping.policy_id, mapping.dynamic_id) == (old_copy_id, earlier_dynamic_id) + + +def test_the_listing_reports_a_mapping_s_merged_dynamic_as_applying_does( + owner_sessions: sessionmaker[Session], + split_role_sessions: sessionmaker[Session], + listing_sessions: sessionmaker[Session], + uk_scenario: Scenario, +) -> None: + scenario = uk_scenario + old_copy_id = _store_policy( + owner_sessions, + scenario, + scenario.parameter_value(UK_TAX_RATE, value=0.21), + scenario.parameter_value(UK_OBR_SWITCH, value=False), + ) + earlier_dynamic_id = _store_dynamic( + owner_sessions, + scenario, + scenario.parameter_value(UK_INCOME_ELASTICITY, value=0.1), + ) + _store_mapping( + owner_sessions, scenario, policy_id=old_copy_id, dynamic_id=earlier_dynamic_id + ) + + listed = _result_for( + _listing_service(listing_sessions).list_policy_copy_splits(), old_copy_id + ) + applied = _result_for( + list(_service(split_role_sessions).split_policy_copies()), old_copy_id + ) + + [listed_mapping] = listed.mappings + [applied_mapping] = applied.mappings + assert listed_mapping.previous_dynamic_id == earlier_dynamic_id + assert (listed_mapping.dynamic.id, listed_mapping.dynamic.created) == (None, True) + assert listed_mapping.dynamic.content_hash == applied_mapping.dynamic.content_hash + assert listed_mapping.dynamic.content_hash != listed.dynamic.content_hash + assert applied_mapping.dynamic.created + + +def test_a_copy_a_household_calculation_names_is_kept( + owner_sessions: sessionmaker[Session], + split_role_sessions: sessionmaker[Session], + us_scenario: Scenario, +) -> None: + scenario = us_scenario + old_copy_id = _store_policy( + owner_sessions, + scenario, + scenario.parameter_value(US_TAX_RATE, value=0.3), + scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), + ) + with owner_sessions() as session: + household = Household( + household_data={"people": {"you": {}}}, + country_id="us", + canonicalization_version=1, + content_hash=uuid4().hex * 2, + ) + session.add(household) + session.flush() + household_job = HouseholdJob( + country="us", + household_id=household.id, + year=2026, + request_data={}, + policy_id=old_copy_id, + tax_benefit_model_version_id=scenario.version_id, + country_package_version="1.0.0", + policyengine_version=CATALOG_VERSION, + ) + session.add(household_job) + session.commit() + scenario.household_ids.append(household.id) + + split = _result_for( + list(_service(split_role_sessions).split_policy_copies()), old_copy_id + ) + + assert split.outcome is PolicyCopyOutcome.KEPT + assert ( + split.references.simulations, + split.references.reports, + split.references.household_jobs, + ) == (0, 0, 1) + assert _policy_exists(owner_sessions, old_copy_id) diff --git a/tests/unit/test_split_v2_policy_copies_script.py b/tests/unit/test_split_v2_policy_copies_script.py index a22c2b898..2385b342d 100644 --- a/tests/unit/test_split_v2_policy_copies_script.py +++ b/tests/unit/test_split_v2_policy_copies_script.py @@ -321,7 +321,9 @@ def open_sessions(url): [(opener, url)] = opened assert opener == expected_opener assert url.query["connect_timeout"] == "10" - assert url.query["options"] == "-c lock_timeout=10000 -c statement_timeout=60000" + # Shorter than PostgreSQL's default one-second deadlock_timeout, so in a + # lock cycle with a live write the split's wait ends first. + assert url.query["options"] == "-c lock_timeout=500 -c statement_timeout=60000" assert url.query["sslmode"] == "require" diff --git a/tests/unit/v2/test_policy_copy_split_retries.py b/tests/unit/v2/test_policy_copy_split_retries.py new file mode 100644 index 000000000..168e6531c --- /dev/null +++ b/tests/unit/v2/test_policy_copy_split_retries.py @@ -0,0 +1,116 @@ +"""The split gives way to API v1's live writes: a copy that waits too long is retried. + +The command's lock timeout (500 ms) is shorter than PostgreSQL's default +one-second deadlock_timeout, so in a lock cycle with a live write the +split's wait ends first. The service then rolls back that copy's +transaction and tries it again, so the live write goes ahead. +""" + +from __future__ import annotations + +from contextlib import contextmanager +from typing import TYPE_CHECKING +from uuid import UUID + +import psycopg.errors +import pytest +from sqlalchemy.exc import OperationalError + +from policyengine_api.services.v2.policy_copy_split import services +from policyengine_api.services.v2.policy_copy_split.services import ( + V2PolicyCopySplitService, +) + +if TYPE_CHECKING: + from collections.abc import Iterator + +COPY_ID = UUID("00000000-0000-0000-0000-0000000d0001") +SPLIT_RESULT = object() + + +class RecordingDatabaseSession: + """Count the transactions the service opens; each yields a stand-in session.""" + + def __init__(self) -> None: + self.transactions = 0 + + @contextmanager + def read(self) -> Iterator[object]: + yield object() + + @contextmanager + def transaction(self) -> Iterator[object]: + self.transactions += 1 + yield object() + + +def _lock_error(error_type: type[Exception]) -> OperationalError: + return OperationalError("SELECT 1", {}, error_type("waited too long")) + + +@pytest.fixture +def one_copy(monkeypatch) -> None: + monkeypatch.setattr(services, "read_policy_copy_ids", lambda _session: (COPY_ID,)) + + +def _split_failing(monkeypatch, *errors: Exception) -> list[UUID]: + """Make each copy's split raise ``errors`` in turn, then succeed.""" + remaining_errors = list(errors) + attempts: list[UUID] = [] + + def split(_session: object, policy_id: UUID) -> object: + attempts.append(policy_id) + if remaining_errors: + raise remaining_errors.pop(0) + return SPLIT_RESULT + + monkeypatch.setattr(services, "split_policy_copy_in_session", split) + return attempts + + +@pytest.mark.usefixtures("one_copy") +@pytest.mark.parametrize( + "error_type", + [psycopg.errors.LockNotAvailable, psycopg.errors.DeadlockDetected], +) +def test_a_copy_that_meets_a_lock_conflict_is_tried_again( + monkeypatch, error_type: type[Exception] +) -> None: + attempts = _split_failing(monkeypatch, _lock_error(error_type)) + database_session = RecordingDatabaseSession() + waits: list[float] = [] + service = V2PolicyCopySplitService( + database_session, retry_delay_seconds=0.25, sleep=waits.append + ) + + assert list(service.split_policy_copies()) == [SPLIT_RESULT] + assert attempts == [COPY_ID, COPY_ID] + assert database_session.transactions == 2 + assert waits == [0.25] + + +@pytest.mark.usefixtures("one_copy") +def test_a_copy_still_in_conflict_after_every_attempt_fails_the_run( + monkeypatch, +) -> None: + lock_errors = [_lock_error(psycopg.errors.LockNotAvailable) for _ in range(3)] + attempts = _split_failing(monkeypatch, *lock_errors) + service = V2PolicyCopySplitService( + RecordingDatabaseSession(), attempts=3, sleep=lambda _seconds: None + ) + + with pytest.raises(OperationalError, match="waited too long"): + list(service.split_policy_copies()) + assert attempts == [COPY_ID] * 3 + + +@pytest.mark.usefixtures("one_copy") +def test_another_database_error_is_not_retried(monkeypatch) -> None: + attempts = _split_failing(monkeypatch, _lock_error(psycopg.errors.UndefinedTable)) + service = V2PolicyCopySplitService( + RecordingDatabaseSession(), sleep=lambda _seconds: None + ) + + with pytest.raises(OperationalError): + list(service.split_policy_copies()) + assert attempts == [COPY_ID] diff --git a/tests/unit/v2/test_policy_copy_split_runbook.py b/tests/unit/v2/test_policy_copy_split_runbook.py index c9d1b922d..64c2db503 100644 --- a/tests/unit/v2/test_policy_copy_split_runbook.py +++ b/tests/unit/v2/test_policy_copy_split_runbook.py @@ -67,9 +67,26 @@ def test_the_runbook_creates_a_login_role_with_no_other_powers() -> None: assert creation.lstrip().startswith("DO $$") -def test_the_runbook_drops_the_role_and_its_grants() -> None: +def test_the_runbook_revokes_every_grant_then_drops_the_role() -> None: + """A login that isn't a superuser can run it. + + ``DROP OWNED BY`` needs the target role's own privileges, which the + CREATEROLE login that created the role lacks on PostgreSQL 16 and later, + so the role's grants are revoked one by one before ``DROP ROLE``. + """ removal = _block_containing(f"DROP ROLE {POLICY_COPY_SPLIT_ROLE}") - assert f"DROP OWNED BY {POLICY_COPY_SPLIT_ROLE};" in removal - assert removal.index("DROP OWNED BY") < removal.index("DROP ROLE") + table_revoke = re.compile( + rf"^\s*REVOKE ALL ON TABLE public\.(\w+) FROM {POLICY_COPY_SPLIT_ROLE};$" + ) + revoked_tables = sorted( + match.group(1) + for statement in removal.splitlines() + if (match := table_revoke.match(statement)) + ) + + assert revoked_tables == sorted(POLICY_COPY_SPLIT_PRIVILEGES) + assert f"REVOKE USAGE ON SCHEMA public FROM {POLICY_COPY_SPLIT_ROLE};" in removal + assert "DROP OWNED BY" not in removal + assert removal.rindex("REVOKE") < removal.index("DROP ROLE") assert removal.lstrip().startswith("DO $$") diff --git a/tests/unit/v2/test_settings.py b/tests/unit/v2/test_settings.py index 65d18f9b1..0d24cad36 100644 --- a/tests/unit/v2/test_settings.py +++ b/tests/unit/v2/test_settings.py @@ -248,6 +248,21 @@ def test_runtime_rejects_transaction_pooling_without_session_timeouts() -> None: ) +def test_the_policy_copy_split_url_refuses_transaction_pooling() -> None: + """Transaction pooling drops the command's lock and statement timeouts.""" + with pytest.raises(V2ConfigurationError, match="session mode on port 5432"): + load_v2_policy_copy_split_database_settings( + { + **TARGET_ENVIRONMENT, + V2_POLICY_COPY_SPLIT_DATABASE_URL: ( + f"postgresql+psycopg://policy-copy-split.{PROJECT_REF}:password@" + "aws-0-us-east-2.pooler.supabase.com:6543/" + "postgres?sslmode=require" + ), + } + ) + + def test_supabase_database_name_must_be_postgres() -> None: with pytest.raises(V2ConfigurationError, match="configured Supabase database"): load_v2_runtime_database_settings( From 8807120074e82ddd698770782a91485bfa84b227 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:34:08 +0400 Subject: [PATCH 6/9] =?UTF-8?q?C1=20=C2=B7=2048:=20fix=20review=20round=20?= =?UTF-8?q?2's=20findings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The split gives way to API v1's live writes in a lock cycle, such as the sign-in merge: the command's lock timeout is now 500 ms, shorter than PostgreSQL's default one-second deadlock_timeout, and the service rolls a copy back and tries it again after a lock timeout or a deadlock, up to five times a second apart. - The runbook revokes each of the temporary role's grants by name, then drops it, which a login that isn't a superuser can do; DROP OWNED BY can't. - The split's URL refuses Supavisor's transaction-mode port 6543, which doesn't keep its lock and statement timeouts. - Listing and applying share one per-copy path (_split_prepared), with the listing's rows and the run's rows behind one interface, so they report the same steps. count_rows_naming_policy returns CopyReferences, and the runbook says "two null names". Co-Authored-By: Claude Opus 5.5 --- docs/migration/stage-10-v2-policies.md | 43 +- policyengine_api/data/v2/settings.py | 12 +- .../database_connectors/reads.py | 7 +- .../services/v2/policy_copy_split/services.py | 524 +++++++++++------- .../v2/policy_copy_split/validators.py | 13 + scripts/split_v2_policy_copies.py | 24 +- .../integration/test_v2_policy_copy_splits.py | 16 +- 7 files changed, 406 insertions(+), 233 deletions(-) diff --git a/docs/migration/stage-10-v2-policies.md b/docs/migration/stage-10-v2-policies.md index 084282eab..eb6a1e13f 100644 --- a/docs/migration/stage-10-v2-policies.md +++ b/docs/migration/stage-10-v2-policies.md @@ -308,7 +308,12 @@ For each such policy, in one transaction, the command legacy mappings and saved policies that name it, then the policy itself (`SELECT … FOR UPDATE`, so nothing can start naming it meanwhile), in the order API v1's copy of a v1 saved policy takes the same locks, so the two -wait for each other instead of deadlocking. It then: +wait for each other instead of deadlocking. Its lock waits end after half a +second, shorter than PostgreSQL's default one-second `deadlock_timeout`, so +in any other lock cycle with a live write, such as API v1's sign-in merge +(which locks a browser's user, then moves its saved policies), the split's +wait ends first: it rolls back that copy and tries it again, up to five +times a second apart, and the live write goes ahead. It then: - finds or creates a policy holding the values that aren't model assumptions, empty when there are none, and a dynamic holding the model assumptions, @@ -325,7 +330,7 @@ wait for each other instead of deadlocking. It then: with the saved policy's name and no description, naming the dynamic the saved policy's own v1 policy's mapping now names, or else the copy's dynamic. When the owner already has a saved dynamic in that country naming - the same dynamic with the same name (two empty names count as the same), + the same dynamic with the same name (two null names count as the same), that one is reused; - deletes the copy, and its values with it, once nothing names it. @@ -389,13 +394,26 @@ $$; ``` Deleting a policy needs no privilege on `parameter_values`: PostgreSQL runs a -foreign key's cascade as the table's owner. After the run, drop the role and -its grants: +foreign key's cascade as the table's owner. After the run, revoke each grant +and drop the role, as the login that created it. `DROP OWNED BY` would need +the role's own privileges, which a login that isn't a superuser lacks on +PostgreSQL 16 and later, so each grant is revoked by name: ```sql DO $$ BEGIN - DROP OWNED BY policyengine_v2_policy_copy_split; + REVOKE ALL ON TABLE public.dynamics FROM policyengine_v2_policy_copy_split; + REVOKE ALL ON TABLE public.household_jobs FROM policyengine_v2_policy_copy_split; + REVOKE ALL ON TABLE public.legacy_policy_mappings FROM policyengine_v2_policy_copy_split; + REVOKE ALL ON TABLE public.parameter_values FROM policyengine_v2_policy_copy_split; + REVOKE ALL ON TABLE public.parameters FROM policyengine_v2_policy_copy_split; + REVOKE ALL ON TABLE public.policies FROM policyengine_v2_policy_copy_split; + REVOKE ALL ON TABLE public.reports FROM policyengine_v2_policy_copy_split; + REVOKE ALL ON TABLE public.simulations FROM policyengine_v2_policy_copy_split; + REVOKE ALL ON TABLE public.tax_benefit_model_versions FROM policyengine_v2_policy_copy_split; + REVOKE ALL ON TABLE public.user_dynamics FROM policyengine_v2_policy_copy_split; + REVOKE ALL ON TABLE public.user_policies FROM policyengine_v2_policy_copy_split; + REVOKE USAGE ON SCHEMA public FROM policyengine_v2_policy_copy_split; DROP ROLE policyengine_v2_policy_copy_split; END $$; @@ -408,7 +426,9 @@ shell for the run only: - `V2_POLICY_COPY_SPLIT_DATABASE_URL`: the temporary role's `postgresql+psycopg://` URL with `sslmode=require` (or `verify-ca` or - `verify-full`), on the project's direct host or its pooler; + `verify-full`), on the project's direct host or its pooler in session + mode on port 5432. Transaction mode (port 6543) is refused, because it + doesn't keep the command's timeouts; - `V2_SUPABASE_PROJECT_REF` and `V2_SUPABASE_ENVIRONMENT`: the values of the GitHub Actions environment variables of the same names, which the command checks the URL against. @@ -433,9 +453,8 @@ as reused, since `--apply` commits each copy before the next. It exits with 0 when no stored policy sets a model assumption afterwards (for the listing: when every listed copy would be deleted), and with 1 otherwise. -Missing settings or a failed connection raise, and also exit with 1. The -command adds a 10-second connection timeout, a 10-second lock timeout and a -60-second statement timeout to the URL, so a wait for a lock that a live -write holds ends with an error rather than holding the copy's lock -indefinitely; the copies already reported have committed, and running the -command again carries on. +Missing settings, a failed connection, or a copy that still can't get its +locks after five attempts raise, and also exit with 1; the copies already +reported have committed, and running the command again carries on. The +command adds a 10-second connection timeout, a half-second lock timeout and +a 60-second statement timeout to the URL. diff --git a/policyengine_api/data/v2/settings.py b/policyengine_api/data/v2/settings.py index 9749e2fef..0d978a8c1 100644 --- a/policyengine_api/data/v2/settings.py +++ b/policyengine_api/data/v2/settings.py @@ -276,13 +276,23 @@ def load_v2_policy_copy_split_database_settings( The operator creates the role for the run with the grants ``privileges.POLICY_COPY_SPLIT_PRIVILEGES`` declares, and drops it after. + Supavisor's transaction-mode port is refused, as for the runtime: it + doesn't keep the command's lock and statement timeouts. """ values = _environment(environ) - return _database_settings( + settings = _database_settings( _required(values, V2_POLICY_COPY_SPLIT_DATABASE_URL), setting_name=V2_POLICY_COPY_SPLIT_DATABASE_URL, environ=values, ) + if settings.connection.url.port == SUPABASE_TRANSACTION_POOLER_PORT: + msg = ( + f"{V2_POLICY_COPY_SPLIT_DATABASE_URL} must use a direct connection or " + "Supavisor session mode on port 5432 so the command's lock and " + "statement timeouts are applied" + ) + raise V2ConfigurationError(msg) + return settings def load_v2_data_write_database_settings( diff --git a/policyengine_api/services/v2/policy_copy_split/database_connectors/reads.py b/policyengine_api/services/v2/policy_copy_split/database_connectors/reads.py index 89c90da4a..2a5cb1128 100644 --- a/policyengine_api/services/v2/policy_copy_split/database_connectors/reads.py +++ b/policyengine_api/services/v2/policy_copy_split/database_connectors/reads.py @@ -18,6 +18,7 @@ UserDynamic, UserPolicy, ) +from policyengine_api.services.v2.policy_copy_split.types import CopyReferences if TYPE_CHECKING: from collections.abc import Mapping @@ -116,7 +117,7 @@ def read_saved_policies_naming_policy( return list(session.exec(statement).all()) -def count_rows_naming_policy(session: Session, policy_id: UUID) -> tuple[int, int, int]: +def count_rows_naming_policy(session: Session, policy_id: UUID) -> CopyReferences: """Return how many simulations, reports and household jobs name the policy.""" simulations = session.exec( select(func.count()) @@ -133,7 +134,9 @@ def count_rows_naming_policy(session: Session, policy_id: UUID) -> tuple[int, in .select_from(HouseholdJob) .where(col(HouseholdJob.policy_id) == policy_id) ).one() - return simulations, reports, household_jobs + return CopyReferences( + simulations=simulations, reports=reports, household_jobs=household_jobs + ) def read_saved_dynamic_with_name( diff --git a/policyengine_api/services/v2/policy_copy_split/services.py b/policyengine_api/services/v2/policy_copy_split/services.py index e89ebb513..383032ed7 100644 --- a/policyengine_api/services/v2/policy_copy_split/services.py +++ b/policyengine_api/services/v2/policy_copy_split/services.py @@ -29,8 +29,11 @@ from __future__ import annotations +import time from dataclasses import replace -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Protocol + +from sqlalchemy.exc import OperationalError from policyengine_api.dynamic_parameters import DYNAMIC_PARAMETER_PREFIXES from policyengine_api.services.v2.dynamics.database_connectors.reads import ( @@ -66,7 +69,6 @@ split_stored_policy, ) from policyengine_api.services.v2.policy_copy_split.types import ( - CopyReferences, ListedRows, MappingTarget, PolicyCopyOutcome, @@ -80,6 +82,7 @@ ) from policyengine_api.services.v2.policy_copy_split.validators import ( PolicyCopySplitRefusedError, + is_lock_conflict, merge_dynamic_content, require_stored_row, ) @@ -91,7 +94,7 @@ from sqlmodel import Session - from policyengine_api.data.v2.models import LegacyPolicyMapping + from policyengine_api.data.v2.models import Dynamic, LegacyPolicyMapping, Policy from policyengine_api.services.v2.dynamics.types import ( ResolvedDynamicCreationInput, ) @@ -170,7 +173,6 @@ def _prepare( ) if split is None: return None - simulations, reports, household_jobs = count_rows_naming_policy(session, policy.id) prepared = PreparedPolicyCopySplit( policy_id=policy.id, country_id=policy.country_id, @@ -178,9 +180,7 @@ def _prepare( split=split, mapping_targets=(), saved_policy_targets=(), - references=CopyReferences( - simulations=simulations, reports=reports, household_jobs=household_jobs - ), + references=count_rows_naming_policy(session, policy.id), refusal_reason=None, ) mappings = read_mappings_naming_policy(session, policy.id, lock=lock) @@ -254,38 +254,128 @@ def _remaining_outcome(prepared: PreparedPolicyCopySplit) -> PolicyCopyOutcome: return PolicyCopyOutcome.DELETED -def plan_policy_copy_split( - session: Session, policy_id: UUID, listed: ListedRows | None = None -) -> PolicyCopySplit | None: - """Return what splitting one copy would change, reading only. +class _SplitRows(Protocol): + """Where one copy's split finds or puts its rows: in a listing, or for real.""" - Rows that don't exist yet have no ID. ``listed`` holds what the listing - reported for earlier copies: applying commits each copy before the next, - so a row an earlier copy creates is reused, and is reported so. Return - None when the policy is no longer stored or sets no model assumption. + def policy(self, content: ResolvedPolicyCreationInput) -> SplitContent: + """Find, or create or report as new, the policy with this content.""" + ... + + def dynamic(self, content: ResolvedDynamicCreationInput) -> SplitContent: + """Find, or create or report as new, the dynamic with this content.""" + ... + + def repoint_mapping( + self, target: MappingTarget, *, policy: SplitContent, dynamic: SplitContent + ) -> None: + """Point the mapping at the policy and dynamic.""" + ... + + def repoint_saved_policy( + self, target: SavedPolicyTarget, *, policy: SplitContent + ) -> None: + """Point the saved policy at the policy.""" + ... + + def saved_dynamic( + self, target: SavedPolicyTarget, *, dynamic: SplitContent + ) -> tuple[UUID | None, bool]: + """Give the saved policy's owner a saved dynamic naming the dynamic. + + Return the saved dynamic's ID (None when a listing would create it) + and whether it is new. + """ + ... + + def delete_copy(self, policy_id: UUID) -> None: + """Delete the copy, which nothing names any more.""" + ... + + +def _split_prepared( + prepared: PreparedPolicyCopySplit, rows: _SplitRows, *, applied: bool +) -> PolicyCopySplit: + """Carry out one copy's split through ``rows``, and say what it did. + + A listing and a run both go through here, so they report the same steps. """ - listed = ListedRows() if listed is None else listed - prepared = _prepare(session, policy_id, lock=False) - if prepared is None: - return None - if prepared.refusal_reason is not None: - return _refused(prepared, applied=False) + policy = rows.policy(prepared.split.policy) + plain_dynamic = rows.dynamic(prepared.split.dynamic) + mappings = [] + for mapping_target in prepared.mapping_targets: + dynamic = rows.dynamic(mapping_target.dynamic) + rows.repoint_mapping(mapping_target, policy=policy, dynamic=dynamic) + mappings.append( + RepointedMapping( + country_id=mapping_target.country_id, + legacy_policy_id=mapping_target.legacy_policy_id, + previous_dynamic_id=mapping_target.previous_dynamic_id, + dynamic=dynamic, + ) + ) + saved_policies = [] + for saved_policy_target in prepared.saved_policy_targets: + dynamic = rows.dynamic(saved_policy_target.dynamic) + rows.repoint_saved_policy(saved_policy_target, policy=policy) + saved_dynamic_id, saved_dynamic_created = rows.saved_dynamic( + saved_policy_target, dynamic=dynamic + ) + saved_policies.append( + RepointedSavedPolicy( + user_policy_id=saved_policy_target.user_policy_id, + dynamic=dynamic, + saved_dynamic_id=saved_dynamic_id, + saved_dynamic_created=saved_dynamic_created, + ) + ) + outcome = _remaining_outcome(prepared) + if outcome is PolicyCopyOutcome.DELETED: + rows.delete_copy(prepared.policy_id) + return PolicyCopySplit( + old_policy_id=prepared.policy_id, + country_id=prepared.country_id, + policyengine_version=prepared.policyengine_version, + applied=applied, + outcome=outcome, + policy=policy, + dynamic=plain_dynamic, + mappings=tuple(mappings), + saved_policies=tuple(saved_policies), + references=prepared.references, + refusal_reason=None, + ) + + +class _StoredRowReader(Protocol): + def __call__( + self, session: Session, *, canonicalization_version: int, content_hash: str + ) -> Policy | Dynamic | None: ... + - copy_policies: dict[str, SplitContent] = {} - copy_dynamics: dict[str, SplitContent] = {} +class _ListedSplitRows: + """Report the rows one copy's split would find or create, changing nothing. - def listed_row( + ``listed`` carries what earlier copies in the listing reported: a run + commits each copy before the next, so a later copy finds a row an + earlier one created, and is reported so. Within one copy, a row is + reported the same way each time, as a run reports it. + """ + + def __init__(self, session: Session, listed: ListedRows) -> None: + """Read through ``session``, adding to ``listed``.""" + self._session = session + self._listed = listed + self._copy_policies: dict[str, SplitContent] = {} + self._copy_dynamics: dict[str, SplitContent] = {} + + def _row( + self, content: ResolvedPolicyCreationInput, *, copy_rows: dict[str, SplitContent], run_rows: dict[str, SplitContent], - stored_id: Callable[[int, str], UUID | None], + read_stored: _StoredRowReader, ) -> SplitContent: - """Report one policy or dynamic as applying this copy would find or create it. - - Within one copy, applying reports a row the same way each time it - meets it; a later copy finds the row an earlier copy created. - """ canonical = canonicalize_policy(content) if canonical.content_hash in copy_rows: return copy_rows[canonical.content_hash] @@ -295,66 +385,57 @@ def listed_row( id=earlier.id, content_hash=canonical.content_hash, created=False ) else: - row_id = stored_id(canonical.version, canonical.content_hash) + stored = read_stored( + self._session, + canonicalization_version=canonical.version, + content_hash=canonical.content_hash, + ) row = SplitContent( - id=row_id, content_hash=canonical.content_hash, created=row_id is None + id=None if stored is None else stored.id, + content_hash=canonical.content_hash, + created=stored is None, ) run_rows[canonical.content_hash] = row copy_rows[canonical.content_hash] = row return row - def stored_policy_id( - canonicalization_version: int, content_hash: str - ) -> UUID | None: - stored = read_policy_by_content_identity( - session, - canonicalization_version=canonicalization_version, - content_hash=content_hash, - ) - return None if stored is None else stored.id - - def stored_dynamic_id( - canonicalization_version: int, content_hash: str - ) -> UUID | None: - stored = read_dynamic_by_content_identity( - session, - canonicalization_version=canonicalization_version, - content_hash=content_hash, + def policy(self, content: ResolvedPolicyCreationInput) -> SplitContent: + """Report the policy as stored, or as one this run would create.""" + return self._row( + content, + copy_rows=self._copy_policies, + run_rows=self._listed.policies, + read_stored=read_policy_by_content_identity, ) - return None if stored is None else stored.id - def listed_dynamic(content: ResolvedDynamicCreationInput) -> SplitContent: - return listed_row( + def dynamic(self, content: ResolvedDynamicCreationInput) -> SplitContent: + """Report the dynamic as stored, or as one this run would create.""" + return self._row( content, - copy_rows=copy_dynamics, - run_rows=listed.dynamics, - stored_id=stored_dynamic_id, + copy_rows=self._copy_dynamics, + run_rows=self._listed.dynamics, + read_stored=read_dynamic_by_content_identity, ) - policy = listed_row( - prepared.split.policy, - copy_rows=copy_policies, - run_rows=listed.policies, - stored_id=stored_policy_id, - ) - plain_dynamic = listed_dynamic(prepared.split.dynamic) - mappings = tuple( - RepointedMapping( - country_id=target.country_id, - legacy_policy_id=target.legacy_policy_id, - previous_dynamic_id=target.previous_dynamic_id, - dynamic=listed_dynamic(target.dynamic), - ) - for target in prepared.mapping_targets - ) - saved_policies = [] - for target in prepared.saved_policy_targets: - dynamic = listed_dynamic(target.dynamic) + def repoint_mapping( + self, target: MappingTarget, *, policy: SplitContent, dynamic: SplitContent + ) -> None: + """Change nothing: a listing only reports the mapping.""" + + def repoint_saved_policy( + self, target: SavedPolicyTarget, *, policy: SplitContent + ) -> None: + """Change nothing: a listing only reports the saved policy.""" + + def saved_dynamic( + self, target: SavedPolicyTarget, *, dynamic: SplitContent + ) -> tuple[UUID | None, bool]: + """Report the owner's identical saved dynamic, or one this run would add.""" existing = ( None if dynamic.id is None else read_saved_dynamic_with_name( - session, + self._session, user_id=target.user_id, country_id=target.country_id, dynamic_id=dynamic.id, @@ -367,155 +448,182 @@ def listed_dynamic(content: ResolvedDynamicCreationInput) -> SplitContent: dynamic_content_hash=dynamic.content_hash, name=target.name, ) - saved_policies.append( - RepointedSavedPolicy( - user_policy_id=target.user_policy_id, - dynamic=dynamic, - saved_dynamic_id=None if existing is None else existing.id, - saved_dynamic_created=existing is None - and identity not in listed.saved_dynamics, - ) - ) - listed.saved_dynamics.add(identity) - return PolicyCopySplit( - old_policy_id=prepared.policy_id, - country_id=prepared.country_id, - policyengine_version=prepared.policyengine_version, - applied=False, - outcome=_remaining_outcome(prepared), - policy=policy, - dynamic=plain_dynamic, - mappings=mappings, - saved_policies=tuple(saved_policies), - references=prepared.references, - refusal_reason=None, - ) + created = existing is None and identity not in self._listed.saved_dynamics + self._listed.saved_dynamics.add(identity) + return (None if existing is None else existing.id), created + def delete_copy(self, policy_id: UUID) -> None: + """Change nothing: a listing only reports the deletion.""" -def split_policy_copy_in_session( - session: Session, policy_id: UUID -) -> PolicyCopySplit | None: - """Split one copy in the caller's transaction, which commits it. - The copy is locked first, so nothing can start naming it before the - transaction ends. Return None when the policy is no longer stored or sets - no model assumption. Raise PolicyCopyIntegrityError, and the policy and - dynamic creation errors, for stored rows that contradict their keys. - """ - from policyengine_api.services.v2.dynamics.services import ( - create_resolved_dynamic, - ) - from policyengine_api.services.v2.policies.services import ( - create_resolved_policy, - ) - from policyengine_api.services.v2.user_dynamics.services import ( - create_user_dynamic_in_session, +def _stored_id(content: SplitContent) -> UUID: + """Return the ID of a row the run found or created; it always has one.""" + return require_stored_row( + content.id, f"the row with content {content.content_hash}" ) - prepared = _prepare(session, policy_id, lock=True) - if prepared is None: - return None - if prepared.refusal_reason is not None: - return _refused(prepared, applied=True) - stored_dynamics: dict[str, SplitContent] = {} +class _StoredSplitRows: + """Find or create one copy's rows, and change what names the copy.""" + + def __init__(self, session: Session) -> None: + """Write through ``session``, in the caller's transaction.""" + self._session = session + self._policies: dict[str, SplitContent] = {} + self._dynamics: dict[str, SplitContent] = {} + + def policy(self, content: ResolvedPolicyCreationInput) -> SplitContent: + """Find or create the policy (C1 · 36's ``create_resolved_policy``).""" + from policyengine_api.services.v2.policies.services import ( + create_resolved_policy, + ) - def stored_dynamic(content: ResolvedDynamicCreationInput) -> SplitContent: content_hash = _content_hash(content) - if content_hash not in stored_dynamics: - result = create_resolved_dynamic(session, content) - stored_dynamics[content_hash] = SplitContent( - id=result.dynamic_id, content_hash=content_hash, created=result.created + if content_hash not in self._policies: + result = create_resolved_policy(self._session, content) + self._policies[content_hash] = SplitContent( + id=result.policy_id, content_hash=content_hash, created=result.created ) - return stored_dynamics[content_hash] + return self._policies[content_hash] - policy_result = create_resolved_policy(session, prepared.split.policy) - plain_dynamic = stored_dynamic(prepared.split.dynamic) - mappings = [] - for mapping_target in prepared.mapping_targets: - dynamic = stored_dynamic(mapping_target.dynamic) - repoint_legacy_policy_mapping( - session, - mapping_target.mapping_id, - policy_id=policy_result.policy_id, - dynamic_id=require_stored_row(dynamic.id, "a stored dynamic's ID"), + def dynamic(self, content: ResolvedDynamicCreationInput) -> SplitContent: + """Find or create the dynamic (C1 · 36's ``create_resolved_dynamic``).""" + from policyengine_api.services.v2.dynamics.services import ( + create_resolved_dynamic, ) - mappings.append( - RepointedMapping( - country_id=mapping_target.country_id, - legacy_policy_id=mapping_target.legacy_policy_id, - previous_dynamic_id=mapping_target.previous_dynamic_id, - dynamic=dynamic, + + content_hash = _content_hash(content) + if content_hash not in self._dynamics: + result = create_resolved_dynamic(self._session, content) + self._dynamics[content_hash] = SplitContent( + id=result.dynamic_id, content_hash=content_hash, created=result.created ) + return self._dynamics[content_hash] + + def repoint_mapping( + self, target: MappingTarget, *, policy: SplitContent, dynamic: SplitContent + ) -> None: + """Point the mapping at the policy and dynamic.""" + repoint_legacy_policy_mapping( + self._session, + target.mapping_id, + policy_id=_stored_id(policy), + dynamic_id=_stored_id(dynamic), ) - saved_policies = [] - for saved_policy_target in prepared.saved_policy_targets: - dynamic = stored_dynamic(saved_policy_target.dynamic) - dynamic_id = require_stored_row(dynamic.id, "a stored dynamic's ID") + + def repoint_saved_policy( + self, target: SavedPolicyTarget, *, policy: SplitContent + ) -> None: + """Point the saved policy at the policy; its name and description stay.""" repoint_saved_policy( - session, - saved_policy_target.user_policy_id, - policy_id=policy_result.policy_id, + self._session, target.user_policy_id, policy_id=_stored_id(policy) + ) + + def saved_dynamic( + self, target: SavedPolicyTarget, *, dynamic: SplitContent + ) -> tuple[UUID | None, bool]: + """Give the saved policy's owner a saved dynamic naming the dynamic. + + It takes the saved policy's name and no description (C1 · 43's + ``create_user_dynamic_in_session``); an identical one the owner + already has is reused. + """ + from policyengine_api.services.v2.user_dynamics.services import ( + create_user_dynamic_in_session, ) + + dynamic_id = _stored_id(dynamic) existing = read_saved_dynamic_with_name( - session, - user_id=saved_policy_target.user_id, - country_id=saved_policy_target.country_id, + self._session, + user_id=target.user_id, + country_id=target.country_id, dynamic_id=dynamic_id, - name=saved_policy_target.name, - ) - saved_dynamic_id = ( - existing.id - if existing is not None - else create_user_dynamic_in_session( - session, - UserDynamicCreationInput.model_validate( - { - "country_id": saved_policy_target.country_id, - "user_id": saved_policy_target.user_id, - "dynamic_id": dynamic_id, - "name": saved_policy_target.name, - "description": None, - } - ), - ).id + name=target.name, ) - saved_policies.append( - RepointedSavedPolicy( - user_policy_id=saved_policy_target.user_policy_id, - dynamic=dynamic, - saved_dynamic_id=saved_dynamic_id, - saved_dynamic_created=existing is None, - ) + if existing is not None: + return existing.id, False + saved_dynamic = create_user_dynamic_in_session( + self._session, + UserDynamicCreationInput.model_validate( + { + "country_id": target.country_id, + "user_id": target.user_id, + "dynamic_id": dynamic_id, + "name": target.name, + "description": None, + } + ), ) - outcome = _remaining_outcome(prepared) - if outcome is PolicyCopyOutcome.DELETED: - delete_policy(session, prepared.policy_id) - return PolicyCopySplit( - old_policy_id=prepared.policy_id, - country_id=prepared.country_id, - policyengine_version=prepared.policyengine_version, - applied=True, - outcome=outcome, - policy=SplitContent( - id=policy_result.policy_id, - content_hash=_content_hash(prepared.split.policy), - created=policy_result.created, - ), - dynamic=plain_dynamic, - mappings=tuple(mappings), - saved_policies=tuple(saved_policies), - references=prepared.references, - refusal_reason=None, + return saved_dynamic.id, True + + def delete_copy(self, policy_id: UUID) -> None: + """Delete the copy; its values go with it.""" + delete_policy(self._session, policy_id) + + +def plan_policy_copy_split( + session: Session, policy_id: UUID, listed: ListedRows | None = None +) -> PolicyCopySplit | None: + """Return what splitting one copy would change, reading only. + + Rows that don't exist yet have no ID. ``listed`` holds what the listing + reported for earlier copies. Return None when the policy is no longer + stored or sets no model assumption. + """ + prepared = _prepare(session, policy_id, lock=False) + if prepared is None: + return None + if prepared.refusal_reason is not None: + return _refused(prepared, applied=False) + return _split_prepared( + prepared, + _ListedSplitRows(session, ListedRows() if listed is None else listed), + applied=False, ) +def split_policy_copy_in_session( + session: Session, policy_id: UUID +) -> PolicyCopySplit | None: + """Split one copy in the caller's transaction, which commits it. + + The rows it changes are locked first, so nothing can start naming the + copy before the transaction ends. Return None when the policy is no + longer stored or sets no model assumption. Raise PolicyCopyIntegrityError, + and the policy and dynamic creation errors, for stored rows that + contradict their keys. + """ + prepared = _prepare(session, policy_id, lock=True) + if prepared is None: + return None + if prepared.refusal_reason is not None: + return _refused(prepared, applied=True) + return _split_prepared(prepared, _StoredSplitRows(session), applied=True) + + class V2PolicyCopySplitService: - """List or apply the split of every stored copy, one transaction per copy.""" + """List or apply the split of every stored copy, one transaction per copy. - def __init__(self, database_session: PolicyCopySplitDatabaseSession) -> None: + A copy whose transaction meets a lock conflict (the lock timeout ran out, + or PostgreSQL found a deadlock) is rolled back and tried again, up to + ``attempts`` times, ``retry_delay_seconds`` apart. With the command's + lock timeout shorter than PostgreSQL's deadlock_timeout, the split gives + way to API v1's live writes in a lock cycle. + """ + + def __init__( + self, + database_session: PolicyCopySplitDatabaseSession, + *, + attempts: int = 5, + retry_delay_seconds: float = 1.0, + sleep: Callable[[float], None] = time.sleep, + ) -> None: """Open sessions through ``database_session``.""" self._database_session = database_session + self._attempts = attempts + self._retry_delay_seconds = retry_delay_seconds + self._sleep = sleep def list_policy_copy_splits(self) -> tuple[PolicyCopySplit, ...]: """Return what splitting every copy would change, in one read session.""" @@ -532,11 +640,27 @@ def split_policy_copies(self) -> Iterator[PolicyCopySplit]: with self._database_session.read() as session: policy_ids = read_policy_copy_ids(session) for policy_id in policy_ids: - with self._database_session.transaction() as session: - split = split_policy_copy_in_session(session, policy_id) + split = self._split_with_retries(policy_id) if split is not None: yield split + def _split_with_retries(self, policy_id: UUID) -> PolicyCopySplit | None: + """Split one copy, trying it again after a lock conflict. + + Raise the last lock conflict when every attempt meets one, and any + other database error at once. + """ + attempt = 1 + while True: + try: + with self._database_session.transaction() as session: + return split_policy_copy_in_session(session, policy_id) + except OperationalError as error: + if attempt >= self._attempts or not is_lock_conflict(error): + raise + attempt += 1 + self._sleep(self._retry_delay_seconds) + def count_policy_copies(self) -> int: """Return how many stored policies still set a model assumption.""" with self._database_session.read() as session: diff --git a/policyengine_api/services/v2/policy_copy_split/validators.py b/policyengine_api/services/v2/policy_copy_split/validators.py index e4e48b88c..cc337eabe 100644 --- a/policyengine_api/services/v2/policy_copy_split/validators.py +++ b/policyengine_api/services/v2/policy_copy_split/validators.py @@ -23,6 +23,8 @@ ) StoredRow = TypeVar("StoredRow") +# PostgreSQL's lock_not_available (a lock timeout ran out) and deadlock_detected. +LOCK_CONFLICT_SQLSTATES = frozenset({"55P03", "40P01"}) class PolicyCopySplitRefusedError(ValueError): @@ -110,3 +112,14 @@ def merge_dynamic_content( return ResolvedDynamicCreationInput.model_validate( {**dict(split_off), "parameter_values": list(merged.values())} ) + + +def is_lock_conflict(error: BaseException) -> bool: + """Return whether a database error is a lock timeout or a deadlock. + + SQLAlchemy wraps the driver's error in ``orig``, whose ``sqlstate`` names + it. A transaction that fails this way changed nothing and can be tried + again. + """ + driver_error = getattr(error, "orig", None) + return getattr(driver_error, "sqlstate", None) in LOCK_CONFLICT_SQLSTATES diff --git a/scripts/split_v2_policy_copies.py b/scripts/split_v2_policy_copies.py index 37754226d..61583ecce 100755 --- a/scripts/split_v2_policy_copies.py +++ b/scripts/split_v2_policy_copies.py @@ -19,11 +19,13 @@ It exits with 0 when, afterwards, no stored policy sets a model assumption (for the listing: when every copy would be deleted), and with 1 otherwise, such as when a copy is kept because a simulation, report or household -calculation names it, or refused. Any other failure, such as missing -settings, an unreachable database (after 10 seconds) or a lock wait of more -than 10 seconds, raises, so Python prints its traceback and also exits with -1; the copies already reported have committed, and running it again -carries on. +calculation names it, or refused. A copy that waits more than half a second +for a lock, or meets a deadlock, is rolled back and tried again, up to five +times a second apart, so the split gives way to API v1's live writes. Any +other failure, such as missing settings, an unreachable database (after 10 +seconds) or a copy that still can't get its locks, raises, so Python prints +its traceback and also exits with 1; the copies already reported have +committed, and running it again carries on. It connects as the temporary role ``policyengine_v2_policy_copy_split``, which the operator creates with the grants in @@ -60,7 +62,10 @@ CONNECT_TIMEOUT_SECONDS = 10 -LOCK_TIMEOUT_MILLISECONDS = 10_000 +# Shorter than PostgreSQL's default one-second deadlock_timeout, so in a lock +# cycle with a live write the split's wait ends first, and the service tries +# that copy again. +LOCK_TIMEOUT_MILLISECONDS = 500 STATEMENT_TIMEOUT_MILLISECONDS = 60_000 @@ -111,10 +116,9 @@ def splitter_on_temporary_role(*, writable: bool) -> Iterator[PolicyCopySplitter def with_time_limits(url: URL) -> URL: """Return the URL with a connection timeout, and lock and statement timeouts. - A lock wait then fails after a while instead of lasting indefinitely - while the split holds a copy's row lock, which blocks a live write that - names the copy. Earlier copies' transactions have committed by then, and - running the command again carries on. + A lock wait then ends after half a second instead of lasting while the + split holds a copy's locks, which a live write may be waiting for; the + service rolls that copy back and tries it again. """ time_limits = ( f"-c lock_timeout={LOCK_TIMEOUT_MILLISECONDS} " diff --git a/tests/integration/test_v2_policy_copy_splits.py b/tests/integration/test_v2_policy_copy_splits.py index 9e1034f79..c6509e3ad 100644 --- a/tests/integration/test_v2_policy_copy_splits.py +++ b/tests/integration/test_v2_policy_copy_splits.py @@ -987,8 +987,8 @@ def run_split() -> None: split_errors.append(error) split_thread = threading.Thread(target=run_split) - with owner_sessions() as live_copy: - live_copy.exec( + with owner_sessions() as live_copy_session: + live_copy_session.exec( select(LegacyPolicyMapping) .where( LegacyPolicyMapping.country_id == scenario.country_id, @@ -1006,8 +1006,8 @@ def run_split() -> None: legacy_policy_id=legacy_policy_id, name="Saved while splitting", ) - live_copy.add(saved_policy) - live_copy.commit() + live_copy_session.add(saved_policy) + live_copy_session.commit() saved_policy_id = saved_policy.id split_thread.join(timeout=60) @@ -1137,19 +1137,19 @@ def run_split() -> None: split_errors.append(error) split_thread = threading.Thread(target=run_split) - with owner_sessions() as sign_in: - sign_in.exec( + with owner_sessions() as sign_in_session: + sign_in_session.exec( select(User).where(User.id == browser_user_id).with_for_update() ).one() split_thread.start() # Give the split time to wait for the browser user's lock. time.sleep(0.3) - sign_in.execute( + sign_in_session.execute( update(UserPolicy) .where(col(UserPolicy.user_id) == browser_user_id) .values(user_id=account_user_id) ) - sign_in.commit() + sign_in_session.commit() split_thread.join(timeout=60) assert not split_thread.is_alive() From eefbbf559e77519c1d4a05d204f545ff31136d2e Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:55:27 +0400 Subject: [PATCH 7/9] =?UTF-8?q?C1=20=C2=B7=2048:=20test=20for=20review=20r?= =?UTF-8?q?ound=203's=20bug=20(failing)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When API v1's sign-in merge waits for a saved policy the split locked early, and the split joins the lock cycle more than half a second later (slow round trips between locking the copy and saving the owner's dynamic), PostgreSQL aborts the merge rather than the split. Co-Authored-By: Claude Opus 5.5 --- .../integration/test_v2_policy_copy_splits.py | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/tests/integration/test_v2_policy_copy_splits.py b/tests/integration/test_v2_policy_copy_splits.py index c6509e3ad..21d28022b 100644 --- a/tests/integration/test_v2_policy_copy_splits.py +++ b/tests/integration/test_v2_policy_copy_splits.py @@ -56,6 +56,7 @@ from policyengine_api.services.v2.dynamics.types import ResolvedDynamicCreationInput from policyengine_api.services.v2.policies.services import create_resolved_policy from policyengine_api.services.v2.policies.types import ResolvedPolicyCreationInput +from policyengine_api.services.v2.policy_copy_split import services as split_services from policyengine_api.services.v2.policy_copy_split.database_session import ( PolicyCopySplitDatabaseSession, ) @@ -1167,6 +1168,92 @@ def run_split() -> None: assert _saved_dynamics(owner_sessions, browser_user_id) == [] +def test_the_split_gives_way_to_a_sign_in_merge_that_waits_first( + owner_sessions: sessionmaker[Session], + time_limited_sessions: sessionmaker[Session], + us_scenario: Scenario, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The merge waits for the saved policy first; the split joins the cycle later. + + Re-pointing the mapping is slowed by 0.7 seconds, as a remote database's + round trips might slow the statements between locking the copy and + saving the owner's dynamic. The merge, holding the browser user's lock, + moves the saved policy meanwhile. It must commit, and the split must + give the account the saved dynamic. + """ + scenario = us_scenario + old_copy_id = _store_policy( + owner_sessions, + scenario, + scenario.parameter_value(US_TAX_RATE, value=0.3), + scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), + ) + legacy_policy_id = _store_mapping(owner_sessions, scenario, policy_id=old_copy_id) + browser_user_id = _store_user(owner_sessions, scenario) + account_user_id = _store_user(owner_sessions, scenario) + saved_policy_id = _store_saved_policy( + owner_sessions, + scenario, + user_id=browser_user_id, + policy_id=old_copy_id, + legacy_policy_id=legacy_policy_id, + name="Saved before signing in", + ) + repoint_mapping = split_services.repoint_legacy_policy_mapping + + def slow_repoint_mapping(*arguments: object, **keywords: object) -> None: + time.sleep(0.7) + repoint_mapping(*arguments, **keywords) + + monkeypatch.setattr( + split_services, "repoint_legacy_policy_mapping", slow_repoint_mapping + ) + service = V2PolicyCopySplitService( + ActingAsTheSplitRole(time_limited_sessions), + attempts=10, + retry_delay_seconds=0.2, + ) + split_results: list[PolicyCopySplit] = [] + split_errors: list[Exception] = [] + + def run_split() -> None: + try: + split_results.extend(service.split_policy_copies()) + except DBAPIError as error: + split_errors.append(error) + + split_thread = threading.Thread(target=run_split) + with owner_sessions() as sign_in_session: + sign_in_session.exec( + select(User).where(User.id == browser_user_id).with_for_update() + ).one() + split_thread.start() + # The split is re-pointing the mapping, slowly, when the merge moves + # the browser's saved policies. + time.sleep(0.15) + sign_in_session.execute( + update(UserPolicy) + .where(col(UserPolicy.user_id) == browser_user_id) + .values(user_id=account_user_id) + ) + sign_in_session.commit() + split_thread.join(timeout=60) + + assert not split_thread.is_alive() + assert split_errors == [] + split = _result_for(split_results, old_copy_id) + assert split.outcome is PolicyCopyOutcome.DELETED + with owner_sessions() as session: + saved_policy = session.get(UserPolicy, saved_policy_id) + assert (saved_policy.user_id, saved_policy.policy_id) == ( + account_user_id, + split.policy.id, + ) + [saved_dynamic] = _saved_dynamics(owner_sessions, account_user_id) + assert saved_dynamic.dynamic_id == split.dynamic.id + + def test_a_mapping_s_dynamic_on_another_catalog_version_refuses_the_copy( owner_sessions: sessionmaker[Session], split_role_sessions: sessionmaker[Session], From 9328b587d72de30296d0520b30d3ad3d0cff99b8 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:58:24 +0400 Subject: [PATCH 8/9] =?UTF-8?q?C1=20=C2=B7=2048:=20fix=20review=20round=20?= =?UTF-8?q?3's=20finding?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The split locks each saved policy naming the copy only just before saving its owner's dynamic, and reads it again then (its owner may have moved to an account at sign-in, or it may have been deleted or pointed elsewhere), instead of locking it with the mappings at the start. Its two waits in a lock cycle with a live write that locks the user first (API v1's sign-in merge, or a deletion of the user) then come within a few statements of each other, so its half-second lock timeout always ends its wait first and the live write goes ahead. The docs say five attempts in all, not five retries. Co-Authored-By: Claude Opus 5.5 --- docs/migration/stage-10-v2-policies.md | 22 +++--- .../database_connectors/reads.py | 9 +++ .../services/v2/policy_copy_split/services.py | 78 +++++++++++++++---- scripts/split_v2_policy_copies.py | 5 +- 4 files changed, 87 insertions(+), 27 deletions(-) diff --git a/docs/migration/stage-10-v2-policies.md b/docs/migration/stage-10-v2-policies.md index eb6a1e13f..0cacf86e8 100644 --- a/docs/migration/stage-10-v2-policies.md +++ b/docs/migration/stage-10-v2-policies.md @@ -305,15 +305,19 @@ otherwise change those policies silently. For each such policy, in one transaction, the command (`policyengine_api/services/v2/policy_copy_split/services.py`) locks the -legacy mappings and saved policies that name it, then the policy itself -(`SELECT … FOR UPDATE`, so nothing can start naming it meanwhile), in the -order API v1's copy of a v1 saved policy takes the same locks, so the two -wait for each other instead of deadlocking. Its lock waits end after half a -second, shorter than PostgreSQL's default one-second `deadlock_timeout`, so -in any other lock cycle with a live write, such as API v1's sign-in merge -(which locks a browser's user, then moves its saved policies), the split's -wait ends first: it rolls back that copy and tries it again, up to five -times a second apart, and the live write goes ahead. It then: +legacy mappings that name it, then the policy itself (`SELECT … FOR +UPDATE`, so nothing can start naming it meanwhile), in the order API v1's +copy of a v1 saved policy takes the same locks, so the two wait for each +other instead of deadlocking. It locks each saved policy that names the +copy only just before saving its owner's dynamic, whose foreign-key check +waits for any lock on the owner's user, so its two waits come within a few +statements of each other. Its lock waits end after half a second, shorter +than PostgreSQL's default one-second `deadlock_timeout`, so in a lock cycle +with a live write that locks the user first, such as API v1's sign-in merge +(which locks a browser's user, then moves its saved policies) or a deletion +of the user, the split's wait ends first: it rolls back that copy and tries +it again a second later, for five attempts in all, and the live write goes +ahead. It then: - finds or creates a policy holding the values that aren't model assumptions, empty when there are none, and a dynamic holding the model assumptions, diff --git a/policyengine_api/services/v2/policy_copy_split/database_connectors/reads.py b/policyengine_api/services/v2/policy_copy_split/database_connectors/reads.py index 2a5cb1128..1747db0a1 100644 --- a/policyengine_api/services/v2/policy_copy_split/database_connectors/reads.py +++ b/policyengine_api/services/v2/policy_copy_split/database_connectors/reads.py @@ -117,6 +117,15 @@ def read_saved_policies_naming_policy( return list(session.exec(statement).all()) +def read_saved_policy_for_update( + session: Session, saved_policy_id: UUID +) -> UserPolicy | None: + """Return the saved policy, selected FOR UPDATE, or None if it was deleted.""" + return session.exec( + select(UserPolicy).where(UserPolicy.id == saved_policy_id).with_for_update() + ).one_or_none() + + def count_rows_naming_policy(session: Session, policy_id: UUID) -> CopyReferences: """Return how many simulations, reports and household jobs name the policy.""" simulations = session.exec( diff --git a/policyengine_api/services/v2/policy_copy_split/services.py b/policyengine_api/services/v2/policy_copy_split/services.py index 383032ed7..8e6a9c1cd 100644 --- a/policyengine_api/services/v2/policy_copy_split/services.py +++ b/policyengine_api/services/v2/policy_copy_split/services.py @@ -60,6 +60,7 @@ read_policy_ids_setting_parameters, read_saved_dynamic_with_name, read_saved_policies_naming_policy, + read_saved_policy_for_update, ) from policyengine_api.services.v2.policy_copy_split.database_connectors.updates import ( repoint_legacy_policy_mapping, @@ -147,20 +148,21 @@ def _mapping_dynamic( def _prepare( session: Session, policy_id: UUID, *, lock: bool ) -> PreparedPolicyCopySplit | None: - """Read what the split of one copy needs, locking the rows it changes with ``lock``. + """Read what the split of one copy needs, locking the copy with ``lock``. The locks are taken in the order API v1's copies take them, so the split waits for a copy instead of deadlocking with it: the copy of a v1 saved policy locks the legacy mapping, then saves a policy naming the mapped - copy, whose foreign-key check locks the copy's row. So the mappings and - saved policies naming the copy are locked before the copy, and read - again once it is locked, since one committed meanwhile can name it and - none can be added after. Return None when the policy is no longer stored - or sets no model assumption. + copy, whose foreign-key check locks the copy's row. So the mappings + naming the copy are locked before the copy, and read again once it is + locked, since one committed meanwhile can name it and none can be added + after. The saved policies naming it are read, not locked: each is locked + only just before its owner's saved dynamic is saved + (``_StoredSplitRows.current_saved_policy``). Return None when the policy + is no longer stored or sets no model assumption. """ if lock: read_mappings_naming_policy(session, policy_id, lock=True) - read_saved_policies_naming_policy(session, policy_id, lock=True) policy = read_policy_for_split(session, policy_id, lock=lock) if policy is None: return None @@ -217,7 +219,7 @@ def _prepare( ), ) for saved_policy in read_saved_policies_naming_policy( - session, policy.id, lock=lock + session, policy.id, lock=False ) ) return replace( @@ -271,6 +273,15 @@ def repoint_mapping( """Point the mapping at the policy and dynamic.""" ... + def current_saved_policy( + self, target: SavedPolicyTarget + ) -> SavedPolicyTarget | None: + """Return the saved policy as it is now, or None if it no longer names the copy. + + A run locks it here, so its owner and name are current. + """ + ... + def repoint_saved_policy( self, target: SavedPolicyTarget, *, policy: SplitContent ) -> None: @@ -314,12 +325,21 @@ def _split_prepared( ) ) saved_policies = [] - for saved_policy_target in prepared.saved_policy_targets: - dynamic = rows.dynamic(saved_policy_target.dynamic) - rows.repoint_saved_policy(saved_policy_target, policy=policy) + for prepared_target in prepared.saved_policy_targets: + dynamic = rows.dynamic(prepared_target.dynamic) + # Lock the saved policy only now, just before saving its owner's + # dynamic, whose foreign-key check waits for any lock on the owner's + # user: the two waits then come within a few statements of each + # other, so in a lock cycle with a live write that locks the user + # first (API v1's sign-in merge, or a deletion of the user) the + # split's half-second lock timeout always ends its wait first. + saved_policy_target = rows.current_saved_policy(prepared_target) + if saved_policy_target is None: + continue saved_dynamic_id, saved_dynamic_created = rows.saved_dynamic( saved_policy_target, dynamic=dynamic ) + rows.repoint_saved_policy(saved_policy_target, policy=policy) saved_policies.append( RepointedSavedPolicy( user_policy_id=saved_policy_target.user_policy_id, @@ -422,6 +442,12 @@ def repoint_mapping( ) -> None: """Change nothing: a listing only reports the mapping.""" + def current_saved_policy( + self, target: SavedPolicyTarget + ) -> SavedPolicyTarget | None: + """Return the saved policy as the listing read it.""" + return target + def repoint_saved_policy( self, target: SavedPolicyTarget, *, policy: SplitContent ) -> None: @@ -466,9 +492,10 @@ def _stored_id(content: SplitContent) -> UUID: class _StoredSplitRows: """Find or create one copy's rows, and change what names the copy.""" - def __init__(self, session: Session) -> None: - """Write through ``session``, in the caller's transaction.""" + def __init__(self, session: Session, copy_id: UUID) -> None: + """Write through ``session``, in the caller's transaction, for one copy.""" self._session = session + self._copy_id = copy_id self._policies: dict[str, SplitContent] = {} self._dynamics: dict[str, SplitContent] = {} @@ -511,6 +538,23 @@ def repoint_mapping( dynamic_id=_stored_id(dynamic), ) + def current_saved_policy( + self, target: SavedPolicyTarget + ) -> SavedPolicyTarget | None: + """Lock the saved policy and read it again. + + Its owner may have changed since ``_prepare`` read it, as when a + browser's saved policies move to an account at sign-in, and it may + have been deleted or pointed elsewhere. The copy is locked, so no + saved policy can start naming it. + """ + saved_policy = read_saved_policy_for_update( + self._session, target.user_policy_id + ) + if saved_policy is None or saved_policy.policy_id != self._copy_id: + return None + return replace(target, user_id=saved_policy.user_id, name=saved_policy.name) + def repoint_saved_policy( self, target: SavedPolicyTarget, *, policy: SplitContent ) -> None: @@ -598,15 +642,17 @@ def split_policy_copy_in_session( return None if prepared.refusal_reason is not None: return _refused(prepared, applied=True) - return _split_prepared(prepared, _StoredSplitRows(session), applied=True) + return _split_prepared( + prepared, _StoredSplitRows(session, prepared.policy_id), applied=True + ) class V2PolicyCopySplitService: """List or apply the split of every stored copy, one transaction per copy. A copy whose transaction meets a lock conflict (the lock timeout ran out, - or PostgreSQL found a deadlock) is rolled back and tried again, up to - ``attempts`` times, ``retry_delay_seconds`` apart. With the command's + or PostgreSQL found a deadlock) is rolled back and tried again, + ``retry_delay_seconds`` apart, for ``attempts`` attempts in all. With the command's lock timeout shorter than PostgreSQL's deadlock_timeout, the split gives way to API v1's live writes in a lock cycle. """ diff --git a/scripts/split_v2_policy_copies.py b/scripts/split_v2_policy_copies.py index 61583ecce..6be2f5aa9 100755 --- a/scripts/split_v2_policy_copies.py +++ b/scripts/split_v2_policy_copies.py @@ -20,8 +20,9 @@ (for the listing: when every copy would be deleted), and with 1 otherwise, such as when a copy is kept because a simulation, report or household calculation names it, or refused. A copy that waits more than half a second -for a lock, or meets a deadlock, is rolled back and tried again, up to five -times a second apart, so the split gives way to API v1's live writes. Any +for a lock, or meets a deadlock, is rolled back and tried again a second +later, for five attempts in all, so the split gives way to API v1's live +writes. Any other failure, such as missing settings, an unreachable database (after 10 seconds) or a copy that still can't get its locks, raises, so Python prints its traceback and also exits with 1; the copies already reported have From b798285a3e851e7170ca5c15207885caca5dd280 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:33:30 +0400 Subject: [PATCH 9/9] =?UTF-8?q?C1=20=C2=B7=2048:=20cover=20the=20split's?= =?UTF-8?q?=20remaining=20branches?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codecov's report on #4345 listed lines in the new package that only concurrency or unusual rows reach. Tests now cover them: - a saved policy deleted, or pointed at another policy, after the split read it and before it locks it, which is skipped; - the listing of a refused copy, and a policy that is gone or sets no model assumption, for which listing and splitting return None; - count_policy_copies, after a run that deletes one copy and keeps one; - the refusal's message, and require_stored_row raising. read_saved_policies_naming_policy loses its lock parameter, which nothing has passed since the split began locking each saved policy on its own. The Postgres tests' row helpers move to tests/integration/ policy_copy_split_rows.py, keeping the test module under the 1,500-line limit for test code. Co-Authored-By: Claude Opus 5.5 --- .../database_connectors/reads.py | 20 +- .../services/v2/policy_copy_split/services.py | 4 +- tests/integration/policy_copy_split_rows.py | 339 ++++++++ .../integration/test_v2_policy_copy_splits.py | 733 +++++++----------- tests/unit/v2/test_policy_copy_split_rules.py | 18 + 5 files changed, 661 insertions(+), 453 deletions(-) create mode 100644 tests/integration/policy_copy_split_rows.py diff --git a/policyengine_api/services/v2/policy_copy_split/database_connectors/reads.py b/policyengine_api/services/v2/policy_copy_split/database_connectors/reads.py index 1747db0a1..b52a257cf 100644 --- a/policyengine_api/services/v2/policy_copy_split/database_connectors/reads.py +++ b/policyengine_api/services/v2/policy_copy_split/database_connectors/reads.py @@ -101,20 +101,20 @@ def read_mappings_naming_policy( def read_saved_policies_naming_policy( - session: Session, policy_id: UUID, *, lock: bool + session: Session, policy_id: UUID ) -> list[UserPolicy]: - """Return the saved policies that name the policy, oldest first. + """Return the saved policies that name the policy, oldest first, unlocked. - With ``lock``, they are selected FOR UPDATE. + The split locks each only just before saving its owner's dynamic + (``read_saved_policy_for_update``). """ - statement = ( - select(UserPolicy) - .where(UserPolicy.policy_id == policy_id) - .order_by(col(UserPolicy.created_at), col(UserPolicy.id)) + return list( + session.exec( + select(UserPolicy) + .where(UserPolicy.policy_id == policy_id) + .order_by(col(UserPolicy.created_at), col(UserPolicy.id)) + ).all() ) - if lock: - statement = statement.with_for_update() - return list(session.exec(statement).all()) def read_saved_policy_for_update( diff --git a/policyengine_api/services/v2/policy_copy_split/services.py b/policyengine_api/services/v2/policy_copy_split/services.py index 8e6a9c1cd..c34502401 100644 --- a/policyengine_api/services/v2/policy_copy_split/services.py +++ b/policyengine_api/services/v2/policy_copy_split/services.py @@ -218,9 +218,7 @@ def _prepare( ) ), ) - for saved_policy in read_saved_policies_naming_policy( - session, policy.id, lock=False - ) + for saved_policy in read_saved_policies_naming_policy(session, policy.id) ) return replace( prepared, diff --git a/tests/integration/policy_copy_split_rows.py b/tests/integration/policy_copy_split_rows.py new file mode 100644 index 000000000..d03ee16c3 --- /dev/null +++ b/tests/integration/policy_copy_split_rows.py @@ -0,0 +1,339 @@ +"""Rows for the policy copy split's PostgreSQL tests, written and removed as the owner. + +Each test's catalog has a model of its own (``Scenario``), so a test removes +only the rows it wrote, although the split reads every stored policy. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import UTC, datetime +from typing import TYPE_CHECKING +from uuid import UUID, uuid4 + +from sqlalchemy import delete, or_ +from sqlmodel import Session, col, select + +from policyengine_api.data.v2.models import ( + Dataset, + Dynamic, + Household, + HouseholdJob, + LegacyPolicyMapping, + Parameter, + ParameterValue, + Policy, + Report, + Simulation, + TaxBenefitModel, + TaxBenefitModelVersion, + User, + UserDynamic, + UserPolicy, +) +from policyengine_api.services.v2.dynamics.services import create_resolved_dynamic +from policyengine_api.services.v2.dynamics.types import ResolvedDynamicCreationInput +from policyengine_api.services.v2.policies.services import create_resolved_policy +from policyengine_api.services.v2.policies.types import ResolvedPolicyCreationInput + +if TYPE_CHECKING: + from collections.abc import Iterable + + from sqlalchemy.orm import sessionmaker + + from policyengine_api.services.v2.policy_copy_split.types import PolicyCopySplit + +CATALOG_VERSION = "6.17.1" +START_2026 = datetime(2026, 1, 1, tzinfo=UTC) +END_2026 = datetime(2026, 12, 31, tzinfo=UTC) + + +@dataclass +class Scenario: + """One test's model, catalog version and parameters, and what it stored.""" + + country_id: str + model_id: UUID + version_id: UUID + parameter_ids: dict[str, UUID] + policyengine_version: str = CATALOG_VERSION + user_ids: list[UUID] = field(default_factory=list) + legacy_policy_ids: list[int] = field(default_factory=list) + household_ids: list[UUID] = field(default_factory=list) + + def parameter_value( + self, name: str, *, value: object, end_date: datetime | None = END_2026 + ) -> dict[str, object]: + return { + "parameter_id": self.parameter_ids[name], + "value": value, + "start_date": START_2026, + "end_date": end_date, + } + + def content(self, *values: dict[str, object]) -> dict[str, object]: + return { + "country_id": self.country_id, + "tax_benefit_model_id": self.model_id, + "tax_benefit_model_version_id": self.version_id, + "policyengine_version": self.policyengine_version, + "parameter_values": list(values), + } + + +def store_catalog( + owner_sessions: sessionmaker[Session], country_id: str, names: list[str] +) -> Scenario: + with owner_sessions() as session: + model = TaxBenefitModel(name=f"split-{country_id}-{uuid4().hex[:16]}") + version = TaxBenefitModelVersion( + model=model, + version=CATALOG_VERSION, + current_law_id=1, + metadata_time_periods=[2026], + ) + parameters = [ + Parameter(name=name, tax_benefit_model_version=version) for name in names + ] + session.add_all(parameters) + session.commit() + return Scenario( + country_id=country_id, + model_id=model.id, + version_id=version.id, + parameter_ids={parameter.name: parameter.id for parameter in parameters}, + ) + + +def remove_scenario(owner_sessions: sessionmaker[Session], scenario: Scenario) -> None: + policy_ids = select(Policy.id).where( + Policy.tax_benefit_model_id == scenario.model_id + ) + dynamic_ids = select(Dynamic.id).where( + Dynamic.tax_benefit_model_id == scenario.model_id + ) + with owner_sessions() as session: + session.execute( + delete(UserDynamic).where(col(UserDynamic.dynamic_id).in_(dynamic_ids)) + ) + session.execute( + delete(UserPolicy).where(col(UserPolicy.policy_id).in_(policy_ids)) + ) + session.execute(delete(User).where(col(User.id).in_(scenario.user_ids))) + session.execute( + delete(LegacyPolicyMapping).where( + or_( + col(LegacyPolicyMapping.policy_id).in_(policy_ids), + col(LegacyPolicyMapping.dynamic_id).in_(dynamic_ids), + ) + ) + ) + session.execute( + delete(Report).where(Report.tax_benefit_model_id == scenario.model_id) + ) + session.execute( + delete(Simulation).where( + Simulation.tax_benefit_model_version_id == scenario.version_id + ) + ) + session.execute( + delete(Dataset).where( + Dataset.tax_benefit_model_version_id == scenario.version_id + ) + ) + session.execute( + delete(Policy).where(Policy.tax_benefit_model_id == scenario.model_id) + ) + session.execute( + delete(Dynamic).where(Dynamic.tax_benefit_model_id == scenario.model_id) + ) + version_ids = select(TaxBenefitModelVersion.id).where( + TaxBenefitModelVersion.model_id == scenario.model_id + ) + session.execute( + delete(HouseholdJob).where( + col(HouseholdJob.tax_benefit_model_version_id).in_(version_ids) + ) + ) + session.execute( + delete(Household).where(col(Household.id).in_(scenario.household_ids)) + ) + parameter_ids = select(Parameter.id).where( + col(Parameter.tax_benefit_model_version_id).in_(version_ids) + ) + session.execute( + delete(ParameterValue).where( + col(ParameterValue.parameter_id).in_(parameter_ids) + ) + ) + session.execute( + delete(Parameter).where( + col(Parameter.tax_benefit_model_version_id).in_(version_ids) + ) + ) + session.execute( + delete(TaxBenefitModelVersion).where( + TaxBenefitModelVersion.model_id == scenario.model_id + ) + ) + session.execute( + delete(TaxBenefitModel).where(TaxBenefitModel.id == scenario.model_id) + ) + session.commit() + + +def store_other_version( + owner_sessions: sessionmaker[Session], scenario: Scenario, names: list[str] +) -> Scenario: + """Store another catalog version of the scenario's model, with these parameters.""" + with owner_sessions() as session: + version = TaxBenefitModelVersion( + model_id=scenario.model_id, + version="6.20.0", + current_law_id=1, + metadata_time_periods=[2026], + ) + parameters = [ + Parameter(name=name, tax_benefit_model_version=version) for name in names + ] + session.add_all(parameters) + session.commit() + return Scenario( + country_id=scenario.country_id, + model_id=scenario.model_id, + version_id=version.id, + parameter_ids={parameter.name: parameter.id for parameter in parameters}, + policyengine_version="6.20.0", + ) + + +def store_policy( + owner_sessions: sessionmaker[Session], + scenario: Scenario, + *values: dict[str, object], +) -> UUID: + """Store a policy as the v1-to-v2 copy did before C1 · 36: no split.""" + with owner_sessions() as session: + result = create_resolved_policy( + session, + ResolvedPolicyCreationInput.model_validate(scenario.content(*values)), + ) + session.commit() + return result.policy_id + + +def store_dynamic( + owner_sessions: sessionmaker[Session], + scenario: Scenario, + *values: dict[str, object], +) -> UUID: + with owner_sessions() as session: + result = create_resolved_dynamic( + session, + ResolvedDynamicCreationInput.model_validate(scenario.content(*values)), + ) + session.commit() + return result.dynamic_id + + +def store_mapping( + owner_sessions: sessionmaker[Session], + scenario: Scenario, + *, + policy_id: UUID, + dynamic_id: UUID | None = None, +) -> int: + legacy_policy_id = 900_000_000 + uuid4().int % 100_000_000 + with owner_sessions() as session: + session.add( + LegacyPolicyMapping( + country_id=scenario.country_id, + legacy_policy_id=legacy_policy_id, + policy_id=policy_id, + dynamic_id=dynamic_id, + source_policy_hash=f"legacy-hash-{legacy_policy_id}", + ) + ) + session.commit() + scenario.legacy_policy_ids.append(legacy_policy_id) + return legacy_policy_id + + +def store_user(owner_sessions: sessionmaker[Session], scenario: Scenario) -> UUID: + with owner_sessions() as session: + user = User(user_type="unauthenticated") + session.add(user) + session.commit() + scenario.user_ids.append(user.id) + return user.id + + +def store_saved_policy( + owner_sessions: sessionmaker[Session], + scenario: Scenario, + **saved_policy_fields: object, +) -> UUID: + """Store a saved policy with the given user, policy, name and other fields.""" + with owner_sessions() as session: + saved_policy = UserPolicy(country_id=scenario.country_id, **saved_policy_fields) + session.add(saved_policy) + session.commit() + return saved_policy.id + + +def stored_values( + owner_sessions: sessionmaker[Session], *, policy_id=None, dynamic_id=None +) -> set: + """Each value a policy or dynamic sets: its parameter, value and end date.""" + with owner_sessions() as session: + owner_column = ( + ParameterValue.policy_id + if dynamic_id is None + else ParameterValue.dynamic_id + ) + rows = session.exec( + select(ParameterValue).where(owner_column == (policy_id or dynamic_id)) + ).all() + return {(row.parameter_id, row.value_json, row.end_date) for row in rows} + + +def stored_mapping( + owner_sessions: sessionmaker[Session], scenario: Scenario, legacy_policy_id: int +): + with owner_sessions() as session: + return session.exec( + select(LegacyPolicyMapping).where( + LegacyPolicyMapping.country_id == scenario.country_id, + LegacyPolicyMapping.legacy_policy_id == legacy_policy_id, + ) + ).one() + + +def saved_policy_target( + owner_sessions: sessionmaker[Session], saved_policy_id: UUID +) -> UUID: + with owner_sessions() as session: + return session.get(UserPolicy, saved_policy_id).policy_id + + +def saved_dynamics_of( + owner_sessions: sessionmaker[Session], user_id: UUID +) -> list[UserDynamic]: + with owner_sessions() as session: + return list( + session.exec( + select(UserDynamic) + .where(UserDynamic.user_id == user_id) + .order_by(col(UserDynamic.created_at), col(UserDynamic.id)) + ).all() + ) + + +def policy_exists(owner_sessions: sessionmaker[Session], policy_id: UUID) -> bool: + with owner_sessions() as session: + return session.get(Policy, policy_id) is not None + + +def split_for(splits: Iterable[PolicyCopySplit], policy_id: UUID) -> PolicyCopySplit: + [split] = [split for split in splits if split.old_policy_id == policy_id] + return split diff --git a/tests/integration/test_v2_policy_copy_splits.py b/tests/integration/test_v2_policy_copy_splits.py index 21d28022b..1ae9b1372 100644 --- a/tests/integration/test_v2_policy_copy_splits.py +++ b/tests/integration/test_v2_policy_copy_splits.py @@ -2,9 +2,9 @@ The command runs as the temporary role C1 · 49 creates, holding exactly ``POLICY_COPY_SPLIT_PRIVILEGES``, so a statement those grants don't allow -fails here. Rows are written and removed as the disposable database's -superuser. Each test's catalog has a model of its own, and assertions look -only at the rows the test wrote, since the command reads every stored policy. +fails here. ``tests.integration.policy_copy_split_rows`` writes and removes +the rows as the disposable database's superuser, and assertions look only at +the rows a test wrote, since the command reads every stored policy. """ from __future__ import annotations @@ -12,13 +12,11 @@ import threading import time from contextlib import contextmanager -from dataclasses import dataclass, field -from datetime import UTC, datetime from typing import TYPE_CHECKING from uuid import UUID, uuid4 import pytest -from sqlalchemy import delete, func, or_, update +from sqlalchemy import delete, func, update from sqlalchemy.engine import make_url from sqlalchemy.exc import DBAPIError from sqlmodel import Session, col, select @@ -33,15 +31,10 @@ Household, HouseholdJob, LegacyPolicyMapping, - Parameter, - ParameterValue, Policy, Report, Simulation, - TaxBenefitModel, - TaxBenefitModelVersion, User, - UserDynamic, UserPolicy, ) from policyengine_api.data.v2.privilege_reconciliation import ( @@ -52,16 +45,13 @@ POLICY_COPY_SPLIT_PRIVILEGES, POLICY_COPY_SPLIT_ROLE, ) -from policyengine_api.services.v2.dynamics.services import create_resolved_dynamic -from policyengine_api.services.v2.dynamics.types import ResolvedDynamicCreationInput -from policyengine_api.services.v2.policies.services import create_resolved_policy -from policyengine_api.services.v2.policies.types import ResolvedPolicyCreationInput from policyengine_api.services.v2.policy_copy_split import services as split_services from policyengine_api.services.v2.policy_copy_split.database_session import ( PolicyCopySplitDatabaseSession, ) from policyengine_api.services.v2.policy_copy_split.services import ( V2PolicyCopySplitService, + plan_policy_copy_split, read_policy_copy_ids, split_policy_copy_in_session, ) @@ -72,21 +62,37 @@ ) from scripts.split_v2_policy_copies import with_time_limits from tests.fixtures.database_sessions import act_as +from tests.integration.policy_copy_split_rows import ( + CATALOG_VERSION, + END_2026, + Scenario, + policy_exists, + remove_scenario, + saved_dynamics_of, + saved_policy_target, + split_for, + store_catalog, + store_dynamic, + store_mapping, + store_other_version, + store_policy, + store_saved_policy, + store_user, + stored_mapping, + stored_values, +) if TYPE_CHECKING: from collections.abc import Callable, Iterator from sqlalchemy.orm import sessionmaker -CATALOG_VERSION = "6.17.1" US_TAX_RATE = "gov.irs.income.rate" US_INCOME_ELASTICITY = "gov.simulation.labor_supply_responses.elasticities.income" US_MTR_DELTA = "simulation.marginal_tax_rate_delta" UK_TAX_RATE = "gov.hmrc.income_tax.rates.uk[0].rate" UK_INCOME_ELASTICITY = "gov.simulation.labour_supply_responses.income_elasticity" UK_OBR_SWITCH = "gov.dynamic.obr_labour_supply_assumptions" -START_2026 = datetime(2026, 1, 1, tzinfo=UTC) -END_2026 = datetime(2026, 12, 31, tzinfo=UTC) @pytest.fixture(scope="module") @@ -165,317 +171,26 @@ def _listing_service(sessions: sessionmaker[Session]) -> V2PolicyCopySplitServic return V2PolicyCopySplitService(ActingAsTheSplitRole(sessions)) -@dataclass -class Scenario: - """One test's model, catalog version and parameters, and what it stored.""" - - country_id: str - model_id: UUID - version_id: UUID - parameter_ids: dict[str, UUID] - policyengine_version: str = CATALOG_VERSION - user_ids: list[UUID] = field(default_factory=list) - legacy_policy_ids: list[int] = field(default_factory=list) - household_ids: list[UUID] = field(default_factory=list) - - def parameter_value( - self, name: str, *, value: object, end_date: datetime | None = END_2026 - ) -> dict[str, object]: - return { - "parameter_id": self.parameter_ids[name], - "value": value, - "start_date": START_2026, - "end_date": end_date, - } - - def content(self, *values: dict[str, object]) -> dict[str, object]: - return { - "country_id": self.country_id, - "tax_benefit_model_id": self.model_id, - "tax_benefit_model_version_id": self.version_id, - "policyengine_version": self.policyengine_version, - "parameter_values": list(values), - } - - -def _store_catalog( - owner_sessions: sessionmaker[Session], country_id: str, names: list[str] -) -> Scenario: - with owner_sessions() as session: - model = TaxBenefitModel(name=f"split-{country_id}-{uuid4().hex[:16]}") - version = TaxBenefitModelVersion( - model=model, - version=CATALOG_VERSION, - current_law_id=1, - metadata_time_periods=[2026], - ) - parameters = [ - Parameter(name=name, tax_benefit_model_version=version) for name in names - ] - session.add_all(parameters) - session.commit() - return Scenario( - country_id=country_id, - model_id=model.id, - version_id=version.id, - parameter_ids={parameter.name: parameter.id for parameter in parameters}, - ) - - -def _remove(owner_sessions: sessionmaker[Session], scenario: Scenario) -> None: - policy_ids = select(Policy.id).where( - Policy.tax_benefit_model_id == scenario.model_id - ) - dynamic_ids = select(Dynamic.id).where( - Dynamic.tax_benefit_model_id == scenario.model_id - ) - with owner_sessions() as session: - session.execute( - delete(UserDynamic).where(col(UserDynamic.dynamic_id).in_(dynamic_ids)) - ) - session.execute( - delete(UserPolicy).where(col(UserPolicy.policy_id).in_(policy_ids)) - ) - session.execute(delete(User).where(col(User.id).in_(scenario.user_ids))) - session.execute( - delete(LegacyPolicyMapping).where( - or_( - col(LegacyPolicyMapping.policy_id).in_(policy_ids), - col(LegacyPolicyMapping.dynamic_id).in_(dynamic_ids), - ) - ) - ) - session.execute( - delete(Report).where(Report.tax_benefit_model_id == scenario.model_id) - ) - session.execute( - delete(Simulation).where( - Simulation.tax_benefit_model_version_id == scenario.version_id - ) - ) - session.execute( - delete(Dataset).where( - Dataset.tax_benefit_model_version_id == scenario.version_id - ) - ) - session.execute( - delete(Policy).where(Policy.tax_benefit_model_id == scenario.model_id) - ) - session.execute( - delete(Dynamic).where(Dynamic.tax_benefit_model_id == scenario.model_id) - ) - version_ids = select(TaxBenefitModelVersion.id).where( - TaxBenefitModelVersion.model_id == scenario.model_id - ) - session.execute( - delete(HouseholdJob).where( - col(HouseholdJob.tax_benefit_model_version_id).in_(version_ids) - ) - ) - session.execute( - delete(Household).where(col(Household.id).in_(scenario.household_ids)) - ) - parameter_ids = select(Parameter.id).where( - col(Parameter.tax_benefit_model_version_id).in_(version_ids) - ) - session.execute( - delete(ParameterValue).where( - col(ParameterValue.parameter_id).in_(parameter_ids) - ) - ) - session.execute( - delete(Parameter).where( - col(Parameter.tax_benefit_model_version_id).in_(version_ids) - ) - ) - session.execute( - delete(TaxBenefitModelVersion).where( - TaxBenefitModelVersion.model_id == scenario.model_id - ) - ) - session.execute( - delete(TaxBenefitModel).where(TaxBenefitModel.id == scenario.model_id) - ) - session.commit() - - @pytest.fixture def us_scenario(owner_sessions: sessionmaker[Session]) -> Iterator[Scenario]: - scenario = _store_catalog( + scenario = store_catalog( owner_sessions, "us", [US_TAX_RATE, US_INCOME_ELASTICITY, US_MTR_DELTA] ) try: yield scenario finally: - _remove(owner_sessions, scenario) + remove_scenario(owner_sessions, scenario) @pytest.fixture def uk_scenario(owner_sessions: sessionmaker[Session]) -> Iterator[Scenario]: - scenario = _store_catalog( + scenario = store_catalog( owner_sessions, "uk", [UK_TAX_RATE, UK_INCOME_ELASTICITY, UK_OBR_SWITCH] ) try: yield scenario finally: - _remove(owner_sessions, scenario) - - -def _store_other_version( - owner_sessions: sessionmaker[Session], scenario: Scenario, names: list[str] -) -> Scenario: - """Store another catalog version of the scenario's model, with these parameters.""" - with owner_sessions() as session: - version = TaxBenefitModelVersion( - model_id=scenario.model_id, - version="6.20.0", - current_law_id=1, - metadata_time_periods=[2026], - ) - parameters = [ - Parameter(name=name, tax_benefit_model_version=version) for name in names - ] - session.add_all(parameters) - session.commit() - return Scenario( - country_id=scenario.country_id, - model_id=scenario.model_id, - version_id=version.id, - parameter_ids={parameter.name: parameter.id for parameter in parameters}, - policyengine_version="6.20.0", - ) - - -def _store_policy( - owner_sessions: sessionmaker[Session], - scenario: Scenario, - *values: dict[str, object], -) -> UUID: - """Store a policy as the v1-to-v2 copy did before C1 · 36: no split.""" - with owner_sessions() as session: - result = create_resolved_policy( - session, - ResolvedPolicyCreationInput.model_validate(scenario.content(*values)), - ) - session.commit() - return result.policy_id - - -def _store_dynamic( - owner_sessions: sessionmaker[Session], - scenario: Scenario, - *values: dict[str, object], -) -> UUID: - with owner_sessions() as session: - result = create_resolved_dynamic( - session, - ResolvedDynamicCreationInput.model_validate(scenario.content(*values)), - ) - session.commit() - return result.dynamic_id - - -def _store_mapping( - owner_sessions: sessionmaker[Session], - scenario: Scenario, - *, - policy_id: UUID, - dynamic_id: UUID | None = None, -) -> int: - legacy_policy_id = 900_000_000 + uuid4().int % 100_000_000 - with owner_sessions() as session: - session.add( - LegacyPolicyMapping( - country_id=scenario.country_id, - legacy_policy_id=legacy_policy_id, - policy_id=policy_id, - dynamic_id=dynamic_id, - source_policy_hash=f"legacy-hash-{legacy_policy_id}", - ) - ) - session.commit() - scenario.legacy_policy_ids.append(legacy_policy_id) - return legacy_policy_id - - -def _store_user(owner_sessions: sessionmaker[Session], scenario: Scenario) -> UUID: - with owner_sessions() as session: - user = User(user_type="unauthenticated") - session.add(user) - session.commit() - scenario.user_ids.append(user.id) - return user.id - - -def _store_saved_policy( - owner_sessions: sessionmaker[Session], - scenario: Scenario, - **saved_policy_fields: object, -) -> UUID: - """Store a saved policy with the given user, policy, name and other fields.""" - with owner_sessions() as session: - saved_policy = UserPolicy(country_id=scenario.country_id, **saved_policy_fields) - session.add(saved_policy) - session.commit() - return saved_policy.id - - -def _values( - owner_sessions: sessionmaker[Session], *, policy_id=None, dynamic_id=None -) -> set: - """Each value a policy or dynamic sets: its parameter, value and end date.""" - with owner_sessions() as session: - owner_column = ( - ParameterValue.policy_id - if dynamic_id is None - else ParameterValue.dynamic_id - ) - rows = session.exec( - select(ParameterValue).where(owner_column == (policy_id or dynamic_id)) - ).all() - return {(row.parameter_id, row.value_json, row.end_date) for row in rows} - - -def _mapping( - owner_sessions: sessionmaker[Session], scenario: Scenario, legacy_policy_id: int -): - with owner_sessions() as session: - return session.exec( - select(LegacyPolicyMapping).where( - LegacyPolicyMapping.country_id == scenario.country_id, - LegacyPolicyMapping.legacy_policy_id == legacy_policy_id, - ) - ).one() - - -def _saved_policy_target( - owner_sessions: sessionmaker[Session], saved_policy_id: UUID -) -> UUID: - with owner_sessions() as session: - return session.get(UserPolicy, saved_policy_id).policy_id - - -def _saved_dynamics( - owner_sessions: sessionmaker[Session], user_id: UUID -) -> list[UserDynamic]: - with owner_sessions() as session: - return list( - session.exec( - select(UserDynamic) - .where(UserDynamic.user_id == user_id) - .order_by(col(UserDynamic.created_at), col(UserDynamic.id)) - ).all() - ) - - -def _policy_exists(owner_sessions: sessionmaker[Session], policy_id: UUID) -> bool: - with owner_sessions() as session: - return session.get(Policy, policy_id) is not None - - -def _result_for(splits, policy_id: UUID) -> PolicyCopySplit: - [split] = [split for split in splits if split.old_policy_id == policy_id] - return split + remove_scenario(owner_sessions, scenario) def test_a_us_copy_is_split_re_pointed_given_a_saved_dynamic_and_deleted( @@ -484,16 +199,16 @@ def test_a_us_copy_is_split_re_pointed_given_a_saved_dynamic_and_deleted( us_scenario: Scenario, ) -> None: scenario = us_scenario - old_copy_id = _store_policy( + old_copy_id = store_policy( owner_sessions, scenario, scenario.parameter_value(US_TAX_RATE, value=0.3), scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), scenario.parameter_value(US_MTR_DELTA, value=0.01, end_date=None), ) - legacy_policy_id = _store_mapping(owner_sessions, scenario, policy_id=old_copy_id) - user_id = _store_user(owner_sessions, scenario) - saved_policy_id = _store_saved_policy( + legacy_policy_id = store_mapping(owner_sessions, scenario, policy_id=old_copy_id) + user_id = store_user(owner_sessions, scenario) + saved_policy_id = store_saved_policy( owner_sessions, scenario, user_id=user_id, @@ -503,7 +218,7 @@ def test_a_us_copy_is_split_re_pointed_given_a_saved_dynamic_and_deleted( description="Raises the rate, with labour supply responses", ) - split = _result_for( + split = split_for( list(_service(split_role_sessions).split_policy_copies()), old_copy_id ) @@ -516,23 +231,23 @@ def test_a_us_copy_is_split_re_pointed_given_a_saved_dynamic_and_deleted( assert split.dynamic is not None assert split.dynamic.created new_policy_id, new_dynamic_id = split.policy.id, split.dynamic.id - assert not _policy_exists(owner_sessions, old_copy_id) - assert _values(owner_sessions, policy_id=old_copy_id) == set() - assert _values(owner_sessions, policy_id=new_policy_id) == { + assert not policy_exists(owner_sessions, old_copy_id) + assert stored_values(owner_sessions, policy_id=old_copy_id) == set() + assert stored_values(owner_sessions, policy_id=new_policy_id) == { (scenario.parameter_ids[US_TAX_RATE], 0.3, END_2026) } - assert _values(owner_sessions, dynamic_id=new_dynamic_id) == { + assert stored_values(owner_sessions, dynamic_id=new_dynamic_id) == { (scenario.parameter_ids[US_INCOME_ELASTICITY], 0.25, END_2026), (scenario.parameter_ids[US_MTR_DELTA], 0.01, None), } - mapping = _mapping(owner_sessions, scenario, legacy_policy_id) + mapping = stored_mapping(owner_sessions, scenario, legacy_policy_id) assert (mapping.policy_id, mapping.dynamic_id) == (new_policy_id, new_dynamic_id) [repointed_mapping] = split.mappings assert repointed_mapping.legacy_policy_id == legacy_policy_id assert repointed_mapping.previous_dynamic_id is None assert repointed_mapping.dynamic.id == new_dynamic_id - assert _saved_policy_target(owner_sessions, saved_policy_id) == new_policy_id - [saved_dynamic] = _saved_dynamics(owner_sessions, user_id) + assert saved_policy_target(owner_sessions, saved_policy_id) == new_policy_id + [saved_dynamic] = saved_dynamics_of(owner_sessions, user_id) assert (saved_dynamic.dynamic_id, saved_dynamic.country_id) == ( new_dynamic_id, "us", @@ -548,13 +263,13 @@ def test_a_us_copy_is_split_re_pointed_given_a_saved_dynamic_and_deleted( second_run = list(_service(split_role_sessions).split_policy_copies()) assert old_copy_id not in {split.old_policy_id for split in second_run} - mapping_after = _mapping(owner_sessions, scenario, legacy_policy_id) + mapping_after = stored_mapping(owner_sessions, scenario, legacy_policy_id) assert (mapping_after.policy_id, mapping_after.dynamic_id) == ( new_policy_id, new_dynamic_id, ) - assert _saved_policy_target(owner_sessions, saved_policy_id) == new_policy_id - assert [row.id for row in _saved_dynamics(owner_sessions, user_id)] == [ + assert saved_policy_target(owner_sessions, saved_policy_id) == new_policy_id + assert [row.id for row in saved_dynamics_of(owner_sessions, user_id)] == [ saved_dynamic.id ] @@ -565,26 +280,26 @@ def test_a_uk_copy_of_only_model_assumptions_points_at_an_empty_policy( uk_scenario: Scenario, ) -> None: scenario = uk_scenario - old_copy_id = _store_policy( + old_copy_id = store_policy( owner_sessions, scenario, scenario.parameter_value(UK_OBR_SWITCH, value=False) ) - legacy_policy_id = _store_mapping(owner_sessions, scenario, policy_id=old_copy_id) + legacy_policy_id = store_mapping(owner_sessions, scenario, policy_id=old_copy_id) - split = _result_for( + split = split_for( list(_service(split_role_sessions).split_policy_copies()), old_copy_id ) assert split.outcome is PolicyCopyOutcome.DELETED - mapping = _mapping(owner_sessions, scenario, legacy_policy_id) + mapping = stored_mapping(owner_sessions, scenario, legacy_policy_id) assert mapping.policy_id == split.policy.id - assert _values(owner_sessions, policy_id=mapping.policy_id) == set() + assert stored_values(owner_sessions, policy_id=mapping.policy_id) == set() with owner_sessions() as session: empty_policy = session.get(Policy, mapping.policy_id) assert empty_policy.tax_benefit_model_version_id == scenario.version_id - assert _values(owner_sessions, dynamic_id=mapping.dynamic_id) == { + assert stored_values(owner_sessions, dynamic_id=mapping.dynamic_id) == { (scenario.parameter_ids[UK_OBR_SWITCH], False, END_2026) } - assert not _policy_exists(owner_sessions, old_copy_id) + assert not policy_exists(owner_sessions, old_copy_id) def test_a_mapping_that_already_names_a_dynamic_gets_one_merged_dynamic( @@ -593,22 +308,22 @@ def test_a_mapping_that_already_names_a_dynamic_gets_one_merged_dynamic( uk_scenario: Scenario, ) -> None: scenario = uk_scenario - old_copy_id = _store_policy( + old_copy_id = store_policy( owner_sessions, scenario, scenario.parameter_value(UK_TAX_RATE, value=0.21), scenario.parameter_value(UK_OBR_SWITCH, value=False), ) - earlier_dynamic_id = _store_dynamic( + earlier_dynamic_id = store_dynamic( owner_sessions, scenario, scenario.parameter_value(UK_INCOME_ELASTICITY, value=0.1), ) - legacy_policy_id = _store_mapping( + legacy_policy_id = store_mapping( owner_sessions, scenario, policy_id=old_copy_id, dynamic_id=earlier_dynamic_id ) - user_id = _store_user(owner_sessions, scenario) - mapped_saved_policy_id = _store_saved_policy( + user_id = store_user(owner_sessions, scenario) + mapped_saved_policy_id = store_saved_policy( owner_sessions, scenario, user_id=user_id, @@ -616,43 +331,41 @@ def test_a_mapping_that_already_names_a_dynamic_gets_one_merged_dynamic( name="Copied from v1", legacy_policy_id=legacy_policy_id, ) - native_saved_policy_id = _store_saved_policy( + native_saved_policy_id = store_saved_policy( owner_sessions, scenario, user_id=user_id, policy_id=old_copy_id, name="Native" ) - split = _result_for( + split = split_for( list(_service(split_role_sessions).split_policy_copies()), old_copy_id ) assert split.outcome is PolicyCopyOutcome.DELETED - mapping = _mapping(owner_sessions, scenario, legacy_policy_id) + mapping = stored_mapping(owner_sessions, scenario, legacy_policy_id) assert mapping.policy_id == split.policy.id - assert _values(owner_sessions, policy_id=mapping.policy_id) == { + assert stored_values(owner_sessions, policy_id=mapping.policy_id) == { (scenario.parameter_ids[UK_TAX_RATE], 0.21, END_2026) } merged_dynamic_id = mapping.dynamic_id assert merged_dynamic_id not in {earlier_dynamic_id, split.dynamic.id} - assert _values(owner_sessions, dynamic_id=merged_dynamic_id) == { + assert stored_values(owner_sessions, dynamic_id=merged_dynamic_id) == { (scenario.parameter_ids[UK_INCOME_ELASTICITY], 0.1, END_2026), (scenario.parameter_ids[UK_OBR_SWITCH], False, END_2026), } - assert _values(owner_sessions, dynamic_id=split.dynamic.id) == { + assert stored_values(owner_sessions, dynamic_id=split.dynamic.id) == { (scenario.parameter_ids[UK_OBR_SWITCH], False, END_2026) } [repointed_mapping] = split.mappings assert repointed_mapping.previous_dynamic_id == earlier_dynamic_id assert repointed_mapping.dynamic.id == merged_dynamic_id saved_dynamics = { - row.name: row.dynamic_id for row in _saved_dynamics(owner_sessions, user_id) + row.name: row.dynamic_id for row in saved_dynamics_of(owner_sessions, user_id) } assert saved_dynamics == { "Copied from v1": merged_dynamic_id, "Native": split.dynamic.id, } for saved_policy_id in (mapped_saved_policy_id, native_saved_policy_id): - assert ( - _saved_policy_target(owner_sessions, saved_policy_id) == mapping.policy_id - ) + assert saved_policy_target(owner_sessions, saved_policy_id) == mapping.policy_id with owner_sessions() as session: assert session.get(Dynamic, earlier_dynamic_id) is not None @@ -663,15 +376,15 @@ def test_a_copy_a_report_names_is_split_and_re_pointed_but_kept( us_scenario: Scenario, ) -> None: scenario = us_scenario - old_copy_id = _store_policy( + old_copy_id = store_policy( owner_sessions, scenario, scenario.parameter_value(US_TAX_RATE, value=0.3), scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), ) - legacy_policy_id = _store_mapping(owner_sessions, scenario, policy_id=old_copy_id) - user_id = _store_user(owner_sessions, scenario) - saved_policy_id = _store_saved_policy( + legacy_policy_id = store_mapping(owner_sessions, scenario, policy_id=old_copy_id) + user_id = store_user(owner_sessions, scenario) + saved_policy_id = store_saved_policy( owner_sessions, scenario, user_id=user_id, policy_id=old_copy_id, name="Kept" ) with owner_sessions() as session: @@ -684,7 +397,7 @@ def test_a_copy_a_report_names_is_split_and_re_pointed_but_kept( session.commit() report_id = report.id - split = _result_for( + split = split_for( list(_service(split_role_sessions).split_policy_copies()), old_copy_id ) @@ -694,28 +407,28 @@ def test_a_copy_a_report_names_is_split_and_re_pointed_but_kept( split.references.reports, split.references.household_jobs, ) == (0, 1, 0) - assert _policy_exists(owner_sessions, old_copy_id) - assert len(_values(owner_sessions, policy_id=old_copy_id)) == 2 + assert policy_exists(owner_sessions, old_copy_id) + assert len(stored_values(owner_sessions, policy_id=old_copy_id)) == 2 with owner_sessions() as session: assert session.get(Report, report_id).policy_id == old_copy_id - mapping = _mapping(owner_sessions, scenario, legacy_policy_id) + mapping = stored_mapping(owner_sessions, scenario, legacy_policy_id) assert (mapping.policy_id, mapping.dynamic_id) == ( split.policy.id, split.dynamic.id, ) - assert _saved_policy_target(owner_sessions, saved_policy_id) == split.policy.id - [saved_dynamic] = _saved_dynamics(owner_sessions, user_id) + assert saved_policy_target(owner_sessions, saved_policy_id) == split.policy.id + [saved_dynamic] = saved_dynamics_of(owner_sessions, user_id) with split_role_sessions() as session: assert old_copy_id in read_policy_copy_ids(session) - second_split = _result_for( + second_split = split_for( list(_service(split_role_sessions).split_policy_copies()), old_copy_id ) assert second_split.outcome is PolicyCopyOutcome.KEPT assert second_split.mappings == () assert second_split.saved_policies == () - assert [row.id for row in _saved_dynamics(owner_sessions, user_id)] == [ + assert [row.id for row in saved_dynamics_of(owner_sessions, user_id)] == [ saved_dynamic.id ] with owner_sessions() as session: @@ -729,22 +442,22 @@ def test_a_conflicting_merge_refuses_the_copy_and_changes_nothing( uk_scenario: Scenario, ) -> None: scenario = uk_scenario - old_copy_id = _store_policy( + old_copy_id = store_policy( owner_sessions, scenario, scenario.parameter_value(UK_TAX_RATE, value=0.21), scenario.parameter_value(UK_INCOME_ELASTICITY, value=0.2), ) - earlier_dynamic_id = _store_dynamic( + earlier_dynamic_id = store_dynamic( owner_sessions, scenario, scenario.parameter_value(UK_INCOME_ELASTICITY, value=0.1), ) - legacy_policy_id = _store_mapping( + legacy_policy_id = store_mapping( owner_sessions, scenario, policy_id=old_copy_id, dynamic_id=earlier_dynamic_id ) - user_id = _store_user(owner_sessions, scenario) - saved_policy_id = _store_saved_policy( + user_id = store_user(owner_sessions, scenario) + saved_policy_id = store_saved_policy( owner_sessions, scenario, user_id=user_id, @@ -753,17 +466,17 @@ def test_a_conflicting_merge_refuses_the_copy_and_changes_nothing( legacy_policy_id=legacy_policy_id, ) - split = _result_for( + split = split_for( list(_service(split_role_sessions).split_policy_copies()), old_copy_id ) assert split.outcome is PolicyCopyOutcome.REFUSED assert split.refusal_reason is PolicyCopyRefusalReason.CONFLICTING_DYNAMIC_VALUES - assert _policy_exists(owner_sessions, old_copy_id) - mapping = _mapping(owner_sessions, scenario, legacy_policy_id) + assert policy_exists(owner_sessions, old_copy_id) + mapping = stored_mapping(owner_sessions, scenario, legacy_policy_id) assert (mapping.policy_id, mapping.dynamic_id) == (old_copy_id, earlier_dynamic_id) - assert _saved_policy_target(owner_sessions, saved_policy_id) == old_copy_id - assert _saved_dynamics(owner_sessions, user_id) == [] + assert saved_policy_target(owner_sessions, saved_policy_id) == old_copy_id + assert saved_dynamics_of(owner_sessions, user_id) == [] with owner_sessions() as session: stored = session.exec( select(Policy.id).where(Policy.tax_benefit_model_id == scenario.model_id) @@ -782,22 +495,22 @@ def test_the_listing_reads_only_and_reports_what_would_change( listing_sessions: sessionmaker[Session], ) -> None: scenario = us_scenario - stored_policy_part_id = _store_policy( + stored_policy_part_id = store_policy( owner_sessions, scenario, scenario.parameter_value(US_TAX_RATE, value=0.3) ) - old_copy_id = _store_policy( + old_copy_id = store_policy( owner_sessions, scenario, scenario.parameter_value(US_TAX_RATE, value=0.3), scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), ) - legacy_policy_id = _store_mapping(owner_sessions, scenario, policy_id=old_copy_id) - user_id = _store_user(owner_sessions, scenario) - saved_policy_id = _store_saved_policy( + legacy_policy_id = store_mapping(owner_sessions, scenario, policy_id=old_copy_id) + user_id = store_user(owner_sessions, scenario) + saved_policy_id = store_saved_policy( owner_sessions, scenario, user_id=user_id, policy_id=old_copy_id, name="Listed" ) - split = _result_for( + split = split_for( _listing_service(listing_sessions).list_policy_copy_splits(), old_copy_id, ) @@ -813,11 +526,11 @@ def test_the_listing_reads_only_and_reports_what_would_change( assert listed_saved_policy.user_policy_id == saved_policy_id assert listed_saved_policy.saved_dynamic_id is None assert listed_saved_policy.saved_dynamic_created - assert _policy_exists(owner_sessions, old_copy_id) - mapping = _mapping(owner_sessions, scenario, legacy_policy_id) + assert policy_exists(owner_sessions, old_copy_id) + mapping = stored_mapping(owner_sessions, scenario, legacy_policy_id) assert (mapping.policy_id, mapping.dynamic_id) == (old_copy_id, None) - assert _saved_policy_target(owner_sessions, saved_policy_id) == old_copy_id - assert _saved_dynamics(owner_sessions, user_id) == [] + assert saved_policy_target(owner_sessions, saved_policy_id) == old_copy_id + assert saved_dynamics_of(owner_sessions, user_id) == [] with owner_sessions() as session: dynamics = session.exec( select(Dynamic.id).where(Dynamic.tax_benefit_model_id == scenario.model_id) @@ -831,21 +544,21 @@ def test_an_identical_saved_dynamic_is_reused_and_another_name_gets_its_own( us_scenario: Scenario, ) -> None: scenario = us_scenario - old_copy_id = _store_policy( + old_copy_id = store_policy( owner_sessions, scenario, scenario.parameter_value(US_TAX_RATE, value=0.3), scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), ) - user_id = _store_user(owner_sessions, scenario) + user_id = store_user(owner_sessions, scenario) first_id, second_id, other_id, unnamed_id, also_unnamed_id = ( - _store_saved_policy( + store_saved_policy( owner_sessions, scenario, user_id=user_id, policy_id=old_copy_id, name=name ) for name in ("Reform A", "Reform A", "Reform B", None, None) ) - split = _result_for( + split = split_for( list(_service(split_role_sessions).split_policy_copies()), old_copy_id ) @@ -862,7 +575,7 @@ def test_an_identical_saved_dynamic_is_reused_and_another_name_gets_its_own( assert by_saved_policy[unnamed_id].saved_dynamic_created assert not by_saved_policy[also_unnamed_id].saved_dynamic_created assert sorted( - (row.name or "") for row in _saved_dynamics(owner_sessions, user_id) + (row.name or "") for row in saved_dynamics_of(owner_sessions, user_id) ) == ["", "Reform A", "Reform B"] @@ -872,16 +585,16 @@ def test_policies_setting_no_model_assumption_are_left_alone( us_scenario: Scenario, ) -> None: scenario = us_scenario - policy_id = _store_policy( + policy_id = store_policy( owner_sessions, scenario, scenario.parameter_value(US_TAX_RATE, value=0.3) ) - legacy_policy_id = _store_mapping(owner_sessions, scenario, policy_id=policy_id) + legacy_policy_id = store_mapping(owner_sessions, scenario, policy_id=policy_id) splits = list(_service(split_role_sessions).split_policy_copies()) assert policy_id not in {split.old_policy_id for split in splits} - assert _policy_exists(owner_sessions, policy_id) - assert _mapping(owner_sessions, scenario, legacy_policy_id).dynamic_id is None + assert policy_exists(owner_sessions, policy_id) + assert stored_mapping(owner_sessions, scenario, legacy_policy_id).dynamic_id is None def test_one_copy_splits_in_a_caller_owned_transaction( @@ -891,13 +604,13 @@ def test_one_copy_splits_in_a_caller_owned_transaction( ) -> None: """D4 · 1's migration reuses the split in a transaction of its own.""" scenario = uk_scenario - old_copy_id = _store_policy( + old_copy_id = store_policy( owner_sessions, scenario, scenario.parameter_value(UK_TAX_RATE, value=0.21), scenario.parameter_value(UK_OBR_SWITCH, value=False), ) - legacy_policy_id = _store_mapping(owner_sessions, scenario, policy_id=old_copy_id) + legacy_policy_id = store_mapping(owner_sessions, scenario, policy_id=old_copy_id) with split_role_sessions() as session: split = split_policy_copy_in_session(session, old_copy_id) @@ -905,8 +618,11 @@ def test_one_copy_splits_in_a_caller_owned_transaction( assert split is not None assert split.outcome is PolicyCopyOutcome.DELETED - assert _policy_exists(owner_sessions, old_copy_id) - assert _mapping(owner_sessions, scenario, legacy_policy_id).policy_id == old_copy_id + assert policy_exists(owner_sessions, old_copy_id) + assert ( + stored_mapping(owner_sessions, scenario, legacy_policy_id).policy_id + == old_copy_id + ) with split_role_sessions() as session: assert split_policy_copy_in_session(session, uuid4()) is None @@ -918,7 +634,7 @@ def test_a_copy_a_simulation_names_is_kept( us_scenario: Scenario, ) -> None: scenario = us_scenario - old_copy_id = _store_policy( + old_copy_id = store_policy( owner_sessions, scenario, scenario.parameter_value(US_TAX_RATE, value=0.3), @@ -942,7 +658,7 @@ def test_a_copy_a_simulation_names_is_kept( session.commit() simulation_id = simulation.id - split = _result_for( + split = split_for( list(_service(split_role_sessions).split_policy_copies()), old_copy_id ) @@ -952,7 +668,7 @@ def test_a_copy_a_simulation_names_is_kept( split.references.reports, split.references.household_jobs, ) == (1, 0, 0) - assert _policy_exists(owner_sessions, old_copy_id) + assert policy_exists(owner_sessions, old_copy_id) with owner_sessions() as session: assert session.get(Simulation, simulation_id).policy_id == old_copy_id @@ -970,14 +686,14 @@ def test_the_split_waits_for_a_live_saved_policy_copy_instead_of_deadlocking( commit, and then re-points the saved policy the copy added. """ scenario = us_scenario - old_copy_id = _store_policy( + old_copy_id = store_policy( owner_sessions, scenario, scenario.parameter_value(US_TAX_RATE, value=0.3), scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), ) - legacy_policy_id = _store_mapping(owner_sessions, scenario, policy_id=old_copy_id) - user_id = _store_user(owner_sessions, scenario) + legacy_policy_id = store_mapping(owner_sessions, scenario, policy_id=old_copy_id) + user_id = store_user(owner_sessions, scenario) split_results: list[PolicyCopySplit] = [] split_errors: list[Exception] = [] @@ -1014,13 +730,13 @@ def run_split() -> None: assert not split_thread.is_alive() assert split_errors == [] - split = _result_for(split_results, old_copy_id) + split = split_for(split_results, old_copy_id) assert split.outcome is PolicyCopyOutcome.DELETED assert [repointed.user_policy_id for repointed in split.saved_policies] == [ saved_policy_id ] - assert _saved_policy_target(owner_sessions, saved_policy_id) == split.policy.id - assert not _policy_exists(owner_sessions, old_copy_id) + assert saved_policy_target(owner_sessions, saved_policy_id) == split.policy.id + assert not policy_exists(owner_sessions, old_copy_id) def test_the_listing_reports_rows_an_earlier_copy_creates_as_reused( @@ -1036,7 +752,7 @@ def test_the_listing_reports_rows_an_earlier_copy_creates_as_reused( """ scenario = uk_scenario copy_ids = [ - _store_policy( + store_policy( owner_sessions, scenario, scenario.parameter_value(UK_TAX_RATE, value=tax_rate), @@ -1044,9 +760,9 @@ def test_the_listing_reports_rows_an_earlier_copy_creates_as_reused( ) for tax_rate in (0.21, 0.22) ] - user_id = _store_user(owner_sessions, scenario) + user_id = store_user(owner_sessions, scenario) for copy_id in copy_ids: - _store_saved_policy( + store_saved_policy( owner_sessions, scenario, user_id=user_id, policy_id=copy_id, name=None ) @@ -1060,14 +776,14 @@ def created_rows(split: PolicyCopySplit) -> tuple[bool, bool, list[bool]]: [saved.saved_dynamic_created for saved in split.saved_policies], ) - assert [created_rows(_result_for(listed, copy_id)) for copy_id in copy_ids] == [ + assert [created_rows(split_for(listed, copy_id)) for copy_id in copy_ids] == [ (True, True, [True]), (True, False, [False]), ] - assert [created_rows(_result_for(applied, copy_id)) for copy_id in copy_ids] == [ - created_rows(_result_for(listed, copy_id)) for copy_id in copy_ids + assert [created_rows(split_for(applied, copy_id)) for copy_id in copy_ids] == [ + created_rows(split_for(listed, copy_id)) for copy_id in copy_ids ] - assert len(_saved_dynamics(owner_sessions, user_id)) == 1 + assert len(saved_dynamics_of(owner_sessions, user_id)) == 1 def test_the_listing_s_sessions_refuse_writes(disposable_v2_database_url: str) -> None: @@ -1108,15 +824,15 @@ def test_the_split_gives_way_to_a_live_sign_in_merge( tries the copy again, for the account the saved policy now belongs to. """ scenario = us_scenario - old_copy_id = _store_policy( + old_copy_id = store_policy( owner_sessions, scenario, scenario.parameter_value(US_TAX_RATE, value=0.3), scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), ) - browser_user_id = _store_user(owner_sessions, scenario) - account_user_id = _store_user(owner_sessions, scenario) - saved_policy_id = _store_saved_policy( + browser_user_id = store_user(owner_sessions, scenario) + account_user_id = store_user(owner_sessions, scenario) + saved_policy_id = store_saved_policy( owner_sessions, scenario, user_id=browser_user_id, @@ -1155,7 +871,7 @@ def run_split() -> None: assert not split_thread.is_alive() assert split_errors == [] - split = _result_for(split_results, old_copy_id) + split = split_for(split_results, old_copy_id) assert split.outcome is PolicyCopyOutcome.DELETED with owner_sessions() as session: saved_policy = session.get(UserPolicy, saved_policy_id) @@ -1163,9 +879,9 @@ def run_split() -> None: account_user_id, split.policy.id, ) - [saved_dynamic] = _saved_dynamics(owner_sessions, account_user_id) + [saved_dynamic] = saved_dynamics_of(owner_sessions, account_user_id) assert saved_dynamic.dynamic_id == split.dynamic.id - assert _saved_dynamics(owner_sessions, browser_user_id) == [] + assert saved_dynamics_of(owner_sessions, browser_user_id) == [] def test_the_split_gives_way_to_a_sign_in_merge_that_waits_first( @@ -1183,16 +899,16 @@ def test_the_split_gives_way_to_a_sign_in_merge_that_waits_first( give the account the saved dynamic. """ scenario = us_scenario - old_copy_id = _store_policy( + old_copy_id = store_policy( owner_sessions, scenario, scenario.parameter_value(US_TAX_RATE, value=0.3), scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), ) - legacy_policy_id = _store_mapping(owner_sessions, scenario, policy_id=old_copy_id) - browser_user_id = _store_user(owner_sessions, scenario) - account_user_id = _store_user(owner_sessions, scenario) - saved_policy_id = _store_saved_policy( + legacy_policy_id = store_mapping(owner_sessions, scenario, policy_id=old_copy_id) + browser_user_id = store_user(owner_sessions, scenario) + account_user_id = store_user(owner_sessions, scenario) + saved_policy_id = store_saved_policy( owner_sessions, scenario, user_id=browser_user_id, @@ -1242,7 +958,7 @@ def run_split() -> None: assert not split_thread.is_alive() assert split_errors == [] - split = _result_for(split_results, old_copy_id) + split = split_for(split_results, old_copy_id) assert split.outcome is PolicyCopyOutcome.DELETED with owner_sessions() as session: saved_policy = session.get(UserPolicy, saved_policy_id) @@ -1250,7 +966,7 @@ def run_split() -> None: account_user_id, split.policy.id, ) - [saved_dynamic] = _saved_dynamics(owner_sessions, account_user_id) + [saved_dynamic] = saved_dynamics_of(owner_sessions, account_user_id) assert saved_dynamic.dynamic_id == split.dynamic.id @@ -1260,32 +976,32 @@ def test_a_mapping_s_dynamic_on_another_catalog_version_refuses_the_copy( uk_scenario: Scenario, ) -> None: scenario = uk_scenario - old_copy_id = _store_policy( + old_copy_id = store_policy( owner_sessions, scenario, scenario.parameter_value(UK_TAX_RATE, value=0.21), scenario.parameter_value(UK_OBR_SWITCH, value=False), ) - other_version = _store_other_version( + other_version = store_other_version( owner_sessions, scenario, [UK_INCOME_ELASTICITY] ) - earlier_dynamic_id = _store_dynamic( + earlier_dynamic_id = store_dynamic( owner_sessions, other_version, other_version.parameter_value(UK_INCOME_ELASTICITY, value=0.1), ) - legacy_policy_id = _store_mapping( + legacy_policy_id = store_mapping( owner_sessions, scenario, policy_id=old_copy_id, dynamic_id=earlier_dynamic_id ) - split = _result_for( + split = split_for( list(_service(split_role_sessions).split_policy_copies()), old_copy_id ) assert split.outcome is PolicyCopyOutcome.REFUSED assert split.refusal_reason is PolicyCopyRefusalReason.DYNAMIC_ON_ANOTHER_CATALOG - assert _policy_exists(owner_sessions, old_copy_id) - mapping = _mapping(owner_sessions, scenario, legacy_policy_id) + assert policy_exists(owner_sessions, old_copy_id) + mapping = stored_mapping(owner_sessions, scenario, legacy_policy_id) assert (mapping.policy_id, mapping.dynamic_id) == (old_copy_id, earlier_dynamic_id) @@ -1296,25 +1012,25 @@ def test_the_listing_reports_a_mapping_s_merged_dynamic_as_applying_does( uk_scenario: Scenario, ) -> None: scenario = uk_scenario - old_copy_id = _store_policy( + old_copy_id = store_policy( owner_sessions, scenario, scenario.parameter_value(UK_TAX_RATE, value=0.21), scenario.parameter_value(UK_OBR_SWITCH, value=False), ) - earlier_dynamic_id = _store_dynamic( + earlier_dynamic_id = store_dynamic( owner_sessions, scenario, scenario.parameter_value(UK_INCOME_ELASTICITY, value=0.1), ) - _store_mapping( + store_mapping( owner_sessions, scenario, policy_id=old_copy_id, dynamic_id=earlier_dynamic_id ) - listed = _result_for( + listed = split_for( _listing_service(listing_sessions).list_policy_copy_splits(), old_copy_id ) - applied = _result_for( + applied = split_for( list(_service(split_role_sessions).split_policy_copies()), old_copy_id ) @@ -1333,7 +1049,7 @@ def test_a_copy_a_household_calculation_names_is_kept( us_scenario: Scenario, ) -> None: scenario = us_scenario - old_copy_id = _store_policy( + old_copy_id = store_policy( owner_sessions, scenario, scenario.parameter_value(US_TAX_RATE, value=0.3), @@ -1362,7 +1078,7 @@ def test_a_copy_a_household_calculation_names_is_kept( session.commit() scenario.household_ids.append(household.id) - split = _result_for( + split = split_for( list(_service(split_role_sessions).split_policy_copies()), old_copy_id ) @@ -1372,4 +1088,141 @@ def test_a_copy_a_household_calculation_names_is_kept( split.references.reports, split.references.household_jobs, ) == (0, 0, 1) - assert _policy_exists(owner_sessions, old_copy_id) + assert policy_exists(owner_sessions, old_copy_id) + + +def test_a_saved_policy_deleted_or_pointed_elsewhere_meanwhile_is_skipped( + owner_sessions: sessionmaker[Session], + split_role_sessions: sessionmaker[Session], + us_scenario: Scenario, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A saved policy the split read can change before the split locks it. + + It's skipped then: one deleted meanwhile, and one pointed at another + policy, which keeps naming that policy and gets no saved dynamic. + """ + scenario = us_scenario + old_copy_id = store_policy( + owner_sessions, + scenario, + scenario.parameter_value(US_TAX_RATE, value=0.3), + scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), + ) + other_policy_id = store_policy( + owner_sessions, scenario, scenario.parameter_value(US_TAX_RATE, value=0.4) + ) + user_id = store_user(owner_sessions, scenario) + deleted_id, repointed_id = ( + store_saved_policy( + owner_sessions, scenario, user_id=user_id, policy_id=old_copy_id, name=name + ) + for name in ("Deleted meanwhile", "Pointed elsewhere meanwhile") + ) + read_for_update = split_services.read_saved_policy_for_update + changed: list[bool] = [] + + def change_then_read(session: Session, saved_policy_id: UUID) -> UserPolicy | None: + if not changed: + with owner_sessions.begin() as other_session: + other_session.execute( + delete(UserPolicy).where(col(UserPolicy.id) == deleted_id) + ) + other_session.execute( + update(UserPolicy) + .where(col(UserPolicy.id) == repointed_id) + .values(policy_id=other_policy_id) + ) + changed.append(True) + return read_for_update(session, saved_policy_id) + + monkeypatch.setattr( + split_services, "read_saved_policy_for_update", change_then_read + ) + + split = split_for( + list(_service(split_role_sessions).split_policy_copies()), old_copy_id + ) + + assert split.outcome is PolicyCopyOutcome.DELETED + assert split.saved_policies == () + assert not policy_exists(owner_sessions, old_copy_id) + assert saved_policy_target(owner_sessions, repointed_id) == other_policy_id + assert saved_dynamics_of(owner_sessions, user_id) == [] + + +def test_the_listing_reports_a_refused_copy_and_skips_rows_with_nothing_to_split( + owner_sessions: sessionmaker[Session], + split_role_sessions: sessionmaker[Session], + listing_sessions: sessionmaker[Session], + uk_scenario: Scenario, +) -> None: + scenario = uk_scenario + refused_copy_id = store_policy( + owner_sessions, + scenario, + scenario.parameter_value(UK_TAX_RATE, value=0.21), + scenario.parameter_value(UK_INCOME_ELASTICITY, value=0.2), + ) + earlier_dynamic_id = store_dynamic( + owner_sessions, + scenario, + scenario.parameter_value(UK_INCOME_ELASTICITY, value=0.1), + ) + store_mapping( + owner_sessions, + scenario, + policy_id=refused_copy_id, + dynamic_id=earlier_dynamic_id, + ) + policy_without_assumptions_id = store_policy( + owner_sessions, scenario, scenario.parameter_value(UK_TAX_RATE, value=0.22) + ) + + listed = split_for( + _listing_service(listing_sessions).list_policy_copy_splits(), + refused_copy_id, + ) + + assert not listed.applied + assert listed.outcome is PolicyCopyOutcome.REFUSED + assert listed.refusal_reason is PolicyCopyRefusalReason.CONFLICTING_DYNAMIC_VALUES + with split_role_sessions() as session: + for policy_id in (policy_without_assumptions_id, uuid4()): + assert plan_policy_copy_split(session, policy_id) is None + assert split_policy_copy_in_session(session, policy_id) is None + session.rollback() + + +def test_the_count_of_copies_left_names_the_ones_kept( + owner_sessions: sessionmaker[Session], + split_role_sessions: sessionmaker[Session], + us_scenario: Scenario, +) -> None: + scenario = us_scenario + deleted_copy_id, kept_copy_id = ( + store_policy( + owner_sessions, + scenario, + scenario.parameter_value(US_TAX_RATE, value=tax_rate), + scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), + ) + for tax_rate in (0.3, 0.4) + ) + with owner_sessions.begin() as session: + session.add( + Report( + country="us", + tax_benefit_model_id=scenario.model_id, + policy_id=kept_copy_id, + ) + ) + service = _service(split_role_sessions) + + list(service.split_policy_copies()) + + with split_role_sessions() as session: + remaining_copy_ids = read_policy_copy_ids(session) + assert kept_copy_id in remaining_copy_ids + assert deleted_copy_id not in remaining_copy_ids + assert service.count_policy_copies() == len(remaining_copy_ids) diff --git a/tests/unit/v2/test_policy_copy_split_rules.py b/tests/unit/v2/test_policy_copy_split_rules.py index 1fa066473..f4c3e5c0d 100644 --- a/tests/unit/v2/test_policy_copy_split_rules.py +++ b/tests/unit/v2/test_policy_copy_split_rules.py @@ -33,8 +33,10 @@ PolicyCopyRefusalReason, ) from policyengine_api.services.v2.policy_copy_split.validators import ( + PolicyCopyIntegrityError, PolicyCopySplitRefusedError, merge_dynamic_content, + require_stored_row, ) MODEL_ID = UUID("00000000-0000-0000-0000-00000000a001") @@ -312,3 +314,19 @@ def test_a_merged_dynamic_over_the_value_limit_refuses_the_copy() -> None: ) assert refusal.value.reason is PolicyCopyRefusalReason.TOO_MANY_VALUES + + +def test_a_refusal_names_its_reason() -> None: + refusal = PolicyCopySplitRefusedError( + PolicyCopyRefusalReason.CONFLICTING_DYNAMIC_VALUES + ) + + assert "conflicting_dynamic_values" in str(refusal) + + +def test_a_missing_row_a_foreign_key_requires_is_an_integrity_error() -> None: + assert require_stored_row(POLICY_ID, "the copy's ID") == POLICY_ID + with pytest.raises( + PolicyCopyIntegrityError, match=r"model version of policy .* is missing" + ): + require_stored_row(None, f"model version of policy {POLICY_ID}")