From 9a93c25d9f3c62fc08ca1673b679967d6c6bb675 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:13:03 +0400 Subject: [PATCH 01/22] Add failing tests for the one-time saved-record migration command MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tests for API v1's one-time command that gives saved reforms, saved reports and saved households holding only an API v1 reference their API v2 records (D4 · 1): rebuilding API v1 reports, translating API v1 regions, dropping missing parameters in the second mode, the closing check, the command's flags and output, and the cross-database run as the runtime role. They fail because the command doesn't exist yet. Co-Authored-By: Claude Opus 5.5 --- .../test_v2_saved_record_migration.py | 969 ++++++++++++++++++ .../unit/test_migrate_saved_records_script.py | 222 ++++ .../v2/test_saved_record_migration_rules.py | 558 ++++++++++ 3 files changed, 1749 insertions(+) create mode 100644 tests/integration/test_v2_saved_record_migration.py create mode 100644 tests/unit/test_migrate_saved_records_script.py create mode 100644 tests/unit/v2/test_saved_record_migration_rules.py diff --git a/tests/integration/test_v2_saved_record_migration.py b/tests/integration/test_v2_saved_record_migration.py new file mode 100644 index 000000000..a5e9ed7d0 --- /dev/null +++ b/tests/integration/test_v2_saved_record_migration.py @@ -0,0 +1,969 @@ +"""The one-time migration of saved records' v1 references (D4 · 1). + +v1's rows are in MySQL and the detailed-save tables in PostgreSQL, where the +command runs as API v1's runtime role, as it does in staging and production. +A stand-in for the simulation service records each report definition it is +sent and stores a report row for it, as the simulation service would, after +checking that the policies, dynamics and household the definition names are +already committed. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import TYPE_CHECKING +from uuid import UUID, uuid4 + +import pytest +from policyengine_api.services.v2.saved_record_migration.database_session import ( + SavedRecordMigrationDatabaseSession, + V1RecordDatabaseSession, +) +from policyengine_api.services.v2.saved_record_migration.services import ( + V2SavedRecordMigrationService, +) +from policyengine_api.services.v2.saved_record_migration.types import ( + DetailedSaveReportDefinition, + DetailedSaveReportKind, + FailureReason, + MigrationOptions, + MigrationRun, + PolicySide, + RowOutcome, + SavedRecordKind, +) +from policyengine_api.services.v2.saved_record_migration.validators import ( + ReportSubmissionRefusedError, +) +from sqlalchemy import delete, func, select +from sqlmodel import col + +from policyengine_api.data.v1_models import Household as V1Household +from policyengine_api.data.v1_models import Policy as V1Policy +from policyengine_api.data.v1_models import ReportOutput as V1ReportOutput +from policyengine_api.data.v1_models import Simulation as V1Simulation +from policyengine_api.data.v2.models import ( + Dynamic, + DynamicParameter, + DynamicParameterValue, + Household, + LegacyHouseholdMapping, + LegacyPolicyMapping, + Parameter, + ParameterValue, + Policy, + TaxBenefitModel, + TaxBenefitModelVersion, + User, + UserDynamic, + UserHouseholdAssociation, + UserPolicy, + UserReportAssociation, + UserSimulationAssociation, +) +from tests.integration.simulation_rows import add_row +from tests.integration.stored_report_rows import ( + CatalogRows, + delete_catalog, + store_catalog, + store_report, +) + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + + from sqlalchemy.orm import Session as OrmSession + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + from tests.integration.conftest import ManagedV2Roles + +RUNNING_VERSION = "d4-1-migration-test" +CTC_AMOUNT = "gov.irs.credits.ctc.amount.base" +EITC_RATE = "gov.irs.credits.eitc.phase_in_rate" +INCOME_ELASTICITY = "gov.simulation.labor_supply_responses.elasticities.income" +REMOVED_PARAMETER = "gov.simulation.reported_snap" +PERIOD = "2026-01-01.2100-12-31" +REFUSAL_CODE = "unknown_household" + +# v1 IDs, chosen high so they don't meet other tests' rows. +CURRENT_LAW = 940_100 +CTC_REFORM = 940_101 +CTC_REFORM_WITH_ELASTICITY = 940_102 +CTC_REFORM_WITH_REMOVED_PARAMETER = 940_103 +ONLY_REMOVED_PARAMETER = 940_104 +V1_HOUSEHOLD = 940_501 +ECONOMY_REPORT = 940_301 +HOUSEHOLD_REPORT = 940_303 +MISSING_PARAMETER_REPORT = 940_304 +UNKNOWN_REGION_REPORT = 940_305 +SAVED_SIMULATION = 940_211 +V1_POLICIES = { + CURRENT_LAW: {}, + CTC_REFORM: {CTC_AMOUNT: {PERIOD: 3000}}, + CTC_REFORM_WITH_ELASTICITY: { + CTC_AMOUNT: {PERIOD: 3500}, + INCOME_ELASTICITY: {PERIOD: 0.1}, + }, + CTC_REFORM_WITH_REMOVED_PARAMETER: { + EITC_RATE: {PERIOD: 0.4}, + REMOVED_PARAMETER: {PERIOD: True}, + }, + ONLY_REMOVED_PARAMETER: {REMOVED_PARAMETER: {PERIOD: True}}, +} +# Each v1 simulation: its population type, population and policy. +V1_SIMULATIONS = { + 940_201: ("geography", "us", CURRENT_LAW), + 940_202: ("geography", "us", CTC_REFORM_WITH_ELASTICITY), + 940_203: ("household", str(V1_HOUSEHOLD), CURRENT_LAW), + 940_204: ("household", str(V1_HOUSEHOLD), CTC_REFORM), + 940_205: ("geography", "us", CTC_REFORM_WITH_REMOVED_PARAMETER), + 940_206: ("geography", "state/zz", CURRENT_LAW), + 940_207: ("geography", "state/zz", CTC_REFORM), +} +# Each v1 report output: its two simulations. +V1_REPORTS = { + ECONOMY_REPORT: (940_201, 940_202), + HOUSEHOLD_REPORT: (940_203, 940_204), + MISSING_PARAMETER_REPORT: (940_201, 940_205), + UNKNOWN_REGION_REPORT: (940_206, 940_207), +} + + +def _household_document() -> dict[str, object]: + members = {"members": ["adult"]} + return { + "people": {"adult": {"age": {"2026": 41}}}, + "households": {"home": members}, + "families": {"family": members}, + "tax_units": {"tax unit": members}, + "spm_units": {"spm unit": members}, + "marital_units": {"marital unit": members}, + } + + +def _store_v1_records(v1_sessions: sessionmaker[OrmSession]) -> None: + _delete_v1_records(v1_sessions) + with v1_sessions.begin() as session: + for policy_id, policy_json in V1_POLICIES.items(): + session.add( + V1Policy( + id=policy_id, + country_id="us", + label=f"v1 policy {policy_id}", + api_version="1.0.0", + policy_json=policy_json, + policy_hash=f"d4-1-hash-{policy_id}", + ) + ) + session.add( + V1Household( + id=V1_HOUSEHOLD, + country_id="us", + label="v1 household", + api_version="1.0.0", + household_json=_household_document(), + household_hash="d4-1-household-hash", + ) + ) + for simulation_id, (kind, population, policy_id) in V1_SIMULATIONS.items(): + session.add( + V1Simulation( + id=simulation_id, + country_id="us", + api_version="1.0.0", + population_type=kind, + population_id=population, + policy_id=policy_id, + ) + ) + for report_id, (first, second) in V1_REPORTS.items(): + session.add( + V1ReportOutput( + id=report_id, + country_id="us", + simulation_1_id=first, + simulation_2_id=second, + api_version="1.0.0", + year="2026", + ) + ) + + +def _delete_v1_records(v1_sessions: sessionmaker[OrmSession]) -> None: + with v1_sessions.begin() as session: + session.execute( + delete(V1ReportOutput).where(V1ReportOutput.id.in_(list(V1_REPORTS))) + ) + session.execute( + delete(V1Simulation).where(V1Simulation.id.in_(list(V1_SIMULATIONS))) + ) + session.execute(delete(V1Household).where(V1Household.id == V1_HOUSEHOLD)) + session.execute(delete(V1Policy).where(V1Policy.id.in_(list(V1_POLICIES)))) + + +@dataclass +class DetailedSaveRows: + """The rows each test stores in the detailed-save tables, to delete after.""" + + model_id: UUID + created_model: bool + version_id: UUID + first_user: UUID + second_user: UUID + report_catalog: CatalogRows | None = None + + +@dataclass +class RecordingSimulationService: + """Stands in for the simulation service's find-or-create of reports by key. + + Each definition gets one report row, stored as the database's owner, and + the same definition gets the same report again. ``refused`` lists the + definitions it refuses, as the simulation service answers 400. + """ + + owner_sessions: sessionmaker[Session] + catalog: CatalogRows + definitions: list[DetailedSaveReportDefinition] = field(default_factory=list) + reports: dict[DetailedSaveReportDefinition, UUID] = field(default_factory=dict) + refused: set[DetailedSaveReportKind] = field(default_factory=set) + + def find_or_create_report(self, definition: DetailedSaveReportDefinition) -> UUID: + self.definitions.append(definition) + with self.owner_sessions() as session: + # The simulation service reads what the definition names itself, + # so it must already be committed. + for side in (definition.baseline, definition.reform): + if side is not None and side.policy_id is not None: + assert session.get(Policy, side.policy_id) is not None + if side is not None and side.dynamic_id is not None: + assert session.get(Dynamic, side.dynamic_id) is not None + if definition.household_id is not None: + assert session.get(Household, definition.household_id) is not None + if definition.kind in self.refused: + message = "the simulation service refused the household report" + raise ReportSubmissionRefusedError(REFUSAL_CODE, message) + if definition not in self.reports: + with self.owner_sessions.begin() as session: + self.reports[definition] = store_report(session, self.catalog).report_id + return self.reports[definition] + + +@pytest.fixture +def runtime_sessions( + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], + managed_v2_roles: ManagedV2Roles, +) -> sessionmaker[Session]: + return v2_sessions_as_role(managed_v2_roles.runtime) + + +@pytest.fixture +def stored_rows( + v1_sessions: sessionmaker[OrmSession], + v2_owner_sessions: sessionmaker[Session], +) -> Iterator[DetailedSaveRows]: + _store_v1_records(v1_sessions) + with v2_owner_sessions.begin() as session: + model_id = session.scalar( + select(TaxBenefitModel.id).where( + col(TaxBenefitModel.name) == "policyengine-us" + ) + ) + created_model = model_id is None + if model_id is None: + model_id = uuid4() + add_row(session, TaxBenefitModel, id=model_id, name="policyengine-us") + version_id = uuid4() + add_row( + session, + TaxBenefitModelVersion, + id=version_id, + model_id=model_id, + version=RUNNING_VERSION, + current_law_id=1, + metadata_time_periods=[2026], + ) + for name in (CTC_AMOUNT, EITC_RATE): + add_row( + session, + Parameter, + id=uuid4(), + name=name, + tax_benefit_model_version_id=version_id, + ) + add_row( + session, + DynamicParameter, + id=uuid4(), + name=INCOME_ELASTICITY, + tax_benefit_model_version_id=version_id, + ) + rows = DetailedSaveRows( + model_id=model_id, + created_model=created_model, + version_id=version_id, + first_user=uuid4(), + second_user=uuid4(), + ) + for user_id in (rows.first_user, rows.second_user): + add_row(session, User, id=user_id, primary_country="us") + rows.report_catalog = store_catalog(session, "us") + try: + yield rows + finally: + _delete_detailed_save_rows(v2_owner_sessions, rows) + _delete_v1_records(v1_sessions) + + +def _delete_detailed_save_rows( + owner_sessions: sessionmaker[Session], rows: DetailedSaveRows +) -> None: + users = [rows.first_user, rows.second_user] + with owner_sessions.begin() as session: + for model in ( + UserReportAssociation, + UserSimulationAssociation, + UserHouseholdAssociation, + UserDynamic, + UserPolicy, + ): + session.execute(delete(model).where(col(model.user_id).in_(users))) + session.execute(delete(User).where(col(User.id).in_(users))) + session.execute( + delete(LegacyPolicyMapping).where( + col(LegacyPolicyMapping.legacy_policy_id).in_(list(V1_POLICIES)) + ) + ) + # The household copy is deleted after its mapping, which names it. + households = list( + session.scalars( + select(LegacyHouseholdMapping.household_id).where( + col(LegacyHouseholdMapping.legacy_household_id) == V1_HOUSEHOLD + ) + ) + ) + session.execute( + delete(LegacyHouseholdMapping).where( + col(LegacyHouseholdMapping.legacy_household_id) == V1_HOUSEHOLD + ) + ) + if rows.report_catalog is not None: + delete_catalog(session, rows.report_catalog) + version_policies = select(Policy.id).where( + col(Policy.tax_benefit_model_version_id) == rows.version_id + ) + version_dynamics = select(Dynamic.id).where( + col(Dynamic.tax_benefit_model_version_id) == rows.version_id + ) + session.execute( + delete(ParameterValue).where( + col(ParameterValue.policy_id).in_(version_policies) + ) + ) + session.execute( + delete(DynamicParameterValue).where( + col(DynamicParameterValue.dynamic_id).in_(version_dynamics) + ) + ) + session.execute( + delete(Policy).where( + col(Policy.tax_benefit_model_version_id) == rows.version_id + ) + ) + session.execute( + delete(Dynamic).where( + col(Dynamic.tax_benefit_model_version_id) == rows.version_id + ) + ) + session.execute(delete(Household).where(col(Household.id).in_(households))) + session.execute( + delete(TaxBenefitModelVersion).where( + col(TaxBenefitModelVersion.id) == rows.version_id + ) + ) + if rows.created_model: + session.execute( + delete(TaxBenefitModel).where(col(TaxBenefitModel.id) == rows.model_id) + ) + + +def _save(owner_sessions: sessionmaker[Session], model: type, **values: object) -> UUID: + row_id = uuid4() + with owner_sessions.begin() as session: + add_row(session, model, id=row_id, country_id="us", **values) + return row_id + + +def _service( + runtime_sessions: sessionmaker[Session], + v1_sessions: sessionmaker[OrmSession], + simulation_service: RecordingSimulationService, +) -> V2SavedRecordMigrationService: + return V2SavedRecordMigrationService( + SavedRecordMigrationDatabaseSession(runtime_sessions), + V1RecordDatabaseSession(v1_sessions), + report_submitter=simulation_service, + running_policyengine_version=RUNNING_VERSION, + ) + + +def _simulation_service( + owner_sessions: sessionmaker[Session], rows: DetailedSaveRows +) -> RecordingSimulationService: + assert rows.report_catalog is not None + return RecordingSimulationService(owner_sessions, rows.report_catalog) + + +def _migrate( + service: V2SavedRecordMigrationService, + rows: DetailedSaveRows, + **options: object, +) -> MigrationRun: + return service.migrate( + MigrationOptions( + user_ids=(rows.first_user, rows.second_user), + **{"apply": True, **options}, + ) + ) + + +def _result(run: MigrationRun, row_id: UUID): + (result,) = [result for result in run.results if result.row_id == row_id] + return result + + +def _remaining(run: MigrationRun, kind: SavedRecordKind): + (remaining,) = [item for item in run.closing_check.remaining if item.kind is kind] + return remaining + + +def _policy_values(owner_sessions: sessionmaker[Session], policy_id: UUID) -> set: + with owner_sessions() as session: + return set( + session.execute( + select(Parameter.name, ParameterValue.value_json) + .join(Parameter, col(Parameter.id) == col(ParameterValue.parameter_id)) + .where(col(ParameterValue.policy_id) == policy_id) + ).all() + ) + + +def _dynamic_values(owner_sessions: sessionmaker[Session], dynamic_id: UUID) -> set: + with owner_sessions() as session: + return set( + session.execute( + select(DynamicParameter.name, DynamicParameterValue.value_json) + .join( + DynamicParameter, + col(DynamicParameter.id) + == col(DynamicParameterValue.dynamic_parameter_id), + ) + .where(col(DynamicParameterValue.dynamic_id) == dynamic_id) + ).all() + ) + + +def _mapping(owner_sessions: sessionmaker[Session], legacy_policy_id: int): + with owner_sessions() as session: + return session.scalar( + select(LegacyPolicyMapping).where( + col(LegacyPolicyMapping.legacy_policy_id) == legacy_policy_id + ) + ) + + +def _row(owner_sessions: sessionmaker[Session], model: type, row_id: UUID): + with owner_sessions() as session: + row = session.get(model, row_id) + session.expunge_all() + return row + + +# Saved reforms. + + +def test_a_saved_reform_is_pointed_at_its_v1_policy_s_copy( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + saved = _save( + v2_owner_sessions, + UserPolicy, + user_id=stored_rows.first_user, + legacy_policy_id=CTC_REFORM, + name="Bigger CTC", + ) + service = _service( + runtime_sessions, + v1_sessions, + _simulation_service(v2_owner_sessions, stored_rows), + ) + + run = _migrate(service, stored_rows) + + mapping = _mapping(v2_owner_sessions, CTC_REFORM) + assert mapping is not None + assert mapping.dynamic_id is None + row = _row(v2_owner_sessions, UserPolicy, saved) + assert (row.policy_id, row.legacy_policy_id) == (mapping.policy_id, CTC_REFORM) + result = _result(run, saved) + assert result.outcome is RowOutcome.MIGRATED + assert result.detailed_save_id == mapping.policy_id + assert result.saved_dynamic_id is None + assert _policy_values(v2_owner_sessions, mapping.policy_id) == {(CTC_AMOUNT, 3000)} + assert run.closing_check.passed + + +def test_model_assumptions_become_a_dynamic_and_a_saved_dynamic_with_its_name( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + saved = _save( + v2_owner_sessions, + UserPolicy, + user_id=stored_rows.first_user, + legacy_policy_id=CTC_REFORM_WITH_ELASTICITY, + name="CTC with responses", + description="With labour supply responses", + ) + service = _service( + runtime_sessions, + v1_sessions, + _simulation_service(v2_owner_sessions, stored_rows), + ) + + run = _migrate(service, stored_rows) + + mapping = _mapping(v2_owner_sessions, CTC_REFORM_WITH_ELASTICITY) + assert mapping is not None + assert mapping.dynamic_id is not None + assert _policy_values(v2_owner_sessions, mapping.policy_id) == {(CTC_AMOUNT, 3500)} + assert _dynamic_values(v2_owner_sessions, mapping.dynamic_id) == { + (INCOME_ELASTICITY, 0.1) + } + result = _result(run, saved) + assert result.saved_dynamic_id is not None + saved_dynamic = _row(v2_owner_sessions, UserDynamic, result.saved_dynamic_id) + assert ( + saved_dynamic.user_id, + saved_dynamic.country_id, + saved_dynamic.dynamic_id, + saved_dynamic.name, + saved_dynamic.description, + ) == ( + stored_rows.first_user, + "us", + mapping.dynamic_id, + "CTC with responses", + "With labour supply responses", + ) + assert _row(v2_owner_sessions, UserPolicy, saved).policy_id == mapping.policy_id + + +def test_a_saved_reform_with_a_missing_parameter_is_left_and_listed( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + saved = _save( + v2_owner_sessions, + UserPolicy, + user_id=stored_rows.first_user, + legacy_policy_id=CTC_REFORM_WITH_REMOVED_PARAMETER, + ) + service = _service( + runtime_sessions, + v1_sessions, + _simulation_service(v2_owner_sessions, stored_rows), + ) + + run = _migrate(service, stored_rows) + + result = _result(run, saved) + assert result.outcome is RowOutcome.MISSING_PARAMETERS + assert result.missing_parameters == (REMOVED_PARAMETER,) + assert _row(v2_owner_sessions, UserPolicy, saved).policy_id is None + assert _mapping(v2_owner_sessions, CTC_REFORM_WITH_REMOVED_PARAMETER) is None + assert _remaining(run, SavedRecordKind.SAVED_REFORM).missing_parameters == 1 + assert run.closing_check.passed + + +def test_the_second_mode_keeps_the_parameters_that_still_exist( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + partly_missing = _save( + v2_owner_sessions, + UserPolicy, + user_id=stored_rows.first_user, + legacy_policy_id=CTC_REFORM_WITH_REMOVED_PARAMETER, + ) + wholly_missing = _save( + v2_owner_sessions, + UserPolicy, + user_id=stored_rows.first_user, + legacy_policy_id=ONLY_REMOVED_PARAMETER, + ) + service = _service( + runtime_sessions, + v1_sessions, + _simulation_service(v2_owner_sessions, stored_rows), + ) + + run = _migrate(service, stored_rows, drop_missing_parameters=True) + + migrated = _result(run, partly_missing) + assert migrated.outcome is RowOutcome.MIGRATED + assert migrated.dropped_parameters == (REMOVED_PARAMETER,) + assert migrated.detailed_save_id is not None + assert _policy_values(v2_owner_sessions, migrated.detailed_save_id) == { + (EITC_RATE, 0.4) + } + row = _row(v2_owner_sessions, UserPolicy, partly_missing) + assert row.policy_id == migrated.detailed_save_id + # The kept policy isn't the v1 policy's copy, so the v1 ID gets no mapping. + assert _mapping(v2_owner_sessions, CTC_REFORM_WITH_REMOVED_PARAMETER) is None + left = _result(run, wholly_missing) + assert left.outcome is RowOutcome.EVERY_PARAMETER_MISSING + assert left.missing_parameters == (REMOVED_PARAMETER,) + assert _row(v2_owner_sessions, UserPolicy, wholly_missing).policy_id is None + assert _remaining(run, SavedRecordKind.SAVED_REFORM).every_parameter_missing == 1 + assert run.closing_check.passed + + +# Saved households and saved simulations. + + +def test_a_saved_household_is_pointed_at_its_v1_household_s_copy( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + saved = _save( + v2_owner_sessions, + UserHouseholdAssociation, + user_id=stored_rows.first_user, + legacy_household_id=V1_HOUSEHOLD, + name="My household", + ) + service = _service( + runtime_sessions, + v1_sessions, + _simulation_service(v2_owner_sessions, stored_rows), + ) + + run = _migrate(service, stored_rows) + + with v2_owner_sessions() as session: + household_id = session.scalar( + select(LegacyHouseholdMapping.household_id).where( + col(LegacyHouseholdMapping.legacy_household_id) == V1_HOUSEHOLD + ) + ) + assert household_id is not None + row = _row(v2_owner_sessions, UserHouseholdAssociation, saved) + assert (row.household_id, row.legacy_household_id) == (household_id, V1_HOUSEHOLD) + assert _result(run, saved).detailed_save_id == household_id + assert run.closing_check.passed + + +def test_a_saved_simulation_is_listed_and_not_migrated( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + saved = _save( + v2_owner_sessions, + UserSimulationAssociation, + user_id=stored_rows.first_user, + legacy_simulation_id=SAVED_SIMULATION, + ) + service = _service( + runtime_sessions, + v1_sessions, + _simulation_service(v2_owner_sessions, stored_rows), + ) + + run = _migrate(service, stored_rows) + + assert _result(run, saved).outcome is RowOutcome.NOT_MIGRATED + assert ( + _row(v2_owner_sessions, UserSimulationAssociation, saved).simulation_id is None + ) + assert _remaining(run, SavedRecordKind.SAVED_SIMULATION).not_migrated == 1 + assert run.closing_check.passed + + +# Saved reports. + + +def test_identical_v1_reports_share_one_report_with_each_side_split( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + first = _save( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=ECONOMY_REPORT, + name="CTC report", + ) + second = _save( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.second_user, + legacy_report_id=ECONOMY_REPORT, + name="Same report, another user", + ) + simulation_service = _simulation_service(v2_owner_sessions, stored_rows) + service = _service(runtime_sessions, v1_sessions, simulation_service) + + run = _migrate(service, stored_rows) + + mapping = _mapping(v2_owner_sessions, CTC_REFORM_WITH_ELASTICITY) + assert mapping is not None + assert simulation_service.definitions == [ + DetailedSaveReportDefinition( + country_id="us", + kind=DetailedSaveReportKind.ECONOMY, + baseline=PolicySide(policy_id=None, dynamic_id=None), + reform=PolicySide( + policy_id=mapping.policy_id, dynamic_id=mapping.dynamic_id + ), + year=2026, + region_code="us", + budget_window_size=None, + household_id=None, + ) + ] + (report_id,) = simulation_service.reports.values() + for row_id, name in ((first, "CTC report"), (second, "Same report, another user")): + row = _row(v2_owner_sessions, UserReportAssociation, row_id) + assert (row.report_id, row.legacy_report_id, row.name) == ( + report_id, + ECONOMY_REPORT, + name, + ) + assert _result(run, row_id).detailed_save_id == report_id + assert run.closing_check.passed + + +def test_a_saved_budget_window_becomes_a_budget_window_report( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + saved = _save( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=ECONOMY_REPORT, + budget_window_years=10, + ) + simulation_service = _simulation_service(v2_owner_sessions, stored_rows) + service = _service(runtime_sessions, v1_sessions, simulation_service) + + run = _migrate(service, stored_rows) + + (definition,) = simulation_service.definitions + assert definition.kind is DetailedSaveReportKind.BUDGET_WINDOW + assert (definition.year, definition.budget_window_size) == (2026, 10) + row = _row(v2_owner_sessions, UserReportAssociation, saved) + assert row.report_id == simulation_service.reports[definition] + assert row.budget_window_years == 10 + assert _result(run, saved).outcome is RowOutcome.MIGRATED + + +def test_a_household_report_names_the_household_s_copy( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + saved = _save( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=HOUSEHOLD_REPORT, + ) + simulation_service = _simulation_service(v2_owner_sessions, stored_rows) + service = _service(runtime_sessions, v1_sessions, simulation_service) + + run = _migrate(service, stored_rows) + + household_mapping_id = None + with v2_owner_sessions() as session: + household_mapping_id = session.scalar( + select(LegacyHouseholdMapping.household_id).where( + col(LegacyHouseholdMapping.legacy_household_id) == V1_HOUSEHOLD + ) + ) + reform_mapping = _mapping(v2_owner_sessions, CTC_REFORM) + assert reform_mapping is not None + assert simulation_service.definitions == [ + DetailedSaveReportDefinition( + country_id="us", + kind=DetailedSaveReportKind.HOUSEHOLD, + baseline=PolicySide(policy_id=None, dynamic_id=None), + reform=PolicySide(policy_id=reform_mapping.policy_id, dynamic_id=None), + year=None, + region_code=None, + budget_window_size=None, + household_id=household_mapping_id, + ) + ] + assert _result(run, saved).outcome is RowOutcome.MIGRATED + assert _row(v2_owner_sessions, UserReportAssociation, saved).report_id is not None + + +def test_reports_that_cant_migrate_are_left_with_a_reason( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + missing_parameter = _save( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=MISSING_PARAMETER_REPORT, + ) + unknown_region = _save( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=UNKNOWN_REGION_REPORT, + ) + refused = _save( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=HOUSEHOLD_REPORT, + ) + no_v1_report = _save( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=940_399, + ) + simulation_service = _simulation_service(v2_owner_sessions, stored_rows) + simulation_service.refused.add(DetailedSaveReportKind.HOUSEHOLD) + service = _service(runtime_sessions, v1_sessions, simulation_service) + + run = _migrate(service, stored_rows) + + skipped = _result(run, missing_parameter) + assert skipped.outcome is RowOutcome.MISSING_PARAMETERS + assert skipped.missing_parameters == (REMOVED_PARAMETER,) + assert _result(run, unknown_region).failure_reason is FailureReason.UNKNOWN_REGION + assert _result(run, refused).failure_reason is FailureReason.REPORT_REFUSED + assert ( + _result(run, no_v1_report).failure_reason is FailureReason.V1_RECORD_NOT_FOUND + ) + for row_id in (missing_parameter, unknown_region, refused, no_v1_report): + assert _row(v2_owner_sessions, UserReportAssociation, row_id).report_id is None + remaining = _remaining(run, SavedRecordKind.SAVED_REPORT) + assert (remaining.missing_parameters, remaining.failed) == (1, 3) + assert not run.closing_check.passed + # Only the household report reached the simulation service. + assert [item.kind for item in simulation_service.definitions] == [ + DetailedSaveReportKind.HOUSEHOLD + ] + + +# Dry runs and running again. + + +def _row_counts(owner_sessions: sessionmaker[Session]) -> dict[str, int]: + with owner_sessions() as session: + return { + model.__name__: session.scalar(select(func.count()).select_from(model)) + for model in ( + Policy, + Dynamic, + Household, + LegacyPolicyMapping, + LegacyHouseholdMapping, + UserDynamic, + ) + } + + +def test_a_dry_run_writes_nothing_and_predicts_the_real_run( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + saved_rows = [ + _save( + v2_owner_sessions, + UserPolicy, + user_id=stored_rows.first_user, + legacy_policy_id=legacy_policy_id, + ) + for legacy_policy_id in (CTC_REFORM_WITH_ELASTICITY, ONLY_REMOVED_PARAMETER) + ] + saved_rows.append( + _save( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=ECONOMY_REPORT, + ) + ) + saved_rows.append( + _save( + v2_owner_sessions, + UserHouseholdAssociation, + user_id=stored_rows.first_user, + legacy_household_id=V1_HOUSEHOLD, + ) + ) + simulation_service = _simulation_service(v2_owner_sessions, stored_rows) + service = _service(runtime_sessions, v1_sessions, simulation_service) + before = _row_counts(v2_owner_sessions) + + dry_run = _migrate(service, stored_rows, apply=False) + + assert _row_counts(v2_owner_sessions) == before + assert simulation_service.definitions == [] + assert _row(v2_owner_sessions, UserPolicy, saved_rows[0]).policy_id is None + real_run = _migrate(service, stored_rows) + assert [ + (result.row_id, result.outcome, result.missing_parameters) + for result in dry_run.results + ] == [ + (result.row_id, result.outcome, result.missing_parameters) + for result in real_run.results + ] + assert dry_run.closing_check == real_run.closing_check + + +def test_a_second_run_finds_nothing_left_to_migrate( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + _save( + v2_owner_sessions, + UserPolicy, + user_id=stored_rows.first_user, + legacy_policy_id=CTC_REFORM, + ) + _save( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=ECONOMY_REPORT, + ) + simulation_service = _simulation_service(v2_owner_sessions, stored_rows) + service = _service(runtime_sessions, v1_sessions, simulation_service) + _migrate(service, stored_rows) + + second = _migrate(service, stored_rows) + + assert second.results == () + assert second.closing_check.passed + assert len(simulation_service.definitions) == 1 + + +def test_the_limit_leaves_rows_the_closing_check_counts( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + for legacy_policy_id in (CTC_REFORM, CTC_REFORM_WITH_ELASTICITY): + _save( + v2_owner_sessions, + UserPolicy, + user_id=stored_rows.first_user, + legacy_policy_id=legacy_policy_id, + ) + service = _service( + runtime_sessions, + v1_sessions, + _simulation_service(v2_owner_sessions, stored_rows), + ) + + run = _migrate(service, stored_rows, limit=1) + + assert [result.outcome for result in run.results] == [RowOutcome.MIGRATED] + assert _remaining(run, SavedRecordKind.SAVED_REFORM).not_attempted == 1 + assert not run.closing_check.passed diff --git a/tests/unit/test_migrate_saved_records_script.py b/tests/unit/test_migrate_saved_records_script.py new file mode 100644 index 000000000..36346072e --- /dev/null +++ b/tests/unit/test_migrate_saved_records_script.py @@ -0,0 +1,222 @@ +"""Tests for the one-time command that migrates saved records' v1 references.""" + +from __future__ import annotations + +import json +import subprocess +import sys +from contextlib import contextmanager +from typing import TYPE_CHECKING +from uuid import UUID + +import pytest +from policyengine_api.services.v2.saved_record_migration.transformations import ( + closing_check, +) +from policyengine_api.services.v2.saved_record_migration.types import ( + MigrationOptions, + MigrationRun, + RowOutcome, + SavedRecordKind, + SavedRecordResult, +) + +from policyengine_api.constants import REPO +from scripts import migrate_saved_records_to_detailed_save as command + +if TYPE_CHECKING: + from collections.abc import Iterator + +FIRST_USER = UUID("00000000-0000-0000-0000-00000000d411") +SECOND_USER = UUID("00000000-0000-0000-0000-00000000d412") +SAVED_ROW = UUID("00000000-0000-0000-0000-00000000d413") + + +class FakeMigrator: + """Record the options each run gets; leave ``remaining`` rows behind.""" + + def __init__(self, remaining: set[UUID] | None = None) -> None: + self.remaining = remaining or set() + self.options: list[MigrationOptions] = [] + + def migrate(self, options: MigrationOptions) -> MigrationRun: + self.options.append(options) + results = ( + SavedRecordResult( + kind=SavedRecordKind.SAVED_REFORM, + row_id=SAVED_ROW, + country_id="us", + legacy_id=12, + outcome=RowOutcome.MIGRATED, + ), + ) + remaining = {kind: set() for kind in SavedRecordKind} + remaining[SavedRecordKind.SAVED_HOUSEHOLD] = self.remaining + return MigrationRun( + options=options, + policyengine_version="6.20.0", + results=results, + closing_check=closing_check(remaining, results), + ) + + +class RecordingFactory: + """Build ``migrator``, recording whether each build was for a dry run.""" + + def __init__(self, migrator: FakeMigrator) -> None: + self.migrator = migrator + self.dry_runs: list[bool] = [] + + @contextmanager + def __call__(self, *, dry_run: bool) -> Iterator[FakeMigrator]: + self.dry_runs.append(dry_run) + yield self.migrator + + +def _run(arguments: list[str], factory: RecordingFactory) -> int: + return command.main(arguments, migrator_factory=factory) + + +def test_a_dry_run_reads_only_and_prints_the_document(capsys) -> None: + factory = RecordingFactory(FakeMigrator()) + + exit_code = _run(["--dry-run"], factory) + + assert exit_code == 0 + assert factory.dry_runs == [True] + (options,) = factory.migrator.options + assert options == MigrationOptions(apply=False) + document = json.loads(capsys.readouterr().out) + assert document["mode"] == "dry_run" + assert document["rows"][0]["row_id"] == str(SAVED_ROW) + + +def test_without_dry_run_it_migrates_with_the_flags_options(capsys) -> None: + factory = RecordingFactory(FakeMigrator()) + + exit_code = _run( + [ + "--drop-missing-parameters", + "--country", + "us", + "--limit", + "25", + "--user-id", + str(FIRST_USER), + "--user-id", + str(SECOND_USER), + ], + factory, + ) + + assert exit_code == 0 + assert factory.dry_runs == [False] + assert factory.migrator.options == [ + MigrationOptions( + apply=True, + drop_missing_parameters=True, + country_ids=("us",), + limit=25, + user_ids=(FIRST_USER, SECOND_USER), + ) + ] + assert json.loads(capsys.readouterr().out)["mode"] == "migrate" + + +def test_both_countries_are_migrated_unless_one_is_named() -> None: + factory = RecordingFactory(FakeMigrator()) + + _run(["--country", "uk", "--country", "us", "--country", "uk"], factory) + + assert factory.migrator.options[0].country_ids == ("uk", "us") + + +def test_rows_left_behind_make_the_command_exit_1(capsys) -> None: + factory = RecordingFactory(FakeMigrator(remaining={SAVED_ROW})) + + exit_code = _run([], factory) + + assert exit_code == 1 + document = json.loads(capsys.readouterr().out) + assert document["closing_check"]["passed"] is False + + +@pytest.mark.parametrize( + "arguments", + [ + ["--limit", "0"], + ["--limit", "many"], + ["--country", "ca"], + ["--user-id", "not-a-uuid"], + ["--apply"], + ], +) +def test_bad_arguments_exit_2_without_building_a_migrator(arguments) -> None: + factory = RecordingFactory(FakeMigrator()) + + with pytest.raises(SystemExit) as stopped: + _run(arguments, factory) + + assert stopped.value.code == 2 + assert factory.dry_runs == [] + + +def test_v1_is_read_as_the_read_only_role_through_the_proxy() -> None: + url = command.v1_read_only_database_url( + {"POLICYENGINE_DB_READONLY_PASSWORD": "reader-secret"} + ) + + assert (url.drivername, url.username, url.host, url.port, url.database) == ( + "mysql+pymysql", + "policyengine_schema_reader", + "127.0.0.1", + 3307, + "policyengine", + ) + assert url.password == "reader-secret" + assert "reader-secret" not in str(url) + + +def test_the_proxy_port_can_be_given() -> None: + url = command.v1_read_only_database_url( + { + "POLICYENGINE_DB_READONLY_PASSWORD": "reader-secret", + "POLICYENGINE_DB_PROXY_PORT": "3310", + } + ) + + assert url.port == 3310 + + +def test_v1_without_the_read_only_password_is_refused() -> None: + with pytest.raises(command.MissingSettingError, match="READONLY_PASSWORD"): + command.v1_read_only_database_url({}) + + +def test_loading_the_command_leaves_the_observability_runtime_unbuilt() -> None: + """The command and what its factory loads mustn't build the runtime. + + Importing ``policyengine_api.observability`` builds the process-wide + runtime, which adds a root log handler and, with no OTLP endpoint, writes + an ERROR record to the command's output. + """ + import_check = ( + "import sys\n" + "import scripts.migrate_saved_records_to_detailed_save\n" + "import policyengine_api.data.v2.database\n" + "import policyengine_api.data.v1_sessions\n" + "import policyengine_api.services.v2.saved_record_migration.database_session\n" + "import policyengine_api.services.v2.saved_record_migration.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_saved_record_migration_rules.py b/tests/unit/v2/test_saved_record_migration_rules.py new file mode 100644 index 000000000..d061092a4 --- /dev/null +++ b/tests/unit/v2/test_saved_record_migration_rules.py @@ -0,0 +1,558 @@ +"""The one-time migration's rules that need no database (D4 · 1). + +They rebuild a v1 report's definition from its v1 rows, translate a v1 region +into a catalog region code, keep only the parameters a running catalog still +has, build the detailed-save report definition, and work out the closing +check and the command's JSON document. +""" + +from __future__ import annotations + +import json +from uuid import UUID + +import pytest +from policyengine_api.services.v2.saved_record_migration.transformations import ( + closing_check, + detailed_save_report_definition, + kept_policy_snapshot, + migration_document, +) +from policyengine_api.services.v2.saved_record_migration.types import ( + DetailedSaveReportKind, + FailureReason, + MigrationOptions, + MigrationRun, + PolicySide, + RowOutcome, + SavedRecordKind, + SavedRecordResult, + V1ReportDefinition, + V1ReportKind, + V1ReportRecord, + V1SimulationRecord, +) +from policyengine_api.services.v2.saved_record_migration.validators import ( + SavedRecordMigrationRefusal, + require_catalog_region_code, + validate_v1_report, +) + +from policyengine_api.data.v2.catalog.region_references import ( + load_region_references, +) +from policyengine_api.services.v2.policies.transformations import split_legacy_policy +from policyengine_api.services.v2.policies.types import LegacyPolicySnapshot + +US_CTC_AMOUNT = "gov.irs.credits.ctc.amount.base" +US_INCOME_ELASTICITY = "gov.simulation.labor_supply_responses.elasticities.income" +UK_INCOME_ELASTICITY = "gov.simulation.labour_supply_responses.income_elasticity" +UK_OLD_INCOME_ELASTICITY = "gov.simulation.labor_supply_responses.income_elasticity" +UK_PERSONAL_ALLOWANCE = "gov.hmrc.income_tax.allowances.personal_allowance.amount" +REMOVED_PARAMETER = "gov.simulation.reported_snap" +FIRST_ROW = UUID("00000000-0000-0000-0000-00000000d401") +SECOND_ROW = UUID("00000000-0000-0000-0000-00000000d402") +THIRD_ROW = UUID("00000000-0000-0000-0000-00000000d403") +FOURTH_ROW = UUID("00000000-0000-0000-0000-00000000d404") +POLICY_ID = UUID("00000000-0000-0000-0000-00000000d405") +DYNAMIC_ID = UUID("00000000-0000-0000-0000-00000000d406") +HOUSEHOLD_ID = UUID("00000000-0000-0000-0000-00000000d407") + + +def _report( + *, year: str = "2026", simulation_2_id: int | None = 12, country_id: str = "us" +) -> V1ReportRecord: + return V1ReportRecord( + country_id=country_id, + report_id=900, + year=year, + simulation_1_id=11, + simulation_2_id=simulation_2_id, + ) + + +def _simulation( + simulation_id: int, + *, + population_type: str = "geography", + population_id: str = "state/ca", + policy_id: int = 2, + country_id: str = "us", +) -> V1SimulationRecord: + return V1SimulationRecord( + simulation_id=simulation_id, + country_id=country_id, + population_type=population_type, + population_id=population_id, + policy_id=policy_id, + ) + + +def _snapshot(country_id: str, policy_json: dict[str, object]) -> LegacyPolicySnapshot: + return LegacyPolicySnapshot( + country_id=country_id, + legacy_policy_id=55, + label="Saved reform", + api_version="1.0.0", + policy_json=policy_json, + source_policy_hash="legacy-hash-55", + ) + + +def _result( + row_id: UUID, + outcome: RowOutcome, + *, + kind: SavedRecordKind = SavedRecordKind.SAVED_REFORM, + **fields: object, +) -> SavedRecordResult: + return SavedRecordResult( + kind=kind, + row_id=row_id, + country_id="us", + legacy_id=55, + outcome=outcome, + **fields, + ) + + +def _remaining(**rows_by_kind: set[UUID]) -> dict[SavedRecordKind, set[UUID]]: + remaining = {kind: set() for kind in SavedRecordKind} + remaining.update( + {SavedRecordKind(kind): rows for kind, rows in rows_by_kind.items()} + ) + return remaining + + +# A v1 report's definition, from its report output and simulations. + + +def test_an_economy_comparison_compares_simulation_one_with_simulation_two() -> None: + definition = validate_v1_report( + _report(), _simulation(11, policy_id=2), _simulation(12, policy_id=77) + ) + + assert definition == V1ReportDefinition( + country_id="us", + legacy_report_id=900, + kind=V1ReportKind.ECONOMY, + year=2026, + region="state/ca", + legacy_household_id=None, + baseline_policy_id=2, + reform_policy_id=77, + ) + + +def test_a_single_economy_simulation_names_its_policy_on_both_sides() -> None: + definition = validate_v1_report( + _report(simulation_2_id=None), _simulation(11, policy_id=77), None + ) + + assert definition.kind is V1ReportKind.ECONOMY + assert definition.baseline_policy_id == 77 + assert definition.reform_policy_id == 77 + + +def test_a_household_comparison_names_the_household_and_both_policies() -> None: + definition = validate_v1_report( + _report(), + _simulation(11, population_type="household", population_id="0501"), + _simulation(12, population_type="household", population_id="501", policy_id=77), + ) + + assert definition.kind is V1ReportKind.HOUSEHOLD + assert definition.legacy_household_id == 501 + assert definition.region is None + assert (definition.baseline_policy_id, definition.reform_policy_id) == (2, 77) + + +def test_a_single_household_simulation_has_no_reform() -> None: + definition = validate_v1_report( + _report(simulation_2_id=None), + _simulation(11, population_type="household", population_id="501"), + None, + ) + + assert definition.reform_policy_id is None + assert definition.baseline_policy_id == 2 + + +@pytest.mark.parametrize( + ("report", "simulation_1", "simulation_2"), + [ + pytest.param( + _report(), + _simulation(11), + _simulation(12, population_type="household", population_id="501"), + id="population types differ", + ), + pytest.param( + _report(), + _simulation(11), + _simulation(12, population_id="state/ny"), + id="regions differ", + ), + pytest.param( + _report(), + _simulation(11, population_type="household", population_id="501"), + _simulation(12, population_type="household", population_id="502"), + id="households differ", + ), + pytest.param( + _report(), + _simulation(11, population_type="household", population_id="first"), + _simulation(12, population_type="household", population_id="first"), + id="household ID not a number", + ), + pytest.param( + _report(simulation_2_id=None), + _simulation(11, population_type="county"), + None, + id="unknown population type", + ), + pytest.param( + _report(year="next year"), + _simulation(11), + _simulation(12), + id="year not a number", + ), + pytest.param( + _report(), + _simulation(11, country_id="uk"), + _simulation(12), + id="simulation of another country", + ), + pytest.param( + _report(simulation_2_id=None), + _simulation(11), + _simulation(12), + id="a second simulation the report doesn't name", + ), + pytest.param( + _report(), + _simulation(11), + None, + id="the report's second simulation is missing", + ), + ], +) +def test_a_v1_report_that_cant_be_rebuilt_is_refused( + report: V1ReportRecord, + simulation_1: V1SimulationRecord, + simulation_2: V1SimulationRecord | None, +) -> None: + with pytest.raises(SavedRecordMigrationRefusal) as refusal: + validate_v1_report(report, simulation_1, simulation_2) + + assert refusal.value.reason is FailureReason.V1_REPORT_UNREADABLE + + +# v1 regions, as catalog region codes. + + +@pytest.mark.parametrize( + ("country_id", "v1_region", "catalog_code"), + [ + ("uk", "constituency/Aldershot", "constituency/E14001063"), + ("uk", "constituency/aldershot", "constituency/E14001063"), + ("uk", "constituency/E14001063", "constituency/E14001063"), + ("uk", "local_authority/Hartlepool", "local_authority/E06000001"), + ("uk", "country/wales", "country/wales"), + ("uk", "Wales", "country/wales"), + ("uk", "uk", "uk"), + ("uk", "", "uk"), + ("us", "us", "us"), + ("us", "state/ca", "state/ca"), + ("us", "ca", "state/ca"), + ("us", "CA", "state/ca"), + ("us", "place/AK-03000", "place/AK-03000"), + ("us", "congressional_district/AK-01", "congressional_district/AK-01"), + ], +) +def test_a_v1_region_becomes_its_catalog_code( + country_id: str, v1_region: str, catalog_code: str +) -> None: + references = load_region_references(country_id) + + assert ( + require_catalog_region_code(country_id, v1_region, references) == catalog_code + ) + + +@pytest.mark.parametrize( + ("country_id", "v1_region"), + [("uk", "constituency/Nowhere"), ("us", "state/zz"), ("us", "county/06037")], +) +def test_a_v1_region_with_no_catalog_code_is_refused( + country_id: str, v1_region: str +) -> None: + with pytest.raises(SavedRecordMigrationRefusal) as refusal: + require_catalog_region_code( + country_id, v1_region, load_region_references(country_id) + ) + + assert refusal.value.reason is FailureReason.UNKNOWN_REGION + assert v1_region in str(refusal.value) + + +# Keeping only the parameters the running catalog has. + + +def test_missing_parameters_are_left_out_and_the_rest_kept() -> None: + snapshot = _snapshot( + "us", + { + US_CTC_AMOUNT: {"2026-01-01.2100-12-31": 3000}, + US_INCOME_ELASTICITY: {"2026-01-01.2100-12-31": 0.1}, + REMOVED_PARAMETER: {"2026-01-01.2100-12-31": True}, + }, + ) + + kept = kept_policy_snapshot( + snapshot, split_legacy_policy(snapshot), missing=[REMOVED_PARAMETER] + ) + + assert kept.policy_json == { + US_CTC_AMOUNT: {"2026-01-01.2100-12-31": 3000}, + US_INCOME_ELASTICITY: {"2026-01-01.2100-12-31": 0.1}, + } + assert kept.model_dump(exclude={"policy_json"}) == snapshot.model_dump( + exclude={"policy_json"} + ) + + +def test_kept_uk_parameters_take_their_current_spelling() -> None: + snapshot = _snapshot( + "uk", + { + UK_OLD_INCOME_ELASTICITY: {"2026-01-01.2100-12-31": 0.2}, + UK_PERSONAL_ALLOWANCE: {"2026-01-01.2100-12-31": 15000}, + }, + ) + + kept = kept_policy_snapshot( + snapshot, split_legacy_policy(snapshot), missing=[UK_PERSONAL_ALLOWANCE] + ) + + assert kept.policy_json == {UK_INCOME_ELASTICITY: {"2026-01-01.2100-12-31": 0.2}} + + +# The detailed-save report definition. + + +def _v1_definition( + kind: V1ReportKind = V1ReportKind.ECONOMY, *, reform_policy_id: int | None = 77 +) -> V1ReportDefinition: + return V1ReportDefinition( + country_id="us", + legacy_report_id=900, + kind=kind, + year=2026, + region="state/ca" if kind is V1ReportKind.ECONOMY else None, + legacy_household_id=501 if kind is V1ReportKind.HOUSEHOLD else None, + baseline_policy_id=2, + reform_policy_id=reform_policy_id, + ) + + +@pytest.mark.parametrize("budget_window_years", [None, 1]) +def test_an_economy_report_without_a_window_is_an_economy_report( + budget_window_years: int | None, +) -> None: + reform = PolicySide(policy_id=POLICY_ID, dynamic_id=DYNAMIC_ID) + + definition = detailed_save_report_definition( + _v1_definition(), + baseline=PolicySide(policy_id=None, dynamic_id=None), + reform=reform, + region_code="state/ca", + household_id=None, + budget_window_years=budget_window_years, + ) + + assert definition.kind is DetailedSaveReportKind.ECONOMY + assert definition.year == 2026 + assert definition.region_code == "state/ca" + assert definition.budget_window_size is None + assert definition.reform == reform + assert definition.household_id is None + + +def test_a_saved_window_of_two_or_more_years_makes_a_budget_window() -> None: + definition = detailed_save_report_definition( + _v1_definition(), + baseline=PolicySide(policy_id=None, dynamic_id=None), + reform=PolicySide(policy_id=POLICY_ID, dynamic_id=None), + region_code="us", + household_id=None, + budget_window_years=10, + ) + + assert definition.kind is DetailedSaveReportKind.BUDGET_WINDOW + assert definition.budget_window_size == 10 + assert definition.year == 2026 + + +def test_a_household_report_names_its_household_and_no_year_or_region() -> None: + definition = detailed_save_report_definition( + _v1_definition(V1ReportKind.HOUSEHOLD, reform_policy_id=None), + baseline=PolicySide(policy_id=POLICY_ID, dynamic_id=None), + reform=None, + region_code=None, + household_id=HOUSEHOLD_ID, + budget_window_years=None, + ) + + assert definition.kind is DetailedSaveReportKind.HOUSEHOLD + assert definition.household_id == HOUSEHOLD_ID + assert definition.reform is None + assert definition.year is None + assert definition.region_code is None + + +# The closing check. + + +def test_rows_left_for_missing_parameters_or_listed_simulations_pass() -> None: + check = closing_check( + _remaining( + saved_reform={FIRST_ROW, SECOND_ROW}, + saved_simulation={THIRD_ROW}, + ), + [ + _result(FIRST_ROW, RowOutcome.MISSING_PARAMETERS), + _result(SECOND_ROW, RowOutcome.EVERY_PARAMETER_MISSING), + _result( + THIRD_ROW, + RowOutcome.NOT_MIGRATED, + kind=SavedRecordKind.SAVED_SIMULATION, + ), + ], + ) + + assert check.passed + by_kind = {remaining.kind: remaining for remaining in check.remaining} + assert by_kind[SavedRecordKind.SAVED_REFORM].missing_parameters == 1 + assert by_kind[SavedRecordKind.SAVED_REFORM].every_parameter_missing == 1 + assert by_kind[SavedRecordKind.SAVED_SIMULATION].not_migrated == 1 + assert [remaining.kind for remaining in check.remaining] == list(SavedRecordKind) + + +def test_a_failed_row_fails_the_check() -> None: + check = closing_check( + _remaining(saved_report={FIRST_ROW}), + [ + _result( + FIRST_ROW, + RowOutcome.FAILED, + kind=SavedRecordKind.SAVED_REPORT, + failure_reason=FailureReason.UNKNOWN_REGION, + ) + ], + ) + + assert not check.passed + by_kind = {remaining.kind: remaining for remaining in check.remaining} + assert by_kind[SavedRecordKind.SAVED_REPORT].failed == 1 + + +def test_a_remaining_row_the_run_didnt_reach_fails_the_check() -> None: + check = closing_check(_remaining(saved_household={FOURTH_ROW}), []) + + assert not check.passed + by_kind = {remaining.kind: remaining for remaining in check.remaining} + assert by_kind[SavedRecordKind.SAVED_HOUSEHOLD].not_attempted == 1 + + +def test_a_dry_run_does_not_count_rows_it_would_migrate() -> None: + check = closing_check( + _remaining(saved_reform={FIRST_ROW}), + [_result(FIRST_ROW, RowOutcome.MIGRATED)], + ) + + assert check.passed + assert all( + ( + remaining.missing_parameters, + remaining.every_parameter_missing, + remaining.failed, + remaining.not_attempted, + remaining.not_migrated, + ) + == (0, 0, 0, 0, 0) + for remaining in check.remaining + ) + + +# The command's JSON document. + + +def test_the_document_lists_every_row_its_counts_and_the_check() -> None: + results = ( + _result( + FIRST_ROW, + RowOutcome.MIGRATED, + detailed_save_id=POLICY_ID, + saved_dynamic_id=DYNAMIC_ID, + dropped_parameters=(REMOVED_PARAMETER,), + ), + _result( + SECOND_ROW, + RowOutcome.FAILED, + kind=SavedRecordKind.SAVED_REPORT, + failure_reason=FailureReason.REPORT_REFUSED, + failure_detail="unknown_region", + ), + ) + run = MigrationRun( + options=MigrationOptions( + apply=True, drop_missing_parameters=True, country_ids=("us",), limit=5 + ), + policyengine_version="6.20.0", + results=results, + closing_check=closing_check(_remaining(saved_report={SECOND_ROW}), results), + ) + + document = json.loads(json.dumps(migration_document(run))) + + assert document["mode"] == "migrate" + assert document["drop_missing_parameters"] is True + assert document["countries"] == ["us"] + assert document["limit"] == 5 + assert document["policyengine_version"] == "6.20.0" + assert document["counts"]["saved_reform"] == {"migrated": 1} + assert document["counts"]["saved_report"] == {"failed": 1} + assert document["rows"][0] == { + "kind": "saved_reform", + "row_id": str(FIRST_ROW), + "country_id": "us", + "legacy_id": 55, + "outcome": "migrated", + "detailed_save_id": str(POLICY_ID), + "saved_dynamic_id": str(DYNAMIC_ID), + "missing_parameters": [], + "dropped_parameters": [REMOVED_PARAMETER], + "failure_reason": None, + "failure_detail": None, + "notes": [], + } + assert document["rows"][1]["failure_reason"] == "report_refused" + assert document["closing_check"]["passed"] is False + assert document["closing_check"]["remaining"]["saved_report"]["failed"] == 1 + + +def test_a_dry_run_document_says_so() -> None: + run = MigrationRun( + options=MigrationOptions(apply=False), + policyengine_version="6.20.0", + results=(), + closing_check=closing_check(_remaining(), ()), + ) + + document = migration_document(run) + + assert document["mode"] == "dry_run" + assert document["countries"] == ["uk", "us"] + assert document["limit"] is None + assert document["rows"] == [] From cf54eb440925051139e45b48466dc31ebf6e68d0 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:28:56 +0400 Subject: [PATCH 02/22] Add a failing test that CI runs the saved-record migration's tests The cross-database integration workflow must run the migration's PostgreSQL and MySQL tests after the managed roles' grants are checked. The integration tests also take a catalog version of their own that is a canonical PEP 440 version, as stored policies require. Co-Authored-By: Claude Opus 5.5 --- .../test_v2_saved_record_migration.py | 3 ++- tests/unit/test_v2_integration_workflow.py | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/tests/integration/test_v2_saved_record_migration.py b/tests/integration/test_v2_saved_record_migration.py index a5e9ed7d0..a859cbafa 100644 --- a/tests/integration/test_v2_saved_record_migration.py +++ b/tests/integration/test_v2_saved_record_migration.py @@ -78,7 +78,8 @@ from tests.integration.conftest import ManagedV2Roles -RUNNING_VERSION = "d4-1-migration-test" +# A catalog version of its own, so it meets no other test's catalog. +RUNNING_VERSION = "940.1.0" CTC_AMOUNT = "gov.irs.credits.ctc.amount.base" EITC_RATE = "gov.irs.credits.eitc.phase_in_rate" INCOME_ELASTICITY = "gov.simulation.labor_supply_responses.elasticities.income" diff --git a/tests/unit/test_v2_integration_workflow.py b/tests/unit/test_v2_integration_workflow.py index dd0c5b185..38a4bece0 100644 --- a/tests/unit/test_v2_integration_workflow.py +++ b/tests/unit/test_v2_integration_workflow.py @@ -113,3 +113,22 @@ def test_the_job_publishes_dynamic_parameters_into_their_own_tables() -> None: "tests/integration/test_v2_catalog_publication_dynamic_parameters.py" in command for command in commands ) + + +def test_the_job_runs_the_saved_record_migration_tests() -> None: + """The one-time saved-record migration's cross-database tests run (D4 · 1). + + They read v1's rows in MySQL and write the detailed-save tables in + PostgreSQL as policyengine_v2_runtime, after the schema upgrades and the + role grants. + """ + commands = _step_commands(_runtime_job()) + + (command,) = [ + command + for command in commands + if "tests/integration/test_v2_saved_record_migration.py" in command + ] + assert commands.index(command) > commands.index( + "uv run --frozen --extra dev python scripts/reconcile_v2_privileges.py verify" + ) From 69569713faaa3e834a77be51525d12b81e0a82bb Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:32:27 +0400 Subject: [PATCH 03/22] Add the one-time command that migrates saved records' API v1 references MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit scripts/migrate_saved_records_to_detailed_save.py gives saved reforms, saved households and saved reports that hold only an API v1 reference their API v2 records (D4 · 1), keeping the API v1 reference: - a saved reform gets its API v1 policy's copy from API v1's policy copy into API v2 (mirror_legacy_policy_in_session, which splits model assumptions into a dynamic), and a saved dynamic with its name when the policy sets assumptions (create_user_dynamic_in_session); - a saved household gets its API v1 household's copy; - a saved report gets the report the simulation service finds or creates for the API v1 report's definition, each side's policy split the same way, a side left with no policy values naming no policy, and its region translated through the catalog's region reference files. Saved simulations are only listed. Rows whose policies set a parameter the running catalog lacks are left and listed; --drop-missing-parameters migrates them from the parameters that still exist, without an API v1 ID mapping, and still leaves a row whose every parameter is missing. A dry run writes nothing. The command prints a JSON document with every row's result and a closing check, and exits 1 when rows are left that the decisions don't leave. It connects as the runtime role and reads API v1 as its read-only role. The cross-database workflow runs its tests. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/v2-integration-check.yml | 2 + changelog.d/saved-record-migration.added.md | 1 + .../v2/saved_record_migration/__init__.py | 1 + .../saved_record_migration/copies/__init__.py | 1 + .../saved_record_migration/copies/services.py | 309 +++++++++ .../database_connectors/__init__.py | 1 + .../database_connectors/reads.py | 149 +++++ .../database_connectors/reads_v1_records.py | 128 ++++ .../database_connectors/updates.py | 79 +++ .../database_session.py | 60 ++ .../v2/saved_record_migration/services.py | 618 ++++++++++++++++++ .../saved_record_migration/transformations.py | 284 ++++++++ .../v2/saved_record_migration/types.py | 303 +++++++++ .../v2/saved_record_migration/validators.py | 200 ++++++ pyproject.toml | 3 + .../migrate_saved_records_to_detailed_save.py | 247 +++++++ .../test_v2_saved_record_migration.py | 40 +- .../unit/test_migrate_saved_records_script.py | 4 +- .../v2/test_saved_record_migration_rules.py | 12 +- 19 files changed, 2414 insertions(+), 28 deletions(-) create mode 100644 changelog.d/saved-record-migration.added.md create mode 100644 policyengine_api/services/v2/saved_record_migration/__init__.py create mode 100644 policyengine_api/services/v2/saved_record_migration/copies/__init__.py create mode 100644 policyengine_api/services/v2/saved_record_migration/copies/services.py create mode 100644 policyengine_api/services/v2/saved_record_migration/database_connectors/__init__.py create mode 100644 policyengine_api/services/v2/saved_record_migration/database_connectors/reads.py create mode 100644 policyengine_api/services/v2/saved_record_migration/database_connectors/reads_v1_records.py create mode 100644 policyengine_api/services/v2/saved_record_migration/database_connectors/updates.py create mode 100644 policyengine_api/services/v2/saved_record_migration/database_session.py create mode 100644 policyengine_api/services/v2/saved_record_migration/services.py create mode 100644 policyengine_api/services/v2/saved_record_migration/transformations.py create mode 100644 policyengine_api/services/v2/saved_record_migration/types.py create mode 100644 policyengine_api/services/v2/saved_record_migration/validators.py create mode 100755 scripts/migrate_saved_records_to_detailed_save.py diff --git a/.github/workflows/v2-integration-check.yml b/.github/workflows/v2-integration-check.yml index cad76f6f9..4822b754b 100644 --- a/.github/workflows/v2-integration-check.yml +++ b/.github/workflows/v2-integration-check.yml @@ -79,6 +79,8 @@ jobs: run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_policy_persistence.py tests/integration/test_v2_dynamic_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 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 the one-time migration of saved records' v1 references + run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_saved_record_migration.py - name: Test comparison-run persistence, the simulation API's roles, shared reports and runs, privilege reconciliation as the managed roles, the v2 migration target checks as roles that don't own the database, and the tests' database sessions run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_stage12_comparison_persistence.py tests/integration/test_v2_simulation_role_privileges.py tests/integration/test_v2_shared_report_rows.py tests/integration/test_v2_privilege_reconciliation.py tests/integration/test_v2_migration_target_persistent.py tests/integration/test_database_sessions.py - name: Test v2 household persistence, immediate v1 copying, household calculation reads and household reports diff --git a/changelog.d/saved-record-migration.added.md b/changelog.d/saved-record-migration.added.md new file mode 100644 index 000000000..9ffdb50d3 --- /dev/null +++ b/changelog.d/saved-record-migration.added.md @@ -0,0 +1 @@ +Add API v1's one-time command that gives saved reforms, saved households and saved reports holding only a v1 reference their detailed-save records, splitting each v1 policy's model assumptions into a dynamic, with a dry run, a mode that drops parameters the running catalog lacks, and a closing check. diff --git a/policyengine_api/services/v2/saved_record_migration/__init__.py b/policyengine_api/services/v2/saved_record_migration/__init__.py new file mode 100644 index 000000000..f2a2ac0f2 --- /dev/null +++ b/policyengine_api/services/v2/saved_record_migration/__init__.py @@ -0,0 +1 @@ +"""The one-time migration of saved records' v1 references (D4 · 1).""" diff --git a/policyengine_api/services/v2/saved_record_migration/copies/__init__.py b/policyengine_api/services/v2/saved_record_migration/copies/__init__.py new file mode 100644 index 000000000..aadcb02ed --- /dev/null +++ b/policyengine_api/services/v2/saved_record_migration/copies/__init__.py @@ -0,0 +1 @@ +"""The policy and household copies the one-time saved-record migration makes.""" diff --git a/policyengine_api/services/v2/saved_record_migration/copies/services.py b/policyengine_api/services/v2/saved_record_migration/copies/services.py new file mode 100644 index 000000000..000a3ed58 --- /dev/null +++ b/policyengine_api/services/v2/saved_record_migration/copies/services.py @@ -0,0 +1,309 @@ +"""The policy and household copies the one-time saved-record migration makes. + +A v1 policy is planned before anything is written: its parameters are looked +up in the running catalog, its policy's among policy parameters and its +model assumptions among dynamic parameters, and the parameters the catalog +lacks are listed. A whole v1 policy is then copied by the v1-to-v2 copy +(``mirror_legacy_policy_in_session``), which splits its model assumptions +into a dynamic and maps the v1 ID to the pair. What the second mode keeps of +a policy with missing parameters is stored on its own, without a v1 ID +mapping, since it isn't a copy of the v1 policy (A1 · 6). A v1 household is +copied by ``mirror_legacy_household_in_session``. Each step works in the +caller's session, and a step that can't copy raises +SavedRecordMigrationRefusal with its reason. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from pydantic import ValidationError + +from policyengine_api.data.v2.catalog.catalog_selection_validation import ( + MetadataCatalogNotPublishedError, +) +from policyengine_api.services.v2.dynamics.database_connectors.reads import ( + read_dynamic_parameters_by_name, +) +from policyengine_api.services.v2.dynamics.transformations import ( + dynamic_creation_input, +) +from policyengine_api.services.v2.dynamics.validators import ( + DynamicCreationIntegrityError, +) +from policyengine_api.services.v2.households.database_connectors.reads import ( + read_legacy_household_mapping, +) +from policyengine_api.services.v2.households.transformations import ( + translate_legacy_household, +) +from policyengine_api.services.v2.households.validators import ( + HouseholdCreationIntegrityError, + HouseholdValidationError, + LegacyHouseholdMappingIntegrityError, + LegacyHouseholdTranslationError, +) +from policyengine_api.services.v2.policies.database_connectors.reads import ( + read_legacy_policy_mapping, + read_parameters_by_name, + read_policy_catalog, +) +from policyengine_api.services.v2.policies.transformations import ( + split_legacy_policy, + translate_legacy_policy, +) +from policyengine_api.services.v2.policies.validators import ( + LegacyPolicyMappingIntegrityError, + LegacyPolicyTranslationError, + PolicyCatalogValidationError, + PolicyCreationIntegrityError, +) +from policyengine_api.services.v2.saved_record_migration.database_connectors.reads import ( # noqa: E501 # a dotted module path cannot be wrapped + read_household_default_year, +) +from policyengine_api.services.v2.saved_record_migration.transformations import ( + kept_policy_snapshot, +) +from policyengine_api.services.v2.saved_record_migration.types import ( + FailureReason, + PolicyMigrationPlan, + PolicySide, + StoredPolicy, +) +from policyengine_api.services.v2.saved_record_migration.validators import ( + SavedRecordMigrationRefusal, +) + +if TYPE_CHECKING: + from uuid import UUID + + from sqlmodel import Session + + from policyengine_api.data.v2.models import DynamicParameter, Parameter + from policyengine_api.services.v2.households.types import ( + LegacyHouseholdSnapshot, + ) + from policyengine_api.services.v2.policies.types import LegacyPolicySnapshot + +POLICY_COPY_ERRORS = ( + LegacyPolicyTranslationError, + LegacyPolicyMappingIntegrityError, + PolicyCatalogValidationError, + PolicyCreationIntegrityError, + DynamicCreationIntegrityError, + ValidationError, +) +HOUSEHOLD_COPY_ERRORS = ( + LegacyHouseholdTranslationError, + LegacyHouseholdMappingIntegrityError, + HouseholdValidationError, + HouseholdCreationIntegrityError, + ValidationError, +) + + +def _not_copyable( + snapshot: LegacyPolicySnapshot, error: Exception +) -> SavedRecordMigrationRefusal: + return SavedRecordMigrationRefusal( + FailureReason.POLICY_NOT_COPYABLE, + f"v1 policy {snapshot.legacy_policy_id} can't be copied: {error}", + ) + + +def plan_policy_in_session( + session: Session, + snapshot: LegacyPolicySnapshot, + *, + drop_missing_parameters: bool, + running_policyengine_version: str, +) -> PolicyMigrationPlan: + """Work out how the v1 policy migrates, writing nothing. + + A whole v1 policy without a copy is translated, so an error the copy + would raise is found before anything is written. In the second mode, + what is kept of a policy with missing parameters is translated too. + """ + try: + selected = read_policy_catalog( + session, + snapshot.country_id, + running_policyengine_version=running_policyengine_version, + ) + except MetadataCatalogNotPublishedError as error: + msg = f"the running catalog of {snapshot.country_id} isn't published" + raise SavedRecordMigrationRefusal( + FailureReason.CATALOG_NOT_PUBLISHED, msg + ) from error + try: + split = split_legacy_policy(snapshot) + parameters: dict[str, Parameter | DynamicParameter] = { + **read_parameters_by_name( + session, + model_version_id=selected.model_version.id, + names=set(split.policy_values), + ), + **read_dynamic_parameters_by_name( + session, + model_version_id=selected.model_version.id, + names=set(split.dynamic_values), + ), + } + missing = tuple( + sorted({*split.policy_values, *split.dynamic_values} - set(parameters)) + ) + if missing and not drop_missing_parameters: + return PolicyMigrationPlan( + snapshot=snapshot, + missing_parameters=missing, + sets_policy_values=bool(split.policy_values), + sets_dynamic_values=bool(split.dynamic_values), + ) + if not missing: + mapping = read_legacy_policy_mapping( + session, + country_id=snapshot.country_id, + legacy_policy_id=snapshot.legacy_policy_id, + lock=False, + ) + if mapping is None: + translate_legacy_policy( + snapshot, selected=selected, parameters=parameters + ) + return PolicyMigrationPlan( + snapshot=snapshot, + missing_parameters=(), + sets_policy_values=bool(split.policy_values), + sets_dynamic_values=bool(split.dynamic_values), + existing_policy_id=None if mapping is None else mapping.policy_id, + existing_dynamic_id=None if mapping is None else mapping.dynamic_id, + ) + kept = kept_policy_snapshot(snapshot, split, missing=missing) + kept_split = split_legacy_policy(kept) + if not kept_split.policy_values and not kept_split.dynamic_values: + return PolicyMigrationPlan( + snapshot=snapshot, + missing_parameters=missing, + sets_policy_values=False, + sets_dynamic_values=False, + ) + return PolicyMigrationPlan( + snapshot=snapshot, + missing_parameters=missing, + sets_policy_values=bool(kept_split.policy_values), + sets_dynamic_values=bool(kept_split.dynamic_values), + kept_translation=translate_legacy_policy( + kept, selected=selected, parameters=parameters + ), + ) + except POLICY_COPY_ERRORS as error: + raise _not_copyable(snapshot, error) from error + + +def store_policy_in_session( + session: Session, + plan: PolicyMigrationPlan, + *, + running_policyengine_version: str, +) -> StoredPolicy: + """Store the planned policy and dynamic, or find the ones already stored. + + A whole v1 policy is copied and mapped to its v1 ID by the v1-to-v2 copy, + which returns an existing copy. What the second mode keeps is stored on + its own, with no v1 ID mapping. + """ + from policyengine_api.services.v2.dynamics.services import ( + create_resolved_dynamic, + ) + from policyengine_api.services.v2.policies.services import ( + create_resolved_policy, + mirror_legacy_policy_in_session, + ) + + try: + if plan.kept_translation is None: + copied = mirror_legacy_policy_in_session( + session, + plan.snapshot, + running_policyengine_version=running_policyengine_version, + ) + return StoredPolicy( + policy_id=copied.policy_id, dynamic_id=copied.dynamic_id + ) + policy = create_resolved_policy(session, plan.kept_translation.policy) + dynamic = ( + None + if plan.kept_translation.dynamic is None + else create_resolved_dynamic( + session, dynamic_creation_input(plan.kept_translation.dynamic) + ) + ) + except POLICY_COPY_ERRORS as error: + raise _not_copyable(plan.snapshot, error) from error + return StoredPolicy( + policy_id=policy.policy_id, + dynamic_id=None if dynamic is None else dynamic.dynamic_id, + ) + + +def report_side_in_session( + session: Session, + plan: PolicyMigrationPlan, + *, + apply: bool, + running_policyengine_version: str, +) -> PolicySide: + """Return the report side a v1 policy is: its policy and dynamic, either maybe none. + + A side whose policy keeps no value names no policy, and one with no model + assumptions no dynamic, so v1's current law names neither (C1 · 35, 9a). + A dry run names the existing copy, or none for one a run would make. + """ + if not plan.sets_policy_values and not plan.sets_dynamic_values: + return PolicySide(policy_id=None, dynamic_id=None) + if not apply: + return PolicySide( + policy_id=plan.existing_policy_id if plan.sets_policy_values else None, + dynamic_id=plan.existing_dynamic_id, + ) + stored = store_policy_in_session( + session, plan, running_policyengine_version=running_policyengine_version + ) + return PolicySide( + policy_id=stored.policy_id if plan.sets_policy_values else None, + dynamic_id=stored.dynamic_id, + ) + + +def household_copy_in_session( + session: Session, snapshot: LegacyHouseholdSnapshot, *, apply: bool +) -> tuple[UUID | None, int | None]: + """Return the v1 household's copy and the year it calculates. + + A run finds or makes the copy. A dry run translates the household, to + find the error a copy would raise, and names an existing copy or none. + """ + from policyengine_api.services.v2.households.services import ( + mirror_legacy_household_in_session, + normalize_creation_input, + ) + + try: + if apply: + copied = mirror_legacy_household_in_session(session, snapshot) + return copied.household_id, read_household_default_year( + session, copied.household_id + ) + translated = normalize_creation_input(translate_legacy_household(snapshot)) + except HOUSEHOLD_COPY_ERRORS as error: + msg = f"v1 household {snapshot.legacy_household_id} can't be copied: {error}" + raise SavedRecordMigrationRefusal( + FailureReason.HOUSEHOLD_NOT_COPYABLE, msg + ) from error + mapping = read_legacy_household_mapping( + session, + country_id=snapshot.country_id, + legacy_household_id=snapshot.legacy_household_id, + lock=False, + ) + return None if mapping is None else mapping.household_id, translated.default_year diff --git a/policyengine_api/services/v2/saved_record_migration/database_connectors/__init__.py b/policyengine_api/services/v2/saved_record_migration/database_connectors/__init__.py new file mode 100644 index 000000000..46ef67e95 --- /dev/null +++ b/policyengine_api/services/v2/saved_record_migration/database_connectors/__init__.py @@ -0,0 +1 @@ +"""Database reads and updates of the one-time saved-record migration.""" diff --git a/policyengine_api/services/v2/saved_record_migration/database_connectors/reads.py b/policyengine_api/services/v2/saved_record_migration/database_connectors/reads.py new file mode 100644 index 000000000..e4f4fcea0 --- /dev/null +++ b/policyengine_api/services/v2/saved_record_migration/database_connectors/reads.py @@ -0,0 +1,149 @@ +"""Reads of saved records holding only a v1 reference, for the migration. + +Each read selects one kind's rows that hold a v1 reference and no +detailed-save reference, in the given countries and, optionally, of the +given owners, oldest first, up to ``limit`` rows (all without one). +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from sqlalchemy import select +from sqlmodel import col + +from policyengine_api.data.v2.models import ( + Household, + UserHouseholdAssociation, + UserPolicy, + UserReportAssociation, + UserSimulationAssociation, +) + +if TYPE_CHECKING: + from collections.abc import Sequence + from uuid import UUID + + from sqlalchemy.sql import Select + from sqlmodel import Session + + +def _pending( + statement: Select[Any], + model: type[Any], + *, + country_ids: Sequence[str], + user_ids: Sequence[UUID] | None, + limit: int | None, +) -> Select[Any]: + statement = statement.where(col(model.country_id).in_(list(country_ids))) + if user_ids is not None: + statement = statement.where(col(model.user_id).in_(list(user_ids))) + return statement.order_by(col(model.created_at), col(model.id)).limit(limit) + + +def read_saved_reforms_holding_only_v1_policies( + session: Session, + *, + country_ids: Sequence[str], + user_ids: Sequence[UUID] | None, + limit: int | None, +) -> list[UserPolicy]: + """Return saved reforms with a v1 policy and no detailed-save policy.""" + statement = select(UserPolicy).where( + col(UserPolicy.policy_id).is_(None), + col(UserPolicy.legacy_policy_id).is_not(None), + ) + return list( + session.scalars( + _pending( + statement, + UserPolicy, + country_ids=country_ids, + user_ids=user_ids, + limit=limit, + ) + ) + ) + + +def read_saved_reports_holding_only_v1_reports( + session: Session, + *, + country_ids: Sequence[str], + user_ids: Sequence[UUID] | None, + limit: int | None, +) -> list[UserReportAssociation]: + """Return saved reports with a v1 report output and no detailed-save report.""" + statement = select(UserReportAssociation).where( + col(UserReportAssociation.report_id).is_(None), + col(UserReportAssociation.legacy_report_id).is_not(None), + ) + return list( + session.scalars( + _pending( + statement, + UserReportAssociation, + country_ids=country_ids, + user_ids=user_ids, + limit=limit, + ) + ) + ) + + +def read_saved_households_holding_only_v1_households( + session: Session, + *, + country_ids: Sequence[str], + user_ids: Sequence[UUID] | None, + limit: int | None, +) -> list[UserHouseholdAssociation]: + """Return saved households with a v1 household and no detailed-save household.""" + statement = select(UserHouseholdAssociation).where( + col(UserHouseholdAssociation.household_id).is_(None), + col(UserHouseholdAssociation.legacy_household_id).is_not(None), + ) + return list( + session.scalars( + _pending( + statement, + UserHouseholdAssociation, + country_ids=country_ids, + user_ids=user_ids, + limit=limit, + ) + ) + ) + + +def read_saved_simulations_holding_only_v1_simulations( + session: Session, + *, + country_ids: Sequence[str], + user_ids: Sequence[UUID] | None, + limit: int | None, +) -> list[UserSimulationAssociation]: + """Return saved simulations with a v1 simulation and no detailed-save one.""" + statement = select(UserSimulationAssociation).where( + col(UserSimulationAssociation.simulation_id).is_(None), + col(UserSimulationAssociation.legacy_simulation_id).is_not(None), + ) + return list( + session.scalars( + _pending( + statement, + UserSimulationAssociation, + country_ids=country_ids, + user_ids=user_ids, + limit=limit, + ) + ) + ) + + +def read_household_default_year(session: Session, household_id: UUID) -> int | None: + """Return the year a stored household calculates, or None without one.""" + return session.scalar( + select(col(Household.default_year)).where(col(Household.id) == household_id) + ) diff --git a/policyengine_api/services/v2/saved_record_migration/database_connectors/reads_v1_records.py b/policyengine_api/services/v2/saved_record_migration/database_connectors/reads_v1_records.py new file mode 100644 index 000000000..20a51b8a3 --- /dev/null +++ b/policyengine_api/services/v2/saved_record_migration/database_connectors/reads_v1_records.py @@ -0,0 +1,128 @@ +"""Reads of the v1 records saved records name, through the v1 mapped models. + +The migration only reads v1's database. Each read returns detached values, +so nothing it returns needs its session afterwards. +""" + +from __future__ import annotations + +import copy +from typing import TYPE_CHECKING + +from sqlalchemy import select + +from policyengine_api.data.v1_models import Household, Policy, ReportOutput, Simulation +from policyengine_api.services.v2.households.types import LegacyHouseholdSnapshot +from policyengine_api.services.v2.policies.types import LegacyPolicySnapshot +from policyengine_api.services.v2.saved_record_migration.types import ( + V1ReportRecord, + V1SimulationRecord, +) + +if TYPE_CHECKING: + from collections.abc import Collection + + from sqlalchemy.orm import Session + + +def read_v1_policy_snapshot( + session: Session, *, country_id: str, policy_id: int +) -> LegacyPolicySnapshot | None: + """Return a detached copy of the v1 policy, or None when it doesn't exist. + + Raise pydantic's ValidationError when the stored row can't be a + snapshot, such as a policy JSON that isn't an object. + """ + policy = session.scalars( + select(Policy).where(Policy.id == policy_id, Policy.country_id == country_id) + ).first() + if policy is None: + return None + return LegacyPolicySnapshot.model_validate( + { + "country_id": policy.country_id, + "legacy_policy_id": policy.id, + "label": policy.label, + "api_version": policy.api_version, + "policy_json": copy.deepcopy(policy.policy_json), + "source_policy_hash": policy.policy_hash, + } + ) + + +def read_v1_household_snapshot( + session: Session, *, country_id: str, household_id: int +) -> LegacyHouseholdSnapshot | None: + """Return a detached copy of the v1 household, or None when it doesn't exist. + + Raise pydantic's ValidationError when the stored row can't be a snapshot. + """ + household = session.scalars( + select(Household).where( + Household.id == household_id, Household.country_id == country_id + ) + ).first() + if household is None: + return None + return LegacyHouseholdSnapshot.model_validate( + { + "country_id": household.country_id, + "legacy_household_id": household.id, + "label": household.label, + "api_version": household.api_version, + "household_json": copy.deepcopy(household.household_json), + "source_household_hash": household.household_hash, + } + ) + + +def read_v1_report( + session: Session, *, country_id: str, report_id: int +) -> V1ReportRecord | None: + """Return the v1 report output's defining fields, or None when it doesn't exist.""" + row = session.execute( + select( + ReportOutput.country_id, + ReportOutput.id, + ReportOutput.year, + ReportOutput.simulation_1_id, + ReportOutput.simulation_2_id, + ).where(ReportOutput.id == report_id, ReportOutput.country_id == country_id) + ).first() + if row is None: + return None + return V1ReportRecord( + country_id=row.country_id, + report_id=row.id, + year=row.year, + simulation_1_id=row.simulation_1_id, + simulation_2_id=row.simulation_2_id, + ) + + +def read_v1_simulations( + session: Session, *, country_id: str, simulation_ids: Collection[int] +) -> dict[int, V1SimulationRecord]: + """Return the country's v1 simulations among ``simulation_ids``, by ID.""" + rows = session.execute( + select( + Simulation.id, + Simulation.country_id, + Simulation.population_type, + Simulation.population_id, + Simulation.policy_id, + ).where( + Simulation.id.in_(sorted(simulation_ids)), + Simulation.country_id == country_id, + ) + ).all() + return { + row.id: V1SimulationRecord( + simulation_id=row.id, + country_id=row.country_id, + population_type=row.population_type, + population_id=row.population_id, + policy_id=row.policy_id, + ) + for row in rows + } diff --git a/policyengine_api/services/v2/saved_record_migration/database_connectors/updates.py b/policyengine_api/services/v2/saved_record_migration/database_connectors/updates.py new file mode 100644 index 000000000..cdca75834 --- /dev/null +++ b/policyengine_api/services/v2/saved_record_migration/database_connectors/updates.py @@ -0,0 +1,79 @@ +"""Updates that give saved records their detailed-save reference. + +Each sets the reference only on a row that still holds its v1 reference and +no detailed-save reference, and keeps the v1 reference: a row holding both +is the record that it was migrated. Each returns whether it changed the row; +a row a user deleted or repointed meanwhile is left as it is. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from sqlalchemy import update +from sqlmodel import col + +from policyengine_api.data.v2.models import ( + UserHouseholdAssociation, + UserPolicy, + UserReportAssociation, +) + +if TYPE_CHECKING: + from uuid import UUID + + from sqlmodel import Session + + +def set_saved_reform_policy( + session: Session, *, row_id: UUID, legacy_policy_id: int, policy_id: UUID +) -> bool: + """Point a saved reform holding only ``legacy_policy_id`` at ``policy_id``.""" + changed = session.execute( + update(UserPolicy) + .where( + col(UserPolicy.id) == row_id, + col(UserPolicy.policy_id).is_(None), + col(UserPolicy.legacy_policy_id) == legacy_policy_id, + ) + .values(policy_id=policy_id) + .returning(col(UserPolicy.id)) + .execution_options(synchronize_session=False) + ).scalar_one_or_none() + return changed is not None + + +def set_saved_report_report( + session: Session, *, row_id: UUID, legacy_report_id: int, report_id: UUID +) -> bool: + """Point a saved report holding only ``legacy_report_id`` at ``report_id``.""" + changed = session.execute( + update(UserReportAssociation) + .where( + col(UserReportAssociation.id) == row_id, + col(UserReportAssociation.report_id).is_(None), + col(UserReportAssociation.legacy_report_id) == legacy_report_id, + ) + .values(report_id=report_id) + .returning(col(UserReportAssociation.id)) + .execution_options(synchronize_session=False) + ).scalar_one_or_none() + return changed is not None + + +def set_saved_household_household( + session: Session, *, row_id: UUID, legacy_household_id: int, household_id: UUID +) -> bool: + """Point a saved household holding only its v1 household at ``household_id``.""" + changed = session.execute( + update(UserHouseholdAssociation) + .where( + col(UserHouseholdAssociation.id) == row_id, + col(UserHouseholdAssociation.household_id).is_(None), + col(UserHouseholdAssociation.legacy_household_id) == legacy_household_id, + ) + .values(household_id=household_id) + .returning(col(UserHouseholdAssociation.id)) + .execution_options(synchronize_session=False) + ).scalar_one_or_none() + return changed is not None diff --git a/policyengine_api/services/v2/saved_record_migration/database_session.py b/policyengine_api/services/v2/saved_record_migration/database_session.py new file mode 100644 index 000000000..a058ddfb9 --- /dev/null +++ b/policyengine_api/services/v2/saved_record_migration/database_session.py @@ -0,0 +1,60 @@ +"""Database session lifetimes of the one-time saved-record migration. + +The detailed-save database is written in one short transaction per saved +record, and read in transactions that commit nothing. v1's database is only +read, in transactions that are always rolled back. +""" + +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 Session as OrmSession + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + +class SavedRecordMigrationDatabaseSession: + """Open the detailed-save database's reads and transactions for the migration.""" + + def __init__(self, session_factory: sessionmaker[Session]) -> None: + """Use ``session_factory``, the runtime role's, to open every session.""" + self._session_factory = session_factory + + @contextmanager + def read(self) -> Iterator[Session]: + """Yield a session whose transaction is rolled back on exit.""" + with self._session_factory() as session: + transaction = session.begin() + try: + yield session + finally: + transaction.rollback() + + @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 + + +class V1RecordDatabaseSession: + """Open v1 transactions that are always rolled back and closed.""" + + def __init__(self, session_factory: sessionmaker[OrmSession]) -> None: + """Use ``session_factory``, the v1 database's, to open every session.""" + self._session_factory = session_factory + + @contextmanager + def read(self) -> Iterator[OrmSession]: + """Yield a v1 session whose transaction is rolled back on exit.""" + with self._session_factory() as session: + transaction = session.begin() + try: + yield session + finally: + transaction.rollback() diff --git a/policyengine_api/services/v2/saved_record_migration/services.py b/policyengine_api/services/v2/saved_record_migration/services.py new file mode 100644 index 000000000..9b6cc787a --- /dev/null +++ b/policyengine_api/services/v2/saved_record_migration/services.py @@ -0,0 +1,618 @@ +"""The one-time migration of saved records' v1 references (D4 · 1). + +A run reads the saved reforms, saved households, saved reports and saved +simulations that hold a v1 reference and no detailed-save reference, oldest +first, and gives each of the first three its detailed-save record: + +- a saved reform its v1 policy's copy, found or made by the v1-to-v2 copy + (``mirror_legacy_policy_in_session``), which splits the policy's model + assumptions into a dynamic; a v1 policy with assumptions also gives the + owner a saved dynamic with the saved reform's name and description; +- a saved household its v1 household's copy + (``mirror_legacy_household_in_session``); +- a saved report the report the simulation service finds or creates by key + for the v1 report's definition, each side's v1 policy copied and split as + above. A side left with no policy values names no policy (C1 · 35, 9a), so + identical v1 reports end on one report. + +Saved simulations are only listed. A row whose policies set a parameter the +running catalog lacks is left on its v1 reference and listed (A1 · 6), +unless the run drops missing parameters (the second mode, for E1 · 4): then +it migrates from the parameters that still exist, stored without a v1 ID +mapping, and a row whose every parameter is missing is still left. A row +keeps its v1 reference too; a row holding both is the record that it was +migrated. A dry run reads both databases, writes nothing and calls no other +service. + +Each saved record is written in its own transaction, and a saved report's +copies commit before the simulation service is asked for the report, since +it reads them itself. A row the run can't migrate fails alone, with a +reason, and keeps its v1 reference. Running again picks up what is left. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from pydantic import ValidationError + +from policyengine_api.constants import POLICYENGINE_VERSION +from policyengine_api.data.v2.catalog.region_references import ( + load_region_references, +) +from policyengine_api.services.v2.saved_record_migration.database_connectors.reads import ( # noqa: E501 # a dotted module path cannot be wrapped + read_saved_households_holding_only_v1_households, + read_saved_reforms_holding_only_v1_policies, + read_saved_reports_holding_only_v1_reports, + read_saved_simulations_holding_only_v1_simulations, +) +from policyengine_api.services.v2.saved_record_migration.database_connectors.reads_v1_records import ( # noqa: E501 # a dotted module path cannot be wrapped + read_v1_household_snapshot, + read_v1_policy_snapshot, + read_v1_report, + read_v1_simulations, +) +from policyengine_api.services.v2.saved_record_migration.database_connectors.updates import ( # noqa: E501 # a dotted module path cannot be wrapped + set_saved_household_household, + set_saved_reform_policy, + set_saved_report_report, +) +from policyengine_api.services.v2.saved_record_migration.transformations import ( + closing_check, + detailed_save_report_definition, + pending_saved_household, + pending_saved_reform, + pending_saved_report, + pending_saved_simulation, +) +from policyengine_api.services.v2.saved_record_migration.types import ( + FailureReason, + MigrationRun, + RowOutcome, + SavedRecordKind, + SavedRecordResult, + V1ReportKind, +) +from policyengine_api.services.v2.saved_record_migration.validators import ( + ReportSubmissionRefusedError, + ReportSubmissionUnavailableError, + SavedRecordMigrationRefusal, + require_catalog_region_code, + validate_v1_report, +) +from policyengine_api.services.v2.user_dynamics.types import ( + UserDynamicCreationInput, +) + +if TYPE_CHECKING: + from collections.abc import Callable + from contextlib import AbstractContextManager + from uuid import UUID + + from sqlmodel import Session + + from policyengine_api.data.v2.catalog.region_references import RegionReference + from policyengine_api.services.v2.households.types import ( + LegacyHouseholdSnapshot, + ) + from policyengine_api.services.v2.policies.types import LegacyPolicySnapshot + from policyengine_api.services.v2.saved_record_migration.database_session import ( + SavedRecordMigrationDatabaseSession, + V1RecordDatabaseSession, + ) + from policyengine_api.services.v2.saved_record_migration.types import ( + DetailedSaveReportDefinition, + MigrationOptions, + PendingSavedRecord, + PolicyMigrationPlan, + ReportSubmitter, + V1ReportDefinition, + ) + +# A saved report's window of one year is the report itself. +_SHORTEST_BUDGET_WINDOW = 2 + + +def _refusal(reason: FailureReason, message: str) -> SavedRecordMigrationRefusal: + return SavedRecordMigrationRefusal(reason, message) + + +def _result( # noqa: PLR0913 # the record and outcome, then each optional field + record: PendingSavedRecord, + outcome: RowOutcome, + *, + detailed_save_id: UUID | None = None, + saved_dynamic_id: UUID | None = None, + missing_parameters: tuple[str, ...] = (), + dropped_parameters: tuple[str, ...] = (), + failure_reason: FailureReason | None = None, + failure_detail: str | None = None, + notes: tuple[str, ...] = (), +) -> SavedRecordResult: + return SavedRecordResult( + kind=record.kind, + row_id=record.row_id, + country_id=record.country_id, + legacy_id=record.legacy_id, + outcome=outcome, + detailed_save_id=detailed_save_id, + saved_dynamic_id=saved_dynamic_id, + missing_parameters=missing_parameters, + dropped_parameters=dropped_parameters, + failure_reason=failure_reason, + failure_detail=failure_detail, + notes=notes, + ) + + +def _left_for_missing_parameters( + record: PendingSavedRecord, + plan: PolicyMigrationPlan, + *, + missing_parameters: tuple[str, ...], + drop_missing_parameters: bool, +) -> SavedRecordResult | None: + """Return the result of a row its missing parameters leave, or None. + + ``plan`` is the plan of the row's own policy: a saved reform's, or a + saved report's reform (its baseline without one), and + ``missing_parameters`` every policy's of the row. + """ + if missing_parameters and not drop_missing_parameters: + return _result( + record, + RowOutcome.MISSING_PARAMETERS, + missing_parameters=missing_parameters, + ) + if plan.every_parameter_missing: + return _result( + record, + RowOutcome.EVERY_PARAMETER_MISSING, + missing_parameters=plan.missing_parameters, + ) + return None + + +class V2SavedRecordMigrationService: + """Migrate saved records' v1 references, one saved record at a time.""" + + def __init__( + self, + database: SavedRecordMigrationDatabaseSession, + v1_database: V1RecordDatabaseSession, + *, + report_submitter: ReportSubmitter | None = None, + running_policyengine_version: str = POLICYENGINE_VERSION, + region_references: Callable[[str], tuple[RegionReference, ...]] = ( + load_region_references + ), + ) -> None: + """Read and write through ``database`` and read v1 through ``v1_database``. + + ``report_submitter`` asks the simulation service for reports; a dry + run doesn't need one. Copies bind to the catalog of + ``running_policyengine_version``, the running .py version's. + """ + self._database = database + self._v1_database = v1_database + self._report_submitter = report_submitter + self._running_policyengine_version = running_policyengine_version + self._region_references = region_references + self._references_by_country: dict[str, tuple[RegionReference, ...]] = {} + + def migrate(self, options: MigrationOptions) -> MigrationRun: + """Migrate the rows ``options`` selects, then check what is left.""" + reports_this_run: dict[tuple[str, int, int | None], SavedRecordResult] = {} + results = tuple( + self._migrate_record(record, options, reports_this_run) + for record in self._pending(options, limit=options.limit) + ) + remaining: dict[SavedRecordKind, set[UUID]] = { + kind: set() for kind in SavedRecordKind + } + for record in self._pending(options, limit=None): + remaining[record.kind].add(record.row_id) + return MigrationRun( + options=options, + policyengine_version=self._running_policyengine_version, + results=results, + closing_check=closing_check(remaining, results), + ) + + def _pending( + self, options: MigrationOptions, *, limit: int | None + ) -> list[PendingSavedRecord]: + """Return the rows holding only a v1 reference. + + Saved reforms come first, then households and reports, which reuse + the copies they made, then simulations. + """ + countries = options.country_ids + users = options.user_ids + with self._database.read() as session: + return [ + *( + pending_saved_reform(row) + for row in read_saved_reforms_holding_only_v1_policies( + session, country_ids=countries, user_ids=users, limit=limit + ) + ), + *( + pending_saved_household(row) + for row in read_saved_households_holding_only_v1_households( + session, country_ids=countries, user_ids=users, limit=limit + ) + ), + *( + pending_saved_report(row) + for row in read_saved_reports_holding_only_v1_reports( + session, country_ids=countries, user_ids=users, limit=limit + ) + ), + *( + pending_saved_simulation(row) + for row in read_saved_simulations_holding_only_v1_simulations( + session, country_ids=countries, user_ids=users, limit=limit + ) + ), + ] + + def _migrate_record( + self, + record: PendingSavedRecord, + options: MigrationOptions, + reports_this_run: dict[tuple[str, int, int | None], SavedRecordResult], + ) -> SavedRecordResult: + try: + if record.kind is SavedRecordKind.SAVED_REFORM: + return self._migrate_saved_reform(record, options) + if record.kind is SavedRecordKind.SAVED_HOUSEHOLD: + return self._migrate_saved_household(record, options) + if record.kind is SavedRecordKind.SAVED_REPORT: + return self._migrate_saved_report(record, options, reports_this_run) + return _result(record, RowOutcome.NOT_MIGRATED) + except SavedRecordMigrationRefusal as refusal: + return _result( + record, + RowOutcome.FAILED, + failure_reason=refusal.reason, + failure_detail=str(refusal), + ) + + def _session(self, options: MigrationOptions) -> AbstractContextManager[Session]: + """Open a transaction that commits for a run, or a read for a dry run.""" + return self._database.transaction() if options.apply else self._database.read() + + # Saved reforms. + + def _migrate_saved_reform( + self, record: PendingSavedRecord, options: MigrationOptions + ) -> SavedRecordResult: + from policyengine_api.services.v2.saved_record_migration.copies.services import ( # noqa: E501 # a dotted module path cannot be wrapped + plan_policy_in_session, + store_policy_in_session, + ) + from policyengine_api.services.v2.user_dynamics.services import ( + create_user_dynamic_in_session, + ) + + snapshot = self._v1_policy(record.country_id, record.legacy_id) + with self._session(options) as session: + plan = plan_policy_in_session( + session, + snapshot, + drop_missing_parameters=options.drop_missing_parameters, + running_policyengine_version=self._running_policyengine_version, + ) + left = _left_for_missing_parameters( + record, + plan, + missing_parameters=plan.missing_parameters, + drop_missing_parameters=options.drop_missing_parameters, + ) + if left is not None: + return left + if not options.apply: + return _result( + record, + RowOutcome.MIGRATED, + detailed_save_id=plan.existing_policy_id, + dropped_parameters=plan.missing_parameters, + ) + stored = store_policy_in_session( + session, + plan, + running_policyengine_version=self._running_policyengine_version, + ) + if not set_saved_reform_policy( + session, + row_id=record.row_id, + legacy_policy_id=record.legacy_id, + policy_id=stored.policy_id, + ): + msg = "the saved reform no longer holds only its v1 policy" + raise _refusal(FailureReason.ROW_CHANGED, msg) + saved_dynamic_id = ( + None + if stored.dynamic_id is None + else create_user_dynamic_in_session( + session, + UserDynamicCreationInput.model_validate( + { + "country_id": record.country_id, + "user_id": record.user_id, + "dynamic_id": stored.dynamic_id, + "name": record.name, + "description": record.description, + } + ), + ).id + ) + return _result( + record, + RowOutcome.MIGRATED, + detailed_save_id=stored.policy_id, + saved_dynamic_id=saved_dynamic_id, + dropped_parameters=plan.missing_parameters, + ) + + # Policies. + + def _v1_policy(self, country_id: str, policy_id: int) -> LegacyPolicySnapshot: + with self._v1_database.read() as session: + try: + snapshot = read_v1_policy_snapshot( + session, country_id=country_id, policy_id=policy_id + ) + except ValidationError as error: + msg = f"v1 policy {policy_id} can't be read: {error}" + raise _refusal(FailureReason.POLICY_NOT_COPYABLE, msg) from error + if snapshot is None: + msg = f"v1 policy {policy_id} doesn't exist" + raise _refusal(FailureReason.V1_RECORD_NOT_FOUND, msg) + return snapshot + + # Saved households. + + def _v1_household( + self, country_id: str, household_id: int + ) -> LegacyHouseholdSnapshot: + with self._v1_database.read() as session: + try: + snapshot = read_v1_household_snapshot( + session, country_id=country_id, household_id=household_id + ) + except ValidationError as error: + msg = f"v1 household {household_id} can't be read: {error}" + raise _refusal(FailureReason.HOUSEHOLD_NOT_COPYABLE, msg) from error + if snapshot is None: + msg = f"v1 household {household_id} doesn't exist" + raise _refusal(FailureReason.V1_RECORD_NOT_FOUND, msg) + return snapshot + + def _migrate_saved_household( + self, record: PendingSavedRecord, options: MigrationOptions + ) -> SavedRecordResult: + from policyengine_api.services.v2.saved_record_migration.copies.services import ( # noqa: E501 # a dotted module path cannot be wrapped + household_copy_in_session, + ) + + snapshot = self._v1_household(record.country_id, record.legacy_id) + with self._session(options) as session: + household_id, _ = household_copy_in_session( + session, snapshot, apply=options.apply + ) + if options.apply and ( + household_id is None + or not set_saved_household_household( + session, + row_id=record.row_id, + legacy_household_id=record.legacy_id, + household_id=household_id, + ) + ): + msg = "the saved household no longer holds only its v1 household" + raise _refusal(FailureReason.ROW_CHANGED, msg) + return _result(record, RowOutcome.MIGRATED, detailed_save_id=household_id) + + # Saved reports. + + def _v1_report( + self, record: PendingSavedRecord + ) -> tuple[ + V1ReportDefinition, + dict[int, LegacyPolicySnapshot], + LegacyHouseholdSnapshot | None, + ]: + """Read the v1 report's definition, its policies and its household.""" + with self._v1_database.read() as session: + report = read_v1_report( + session, country_id=record.country_id, report_id=record.legacy_id + ) + if report is None: + msg = f"v1 report {record.legacy_id} doesn't exist" + raise _refusal(FailureReason.V1_RECORD_NOT_FOUND, msg) + simulation_ids = {report.simulation_1_id} + if report.simulation_2_id is not None: + simulation_ids.add(report.simulation_2_id) + simulations = read_v1_simulations( + session, country_id=record.country_id, simulation_ids=simulation_ids + ) + baseline = simulations.get(report.simulation_1_id) + if baseline is None: + msg = f"v1 report {record.legacy_id}'s first simulation doesn't exist" + raise _refusal(FailureReason.V1_REPORT_UNREADABLE, msg) + reform = ( + None + if report.simulation_2_id is None + else simulations.get(report.simulation_2_id) + ) + definition = validate_v1_report(report, baseline, reform) + policy_ids = {definition.baseline_policy_id} + if definition.reform_policy_id is not None: + policy_ids.add(definition.reform_policy_id) + snapshots = { + policy_id: self._v1_policy(record.country_id, policy_id) + for policy_id in sorted(policy_ids) + } + household = ( + None + if definition.legacy_household_id is None + else self._v1_household(record.country_id, definition.legacy_household_id) + ) + return definition, snapshots, household + + def _report_id(self, definition: DetailedSaveReportDefinition) -> UUID: + """Ask the simulation service to find or create the report.""" + if self._report_submitter is None: + msg = "migrating saved reports needs the simulation service" + raise RuntimeError(msg) + try: + return self._report_submitter.find_or_create_report(definition) + except ReportSubmissionRefusedError as error: + msg = f"{error.code}: {error}" + raise _refusal(FailureReason.REPORT_REFUSED, msg) from error + except ReportSubmissionUnavailableError as error: + msg = f"the simulation service can't answer: {error}" + raise _refusal(FailureReason.SIMULATION_SERVICE_UNAVAILABLE, msg) from error + + def _country_regions(self, country_id: str) -> tuple[RegionReference, ...]: + if country_id not in self._references_by_country: + self._references_by_country[country_id] = self._region_references( + country_id + ) + return self._references_by_country[country_id] + + def _point_saved_report(self, record: PendingSavedRecord, report_id: UUID) -> None: + with self._database.transaction() as session: + if not set_saved_report_report( + session, + row_id=record.row_id, + legacy_report_id=record.legacy_id, + report_id=report_id, + ): + msg = "the saved report no longer holds only its v1 report" + raise _refusal(FailureReason.ROW_CHANGED, msg) + + def _migrate_saved_report( + self, + record: PendingSavedRecord, + options: MigrationOptions, + reports_this_run: dict[tuple[str, int, int | None], SavedRecordResult], + ) -> SavedRecordResult: + from policyengine_api.services.v2.saved_record_migration.copies.services import ( # noqa: E501 # a dotted module path cannot be wrapped + household_copy_in_session, + plan_policy_in_session, + report_side_in_session, + ) + + window = record.budget_window_years + report_key = ( + record.country_id, + record.legacy_id, + window + if window is not None and window >= _SHORTEST_BUDGET_WINDOW + else None, + ) + earlier = reports_this_run.get(report_key) + if earlier is not None: + # Another saved report of the same v1 report, migrated by this run. + if options.apply and earlier.detailed_save_id is not None: + self._point_saved_report(record, earlier.detailed_save_id) + return _result( + record, + RowOutcome.MIGRATED, + detailed_save_id=earlier.detailed_save_id, + dropped_parameters=earlier.dropped_parameters, + notes=earlier.notes, + ) + definition, snapshots, household = self._v1_report(record) + region_code = ( + require_catalog_region_code( + record.country_id, + definition.region or "", + self._country_regions(record.country_id), + ) + if definition.kind is V1ReportKind.ECONOMY + else None + ) + with self._session(options) as session: + plans = { + policy_id: plan_policy_in_session( + session, + snapshot, + drop_missing_parameters=options.drop_missing_parameters, + running_policyengine_version=self._running_policyengine_version, + ) + for policy_id, snapshot in snapshots.items() + } + missing = tuple( + sorted( + { + name + for plan in plans.values() + for name in plan.missing_parameters + } + ) + ) + own_policy_id = ( + definition.baseline_policy_id + if definition.reform_policy_id is None + else definition.reform_policy_id + ) + left = _left_for_missing_parameters( + record, + plans[own_policy_id], + missing_parameters=missing, + drop_missing_parameters=options.drop_missing_parameters, + ) + if left is not None: + return left + sides = { + policy_id: report_side_in_session( + session, + plan, + apply=options.apply, + running_policyengine_version=self._running_policyengine_version, + ) + for policy_id, plan in plans.items() + } + household_id, household_year = ( + (None, None) + if household is None + else household_copy_in_session(session, household, apply=options.apply) + ) + notes = ( + ( + f"the report calculates its household's year, {household_year}, " + f"not the v1 report's {definition.year}", + ) + if household is not None and household_year != definition.year + else () + ) + report_id = None + if options.apply: + report_id = self._report_id( + detailed_save_report_definition( + definition, + baseline=sides[definition.baseline_policy_id], + reform=( + None + if definition.reform_policy_id is None + else sides[definition.reform_policy_id] + ), + region_code=region_code, + household_id=household_id, + budget_window_years=window, + ) + ) + self._point_saved_report(record, report_id) + result = _result( + record, + RowOutcome.MIGRATED, + detailed_save_id=report_id, + dropped_parameters=missing, + notes=notes, + ) + reports_this_run[report_key] = result + return result diff --git a/policyengine_api/services/v2/saved_record_migration/transformations.py b/policyengine_api/services/v2/saved_record_migration/transformations.py new file mode 100644 index 000000000..3cff901c7 --- /dev/null +++ b/policyengine_api/services/v2/saved_record_migration/transformations.py @@ -0,0 +1,284 @@ +"""Conversions the one-time saved-record migration makes (D4 · 1). + +They read saved records' rows into pending records, keep a v1 policy's +parameters that the running catalog still has, build the detailed-save +report definition, and work out the closing check and the command's JSON +document. +""" + +from __future__ import annotations + +from collections import Counter +from typing import TYPE_CHECKING + +from policyengine_api.services.v2.saved_record_migration.types import ( + ClosingCheck, + DetailedSaveReportDefinition, + DetailedSaveReportKind, + PendingSavedRecord, + RemainingV1References, + RowOutcome, + SavedRecordKind, + V1ReportKind, +) + +if TYPE_CHECKING: + from collections.abc import Collection, Mapping, Sequence + from uuid import UUID + + from policyengine_api.data.v2.models import ( + UserHouseholdAssociation, + UserPolicy, + UserReportAssociation, + UserSimulationAssociation, + ) + from policyengine_api.dynamic_parameters import LegacyPolicySplit + from policyengine_api.services.v2.policies.types import LegacyPolicySnapshot + from policyengine_api.services.v2.saved_record_migration.types import ( + MigrationRun, + PolicySide, + SavedRecordResult, + V1ReportDefinition, + ) + +# A saved report's window of one year is the report itself. +_SHORTEST_BUDGET_WINDOW = 2 +# Outcomes that leave a row on its v1 reference, by the count they go to. +_LEFT_OUTCOMES = { + RowOutcome.MISSING_PARAMETERS: "missing_parameters", + RowOutcome.EVERY_PARAMETER_MISSING: "every_parameter_missing", + RowOutcome.FAILED: "failed", + RowOutcome.NOT_MIGRATED: "not_migrated", +} + + +def pending_saved_reform(row: UserPolicy) -> PendingSavedRecord: + """Read a saved reform holding only its v1 policy.""" + if row.legacy_policy_id is None: + msg = "a pending saved reform holds a v1 policy" + raise ValueError(msg) + return PendingSavedRecord( + kind=SavedRecordKind.SAVED_REFORM, + row_id=row.id, + user_id=row.user_id, + country_id=row.country_id, + legacy_id=row.legacy_policy_id, + name=row.name, + description=row.description, + ) + + +def pending_saved_report(row: UserReportAssociation) -> PendingSavedRecord: + """Read a saved report holding only its v1 report output.""" + if row.legacy_report_id is None: + msg = "a pending saved report holds a v1 report" + raise ValueError(msg) + return PendingSavedRecord( + kind=SavedRecordKind.SAVED_REPORT, + row_id=row.id, + user_id=row.user_id, + country_id=row.country_id, + legacy_id=row.legacy_report_id, + name=row.name, + description=row.description, + budget_window_years=row.budget_window_years, + ) + + +def pending_saved_household(row: UserHouseholdAssociation) -> PendingSavedRecord: + """Read a saved household holding only its v1 household.""" + if row.legacy_household_id is None: + msg = "a pending saved household holds a v1 household" + raise ValueError(msg) + return PendingSavedRecord( + kind=SavedRecordKind.SAVED_HOUSEHOLD, + row_id=row.id, + user_id=row.user_id, + country_id=row.country_id, + legacy_id=row.legacy_household_id, + name=row.name, + description=row.description, + ) + + +def pending_saved_simulation(row: UserSimulationAssociation) -> PendingSavedRecord: + """Read a saved simulation holding only its v1 simulation.""" + if row.legacy_simulation_id is None: + msg = "a pending saved simulation holds a v1 simulation" + raise ValueError(msg) + return PendingSavedRecord( + kind=SavedRecordKind.SAVED_SIMULATION, + row_id=row.id, + user_id=row.user_id, + country_id=row.country_id, + legacy_id=row.legacy_simulation_id, + name=row.name, + description=row.description, + ) + + +def kept_policy_snapshot( + snapshot: LegacyPolicySnapshot, + split: LegacyPolicySplit, + *, + missing: Collection[str], +) -> LegacyPolicySnapshot: + """Return the v1 policy without the parameters the running catalog lacks. + + ``split`` is the snapshot's split, whose names are the parameters' + current ones (the UK's old labour-supply spelling rewritten), and + ``missing`` the names among them that the catalog lacks. The other fields + are the snapshot's. + """ + kept = { + name: values + for name, values in {**split.policy_values, **split.dynamic_values}.items() + if name not in missing + } + return snapshot.model_copy(update={"policy_json": kept}) + + +def detailed_save_report_definition( # noqa: PLR0913 # the v1 definition, then each part the copies give + definition: V1ReportDefinition, + *, + baseline: PolicySide, + reform: PolicySide | None, + region_code: str | None, + household_id: UUID | None, + budget_window_years: int | None, +) -> DetailedSaveReportDefinition: + """Return the report the simulation service is asked to find or create. + + A household report names its household and calculates the household's + own year. An economy report names its year and region, and is a budget + window when the saved report kept a window of two or more years. + """ + if definition.kind is V1ReportKind.HOUSEHOLD: + return DetailedSaveReportDefinition( + country_id=definition.country_id, + kind=DetailedSaveReportKind.HOUSEHOLD, + baseline=baseline, + reform=reform, + year=None, + region_code=None, + budget_window_size=None, + household_id=household_id, + ) + is_window = ( + budget_window_years is not None + and budget_window_years >= _SHORTEST_BUDGET_WINDOW + ) + return DetailedSaveReportDefinition( + country_id=definition.country_id, + kind=( + DetailedSaveReportKind.BUDGET_WINDOW + if is_window + else DetailedSaveReportKind.ECONOMY + ), + baseline=baseline, + reform=reform, + year=definition.year, + region_code=region_code, + budget_window_size=budget_window_years if is_window else None, + household_id=None, + ) + + +def closing_check( + remaining: Mapping[SavedRecordKind, Collection[UUID]], + results: Sequence[SavedRecordResult], +) -> ClosingCheck: + """Count the rows still holding only a v1 reference by what the run did. + + ``remaining`` holds, for each kind, the rows holding only a v1 reference + when the run ended. A row the run migrated, or in a dry run would + migrate, isn't counted. Any other row is counted by its outcome, and one + the run has no result for as not attempted. The check passes when + nothing failed and nothing was left unattempted. + """ + outcomes = {(result.kind, result.row_id): result.outcome for result in results} + counted: list[RemainingV1References] = [] + for kind in SavedRecordKind: + counts: Counter[str] = Counter() + for row_id in remaining.get(kind, ()): + outcome = outcomes.get((kind, row_id)) + if outcome is RowOutcome.MIGRATED: + continue + counts["not_attempted" if outcome is None else _LEFT_OUTCOMES[outcome]] += 1 + counted.append( + RemainingV1References( + kind=kind, + missing_parameters=counts["missing_parameters"], + every_parameter_missing=counts["every_parameter_missing"], + failed=counts["failed"], + not_attempted=counts["not_attempted"], + not_migrated=counts["not_migrated"], + ) + ) + return ClosingCheck( + remaining=tuple(counted), + passed=all(item.failed == 0 and item.not_attempted == 0 for item in counted), + ) + + +def _optional_text(value: object | None) -> str | None: + return None if value is None else str(value) + + +def _result_document(result: SavedRecordResult) -> dict[str, object]: + return { + "kind": result.kind.value, + "row_id": str(result.row_id), + "country_id": result.country_id, + "legacy_id": result.legacy_id, + "outcome": result.outcome.value, + "detailed_save_id": _optional_text(result.detailed_save_id), + "saved_dynamic_id": _optional_text(result.saved_dynamic_id), + "missing_parameters": list(result.missing_parameters), + "dropped_parameters": list(result.dropped_parameters), + "failure_reason": ( + None if result.failure_reason is None else result.failure_reason.value + ), + "failure_detail": result.failure_detail, + "notes": list(result.notes), + } + + +def migration_document(run: MigrationRun) -> dict[str, object]: + """Return the run as the JSON document the command prints. + + It holds the options, counts of each kind's rows by outcome, every row's + result (a rollback clears the detailed-save reference of the rows it + lists as migrated), and the closing check. + """ + counts: dict[str, dict[str, int]] = {kind.value: {} for kind in SavedRecordKind} + for result in run.results: + by_outcome = counts[result.kind.value] + by_outcome[result.outcome.value] = by_outcome.get(result.outcome.value, 0) + 1 + return { + "mode": "migrate" if run.options.apply else "dry_run", + "drop_missing_parameters": run.options.drop_missing_parameters, + "countries": list(run.options.country_ids), + "limit": run.options.limit, + "user_ids": ( + None + if run.options.user_ids is None + else [str(user_id) for user_id in run.options.user_ids] + ), + "policyengine_version": run.policyengine_version, + "counts": counts, + "rows": [_result_document(result) for result in run.results], + "closing_check": { + "passed": run.closing_check.passed, + "remaining": { + item.kind.value: { + "missing_parameters": item.missing_parameters, + "every_parameter_missing": item.every_parameter_missing, + "failed": item.failed, + "not_attempted": item.not_attempted, + "not_migrated": item.not_migrated, + } + for item in run.closing_check.remaining + }, + }, + } diff --git a/policyengine_api/services/v2/saved_record_migration/types.py b/policyengine_api/services/v2/saved_record_migration/types.py new file mode 100644 index 000000000..febc628a0 --- /dev/null +++ b/policyengine_api/services/v2/saved_record_migration/types.py @@ -0,0 +1,303 @@ +"""Types of the one-time migration of saved records' v1 references (D4 · 1). + +Saved reforms, saved reports and saved households that hold only a v1 +reference are given the detailed-save record that reference stands for; +saved simulations holding only a v1 reference are listed. Each row's outcome +is a ``SavedRecordResult``, and a run's is a ``MigrationRun`` with its closing +check. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import StrEnum +from typing import TYPE_CHECKING, Protocol + +if TYPE_CHECKING: + from uuid import UUID + + from policyengine_api.services.v2.policies.types import ( + LegacyPolicySnapshot, + LegacyPolicyTranslation, + ) + + +class SavedRecordKind(StrEnum): + """A kind of saved record, each a table of rows owned by one user.""" + + SAVED_REFORM = "saved_reform" + SAVED_REPORT = "saved_report" + SAVED_HOUSEHOLD = "saved_household" + SAVED_SIMULATION = "saved_simulation" + + +class RowOutcome(StrEnum): + """What a run did with one saved record, or, in a dry run, would do. + + ``missing_parameters``: left on its v1 reference because a policy it + names sets a parameter the running catalog lacks (A1 · 6), and listed. + ``every_parameter_missing``: in the second mode, left and listed because + dropping those parameters leaves nothing the user set (decision (a)). + ``not_migrated``: a saved simulation, only listed. + """ + + MIGRATED = "migrated" + MISSING_PARAMETERS = "missing_parameters" + EVERY_PARAMETER_MISSING = "every_parameter_missing" + FAILED = "failed" + NOT_MIGRATED = "not_migrated" + + +class FailureReason(StrEnum): + """Why a saved record could not be migrated; it keeps its v1 reference.""" + + V1_RECORD_NOT_FOUND = "v1_record_not_found" + V1_REPORT_UNREADABLE = "v1_report_unreadable" + UNKNOWN_REGION = "unknown_region" + POLICY_NOT_COPYABLE = "policy_not_copyable" + HOUSEHOLD_NOT_COPYABLE = "household_not_copyable" + CATALOG_NOT_PUBLISHED = "catalog_not_published" + REPORT_REFUSED = "report_refused" + SIMULATION_SERVICE_UNAVAILABLE = "simulation_service_unavailable" + ROW_CHANGED = "row_changed" + + +class V1ReportKind(StrEnum): + """Whether a v1 report simulates a region's population or one household.""" + + ECONOMY = "economy" + HOUSEHOLD = "household" + + +class DetailedSaveReportKind(StrEnum): + """The kind of report the simulation service is asked to find or create.""" + + ECONOMY = "economy" + BUDGET_WINDOW = "budget_window" + HOUSEHOLD = "household" + + +@dataclass(frozen=True) +class MigrationOptions: + """What one run of the command migrates, and how. + + ``apply`` False is a dry run, which writes nothing and calls no other + service. ``drop_missing_parameters`` is the second mode, for the last run + (E1 · 4): rows whose policies set parameters the running catalog lacks + migrate from the parameters that still exist. ``limit`` caps the rows of + each kind a run takes, oldest first; ``user_ids`` keeps the run to those + owners' rows. The closing check covers the same countries and owners. + """ + + apply: bool + drop_missing_parameters: bool = False + country_ids: tuple[str, ...] = ("uk", "us") + limit: int | None = None + user_ids: tuple[UUID, ...] | None = None + + +@dataclass(frozen=True) +class PendingSavedRecord: + """A saved record that holds only its v1 reference, as a run reads it.""" + + kind: SavedRecordKind + row_id: UUID + user_id: UUID + country_id: str + legacy_id: int + name: str | None = None + description: str | None = None + budget_window_years: int | None = None + + +@dataclass(frozen=True) +class V1ReportRecord: + """The fields of a v1 report output that define the report.""" + + country_id: str + report_id: int + year: str | None + simulation_1_id: int + simulation_2_id: int | None + + +@dataclass(frozen=True) +class V1SimulationRecord: + """The fields of a v1 simulation that define one side of a report.""" + + simulation_id: int + country_id: str + population_type: str + population_id: str + policy_id: int + + +@dataclass(frozen=True) +class V1ReportDefinition: + """A v1 report as v1's report spec reads it (``ReportSpecService``). + + Simulation 1 is the baseline and simulation 2 the reform. A report of one + economy simulation names that simulation's policy on both sides; a report + of one household simulation has no reform. ``region`` is an economy + report's v1 region, and ``legacy_household_id`` a household report's v1 + household. + """ + + country_id: str + legacy_report_id: int + kind: V1ReportKind + year: int + region: str | None + legacy_household_id: int | None + baseline_policy_id: int + reform_policy_id: int | None + + +@dataclass(frozen=True) +class PolicySide: + """One side of a detailed-save report: its policy and dynamic, or neither. + + Neither means current law and no model assumptions beyond the model's + defaults; a side whose v1 policy sets only model assumptions names its + dynamic and no policy (C1 · 35, 9a). + """ + + policy_id: UUID | None + dynamic_id: UUID | None + + +@dataclass(frozen=True) +class PolicyMigrationPlan: + """How one v1 policy migrates, worked out before anything is written. + + ``missing_parameters`` are the parameters it sets that the running + catalog lacks, by their current names. ``sets_policy_values`` and + ``sets_dynamic_values`` say whether the policy and its model assumptions + keep any value, without the missing parameters in the second mode. + ``kept_translation`` is, in the second mode, the translation of what is + kept, stored without a v1 ID mapping; it is None when the whole v1 policy + is copied. ``existing_policy_id`` and ``existing_dynamic_id`` name the + copy the v1 policy already maps to, if any. + """ + + snapshot: LegacyPolicySnapshot + missing_parameters: tuple[str, ...] + sets_policy_values: bool + sets_dynamic_values: bool + kept_translation: LegacyPolicyTranslation | None = None + existing_policy_id: UUID | None = None + existing_dynamic_id: UUID | None = None + + @property + def every_parameter_missing(self) -> bool: + """Whether the policy set parameters and the catalog lacks all of them.""" + return bool(self.missing_parameters) and not ( + self.sets_policy_values or self.sets_dynamic_values + ) + + +@dataclass(frozen=True) +class StoredPolicy: + """The policy, and the dynamic if any, a v1 policy's values are stored as.""" + + policy_id: UUID + dynamic_id: UUID | None + + +@dataclass(frozen=True) +class DetailedSaveReportDefinition: + """The report the simulation service is asked to find or create by key. + + An economy or budget-window report names its year and catalog region + code, and a budget window its size; a household report names its + household and calculates the household's own year, so it names neither. + No definition names a dataset or a data source: the region's own dataset + is used, as for the v1 report. + """ + + country_id: str + kind: DetailedSaveReportKind + baseline: PolicySide + reform: PolicySide | None + year: int | None + region_code: str | None + budget_window_size: int | None + household_id: UUID | None + + +class ReportSubmitter(Protocol): + """Finds or creates a report through the simulation service.""" + + def find_or_create_report(self, definition: DetailedSaveReportDefinition) -> UUID: + """Return the ID of the report the simulation service found or created. + + Raise ReportSubmissionRefusedError when the service refuses the + definition, and ReportSubmissionUnavailableError when it can't answer. + """ + ... + + +@dataclass(frozen=True) +class SavedRecordResult: + """What a run did with one saved record. + + ``detailed_save_id`` is the policy, report or household ID the row now + holds; in a dry run, the existing copy it would hold, or None when the run + would make a new one. ``missing_parameters`` lists the parameters the + running catalog lacks of a row left for them, and ``dropped_parameters`` + those the second mode left out of a row it migrated. ``notes`` hold facts + about a migrated row a reviewer should see. + """ + + kind: SavedRecordKind + row_id: UUID + country_id: str + legacy_id: int + outcome: RowOutcome + detailed_save_id: UUID | None = None + saved_dynamic_id: UUID | None = None + missing_parameters: tuple[str, ...] = () + dropped_parameters: tuple[str, ...] = () + failure_reason: FailureReason | None = None + failure_detail: str | None = None + notes: tuple[str, ...] = () + + +@dataclass(frozen=True) +class RemainingV1References: + """The rows of one kind that still hold only a v1 reference after a run. + + Each is counted once, by what the run did with it: left for missing + parameters, left because every parameter is missing, failed, not reached + by the run (beyond its limit, or saved after it read the rows), or, for + saved simulations, only listed. + """ + + kind: SavedRecordKind + missing_parameters: int = 0 + every_parameter_missing: int = 0 + failed: int = 0 + not_attempted: int = 0 + not_migrated: int = 0 + + +@dataclass(frozen=True) +class ClosingCheck: + """The rows left holding only a v1 reference, by kind, and the verdict. + + It passes when nothing failed and every row left is one the decisions + leave: rows with missing parameters, and saved simulations. + """ + + remaining: tuple[RemainingV1References, ...] + passed: bool + + +@dataclass(frozen=True) +class MigrationRun: + """One run of the command: its options, each row's result and the check.""" + + options: MigrationOptions + policyengine_version: str + results: tuple[SavedRecordResult, ...] + closing_check: ClosingCheck diff --git a/policyengine_api/services/v2/saved_record_migration/validators.py b/policyengine_api/services/v2/saved_record_migration/validators.py new file mode 100644 index 000000000..43cc3e537 --- /dev/null +++ b/policyengine_api/services/v2/saved_record_migration/validators.py @@ -0,0 +1,200 @@ +"""Checks the one-time migration makes on rows it has already read (D4 · 1). + +A v1 report is rebuilt from its report output and simulations as v1's report +spec reads them (``policyengine_api.services.report_spec_service``), and a v1 +region is translated through the catalog's region reference files, which +pair each catalog region with the v1 region it replaces (``v1_code``). A row +that can't be migrated raises ``SavedRecordMigrationRefusal`` with a reason, +and keeps its v1 reference. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from policyengine_api.services.v2.saved_record_migration.types import ( + FailureReason, + V1ReportDefinition, + V1ReportKind, +) + +if TYPE_CHECKING: + from collections.abc import Iterable + + from policyengine_api.data.v2.catalog.region_references import RegionReference + from policyengine_api.services.v2.saved_record_migration.types import ( + V1ReportRecord, + V1SimulationRecord, + ) + +_POPULATION_KINDS = { + "geography": V1ReportKind.ECONOMY, + "household": V1ReportKind.HOUSEHOLD, +} +_NATIONAL_REGIONS = {"uk": "uk", "us": "us"} +_US_STATE_CODE_LENGTH = 2 + + +class SavedRecordMigrationRefusal(Exception): # noqa: N818 # a refusal, not a programming error + """A saved record can't be migrated, for ``reason``; it keeps its v1 reference.""" + + def __init__(self, reason: FailureReason, message: str) -> None: + """Keep ``reason`` for the row's result and ``message`` as its detail.""" + super().__init__(message) + self.reason = reason + + +class ReportSubmissionRefusedError(Exception): + """The simulation service refused a report definition (its 400 or 422). + + ``code`` is the service's error code, such as ``unknown_region``. + """ + + def __init__(self, code: str, message: str) -> None: + """Keep the service's ``code`` with its ``message``.""" + super().__init__(message) + self.code = code + + +class ReportSubmissionUnavailableError(Exception): + """The simulation service could not answer; the report may be retried.""" + + +def _unreadable(message: str) -> SavedRecordMigrationRefusal: + return SavedRecordMigrationRefusal(FailureReason.V1_REPORT_UNREADABLE, message) + + +def _report_year(report: V1ReportRecord) -> int: + year = (report.year or "").strip() + if not year.isdigit(): + msg = f"v1 report {report.report_id}'s year isn't a number: {report.year!r}" + raise _unreadable(msg) + return int(year) + + +def _legacy_household_id(simulation: V1SimulationRecord) -> int: + population = simulation.population_id.strip() + if not population.isdigit(): + msg = ( + f"v1 simulation {simulation.simulation_id} names household " + f"{simulation.population_id!r}, not a household ID" + ) + raise _unreadable(msg) + return int(population) + + +def _check_simulations( + report: V1ReportRecord, + baseline: V1SimulationRecord, + reform: V1SimulationRecord | None, +) -> V1ReportKind: + if baseline.simulation_id != report.simulation_1_id or ( + (reform.simulation_id if reform is not None else None) != report.simulation_2_id + ): + msg = f"v1 report {report.report_id}'s simulations are not the ones it names" + raise _unreadable(msg) + simulations = [baseline] if reform is None else [baseline, reform] + if any(simulation.country_id != report.country_id for simulation in simulations): + msg = f"v1 report {report.report_id} names a simulation of another country" + raise _unreadable(msg) + kinds = {simulation.population_type for simulation in simulations} + if len(kinds) != 1 or not kinds <= set(_POPULATION_KINDS): + msg = ( + f"v1 report {report.report_id}'s simulations have population types " + f"{sorted(kinds)}, not one of geography or household" + ) + raise _unreadable(msg) + return _POPULATION_KINDS[kinds.pop()] + + +def validate_v1_report( + report: V1ReportRecord, + baseline: V1SimulationRecord, + reform: V1SimulationRecord | None, +) -> V1ReportDefinition: + """Return the v1 report's definition, as v1's report spec reads it. + + ``baseline`` is the report's simulation 1 and ``reform`` its simulation + 2, None for a report of one simulation. Raise SavedRecordMigrationRefusal + (``v1_report_unreadable``) when the simulations aren't the report's, are + of another country or of different population types, cover different + regions or households, or when the year isn't a number. + """ + kind = _check_simulations(report, baseline, reform) + year = _report_year(report) + if kind is V1ReportKind.HOUSEHOLD: + household_id = _legacy_household_id(baseline) + if reform is not None and _legacy_household_id(reform) != household_id: + msg = f"v1 report {report.report_id} compares two different households" + raise _unreadable(msg) + return V1ReportDefinition( + country_id=report.country_id, + legacy_report_id=report.report_id, + kind=kind, + year=year, + region=None, + legacy_household_id=household_id, + baseline_policy_id=baseline.policy_id, + reform_policy_id=None if reform is None else reform.policy_id, + ) + if reform is not None and reform.population_id != baseline.population_id: + msg = f"v1 report {report.report_id} compares two different regions" + raise _unreadable(msg) + return V1ReportDefinition( + country_id=report.country_id, + legacy_report_id=report.report_id, + kind=kind, + year=year, + region=baseline.population_id, + legacy_household_id=None, + baseline_policy_id=baseline.policy_id, + # v1 runs a report of one economy simulation with its policy on both + # sides (ReportSpecService.build_report_spec). + reform_policy_id=(baseline if reform is None else reform).policy_id, + ) + + +def _spelled_as_v1_matches(country_id: str, v1_region: str) -> str: + """Spell a v1 region as v1 normalised it before running it. + + A blank region is the country. In the UK, a region without a type is a + nation, lower-cased with spaces as underscores (``normalise_uk_region``); + in the US, a bare two-letter state code is that state + (``normalize_us_region``). + """ + region = v1_region.strip() + if region == "": + return _NATIONAL_REGIONS[country_id] + if "/" in region: + return region + if country_id == "uk" and region.lower() != "uk": + return f"country/{region.lower().replace(' ', '_')}" + if ( + country_id == "us" + and region.lower() != "us" + and len(region) == _US_STATE_CODE_LENGTH + ): + return f"state/{region.lower()}" + return region + + +def require_catalog_region_code( + country_id: str, v1_region: str, references: Iterable[RegionReference] +) -> str: + """Return the catalog code of the region a v1 economy report ran on. + + The v1 region matches a region's ``v1_code``, or its catalog code, ignoring + case: a UK constituency or local authority by name (its v1 code) or by + ONS code (its catalog code). Raise SavedRecordMigrationRefusal + (``unknown_region``) when no region of the country matches. + """ + spelled = _spelled_as_v1_matches(country_id, v1_region).casefold() + by_spelling: dict[str, str] = {} + for reference in references: + by_spelling.setdefault(reference.code.casefold(), reference.code) + if reference.v1_code is not None: + by_spelling.setdefault(reference.v1_code.casefold(), reference.code) + if spelled not in by_spelling: + msg = f"{country_id} has no catalog region for v1 region {v1_region!r}" + raise SavedRecordMigrationRefusal(FailureReason.UNKNOWN_REGION, msg) + return by_spelling[spelled] diff --git a/pyproject.toml b/pyproject.toml index f981d1824..31c6bf82d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -417,6 +417,9 @@ banned-module-level-imports = [ "policyengine_api.services.v2.policies.services", "policyengine_api.services.v2.report_run_records.database_session", "policyengine_api.services.v2.report_run_records.services", + "policyengine_api.services.v2.saved_record_migration.copies.services", + "policyengine_api.services.v2.saved_record_migration.database_session", + "policyengine_api.services.v2.saved_record_migration.services", "policyengine_api.services.v2.simulation_service.services", "policyengine_api.services.v2.stored_reports.database_session", "policyengine_api.services.v2.stored_reports.services", diff --git a/scripts/migrate_saved_records_to_detailed_save.py b/scripts/migrate_saved_records_to_detailed_save.py new file mode 100755 index 000000000..1ba414685 --- /dev/null +++ b/scripts/migrate_saved_records_to_detailed_save.py @@ -0,0 +1,247 @@ +#!/usr/bin/env python3 +"""Give saved records that hold only a v1 reference their detailed-save records. + +The one-time migration (D4 · 1). Usage:: + + migrate_saved_records_to_detailed_save.py [--dry-run] + [--drop-missing-parameters] [--country us|uk ...] [--limit N] + [--user-id UUID ...] + +It reads every saved reform, saved household, saved report and saved +simulation that holds a v1 reference and no detailed-save reference, oldest +first, and gives each of the first three the detailed-save record that v1 +reference stands for: a saved reform its v1 policy's copy, split into a +policy and a dynamic, with a saved dynamic of the same name when the v1 +policy sets model assumptions; a saved household its v1 household's copy; a +saved report the report the simulation service finds or creates for the v1 +report's definition. Each row keeps its v1 reference. Saved simulations are +only listed. Running it again picks up what is left. + +- ``--dry-run`` reads both databases and writes nothing; it calls no other + service. +- A row whose policies set a parameter the running catalog lacks is left + and listed. ``--drop-missing-parameters`` (the last run, E1 · 4) migrates + it from the parameters that still exist and lists those it dropped; a row + whose every parameter is missing is still left and listed. +- ``--country`` keeps the run to one country (both without it), ``--limit`` + to the oldest N rows of each kind, and ``--user-id`` to those owners' rows. + The closing check covers the same rows. + +It prints one JSON document: counts of each kind's rows by outcome, every +row's result (the detailed-save ID it now holds, or why not), and the closing +check, which counts the rows still holding only a v1 reference by why. It +exits 0 when the check passes (nothing failed, and nothing is left but rows +with missing parameters and saved simulations), 1 when it doesn't, and 2 for +bad arguments. + +Run it from a checkout of the commit deployed in that environment, since +copies bind to the running .py version's catalog. It connects as the +deployed API v1 does: + +- the detailed-save database as the runtime role: ``V2_RUNTIME_DATABASE_URL`` + (or ``V2_RUNTIME_DATABASE_URL_SECRET_RESOURCE``), ``V2_SUPABASE_PROJECT_REF`` + and ``V2_SUPABASE_ENVIRONMENT``; a dry run's transactions are read only; +- v1's database read only, as ``policyengine_schema_reader`` through the Cloud + SQL Auth Proxy on 127.0.0.1 (``POLICYENGINE_DB_READONLY_PASSWORD``, and + ``POLICYENGINE_DB_PROXY_PORT``, 3307 without it). +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +from contextlib import contextmanager +from typing import TYPE_CHECKING, Protocol +from uuid import UUID + +from sqlalchemy.engine import URL + +from policyengine_api.data.v1_sessions import unpooled_v1_sessions +from policyengine_api.data.v2.settings import load_v2_runtime_database_settings +from policyengine_api.services.v2.saved_record_migration.transformations import ( + migration_document, +) +from policyengine_api.services.v2.saved_record_migration.types import ( + MigrationOptions, +) + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator, Mapping, Sequence + from contextlib import AbstractContextManager + + from policyengine_api.services.v2.saved_record_migration.types import ( + MigrationRun, + ) + +COUNTRIES = ("uk", "us") +V1_DATABASE_NAME = "policyengine" +V1_READ_ONLY_USER = "policyengine_schema_reader" +V1_PROXY_HOST = "127.0.0.1" +V1_PROXY_PORT = "POLICYENGINE_DB_PROXY_PORT" +DEFAULT_V1_PROXY_PORT = 3307 + + +class MissingSettingError(RuntimeError): + """A setting the command needs to connect is not set.""" + + +class SavedRecordMigrator(Protocol): + """The migration service operation this command calls.""" + + def migrate(self, options: MigrationOptions) -> MigrationRun: + """Migrate the rows ``options`` selects and check what is left.""" + ... + + +def v1_read_only_database_url(environ: Mapping[str, str]) -> URL: + """Return the URL of v1's database as its read-only role, through the proxy. + + Raise MissingSettingError without ``POLICYENGINE_DB_READONLY_PASSWORD``. + """ + password = environ.get("POLICYENGINE_DB_READONLY_PASSWORD", "") + if not password: + msg = "POLICYENGINE_DB_READONLY_PASSWORD is required to read v1's database" + raise MissingSettingError(msg) + return URL.create( + drivername="mysql+pymysql", + username=V1_READ_ONLY_USER, + password=password, + host=V1_PROXY_HOST, + port=int(environ.get(V1_PROXY_PORT, "") or DEFAULT_V1_PROXY_PORT), + database=V1_DATABASE_NAME, + ) + + +@contextmanager +def _migrator_from_environment(*, dry_run: bool) -> Iterator[SavedRecordMigrator]: + """Build the migration service on the deployed API v1's connections.""" + # These modules are imported only when the command runs, as they read the + # database settings or need the connections. + from policyengine_api.data.v2.database import ( + unpooled_v2_read_only_sessions, + unpooled_v2_sessions, + ) + from policyengine_api.services.v2.saved_record_migration.database_session import ( + SavedRecordMigrationDatabaseSession, + V1RecordDatabaseSession, + ) + from policyengine_api.services.v2.saved_record_migration.services import ( + V2SavedRecordMigrationService, + ) + + v2_url = load_v2_runtime_database_settings().connection.url + v1_url = v1_read_only_database_url(os.environ) + open_v2_sessions = ( + unpooled_v2_read_only_sessions if dry_run else unpooled_v2_sessions + ) + with ( + open_v2_sessions(v2_url) as v2_sessions, + unpooled_v1_sessions(v1_url) as v1_sessions, + ): + yield V2SavedRecordMigrationService( + SavedRecordMigrationDatabaseSession(v2_sessions), + V1RecordDatabaseSession(v1_sessions), + ) + + +def _positive_integer(text: str) -> int: + try: + value = int(text) + except ValueError as error: + msg = f"{text!r} is not a whole number" + raise argparse.ArgumentTypeError(msg) from error + if value < 1: + msg = "the limit must be at least 1" + raise argparse.ArgumentTypeError(msg) + return value + + +def _user_id(text: str) -> UUID: + try: + return UUID(text) + except ValueError as error: + msg = f"{text!r} is not a user ID" + raise argparse.ArgumentTypeError(msg) from error + + +def _parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description=( + "Give saved records that hold only a v1 reference their " + "detailed-save records, and check what is left." + ) + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="Read both databases and write nothing", + ) + parser.add_argument( + "--drop-missing-parameters", + action="store_true", + help=( + "Migrate rows whose policies set parameters the running catalog " + "lacks, from the parameters that still exist" + ), + ) + parser.add_argument( + "--country", + action="append", + choices=COUNTRIES, + dest="countries", + help="Migrate this country's rows only; repeat for both (the default)", + ) + parser.add_argument( + "--limit", + type=_positive_integer, + help="Migrate at most this many rows of each kind, oldest first", + ) + parser.add_argument( + "--user-id", + action="append", + type=_user_id, + dest="user_ids", + help="Migrate this user's rows only; repeat for more users", + ) + return parser + + +def _options(arguments: argparse.Namespace) -> MigrationOptions: + return MigrationOptions( + apply=not arguments.dry_run, + drop_missing_parameters=arguments.drop_missing_parameters, + country_ids=( + COUNTRIES + if arguments.countries is None + else tuple(sorted(set(arguments.countries))) + ), + limit=arguments.limit, + user_ids=None if arguments.user_ids is None else tuple(arguments.user_ids), + ) + + +def main( + argv: Sequence[str] | None = None, + *, + migrator_factory: Callable[..., AbstractContextManager[SavedRecordMigrator]] = ( + _migrator_from_environment + ), +) -> int: + """Run the migration and print its document; return 0 when its check passes. + + Bad arguments exit 2 before anything connects. Any other failure, such + as missing settings or an unreachable database, raises, so Python prints + its traceback and exits with 1. + """ + arguments = _parser().parse_args(argv) + options = _options(arguments) + with migrator_factory(dry_run=arguments.dry_run) as migrator: + run = migrator.migrate(options) + print(json.dumps(migration_document(run), indent=2)) + return 0 if run.closing_check.passed else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/integration/test_v2_saved_record_migration.py b/tests/integration/test_v2_saved_record_migration.py index a859cbafa..84849f0cd 100644 --- a/tests/integration/test_v2_saved_record_migration.py +++ b/tests/integration/test_v2_saved_record_migration.py @@ -15,26 +15,6 @@ from uuid import UUID, uuid4 import pytest -from policyengine_api.services.v2.saved_record_migration.database_session import ( - SavedRecordMigrationDatabaseSession, - V1RecordDatabaseSession, -) -from policyengine_api.services.v2.saved_record_migration.services import ( - V2SavedRecordMigrationService, -) -from policyengine_api.services.v2.saved_record_migration.types import ( - DetailedSaveReportDefinition, - DetailedSaveReportKind, - FailureReason, - MigrationOptions, - MigrationRun, - PolicySide, - RowOutcome, - SavedRecordKind, -) -from policyengine_api.services.v2.saved_record_migration.validators import ( - ReportSubmissionRefusedError, -) from sqlalchemy import delete, func, select from sqlmodel import col @@ -61,6 +41,26 @@ UserReportAssociation, UserSimulationAssociation, ) +from policyengine_api.services.v2.saved_record_migration.database_session import ( + SavedRecordMigrationDatabaseSession, + V1RecordDatabaseSession, +) +from policyengine_api.services.v2.saved_record_migration.services import ( + V2SavedRecordMigrationService, +) +from policyengine_api.services.v2.saved_record_migration.types import ( + DetailedSaveReportDefinition, + DetailedSaveReportKind, + FailureReason, + MigrationOptions, + MigrationRun, + PolicySide, + RowOutcome, + SavedRecordKind, +) +from policyengine_api.services.v2.saved_record_migration.validators import ( + ReportSubmissionRefusedError, +) from tests.integration.simulation_rows import add_row from tests.integration.stored_report_rows import ( CatalogRows, diff --git a/tests/unit/test_migrate_saved_records_script.py b/tests/unit/test_migrate_saved_records_script.py index 36346072e..ba7201a36 100644 --- a/tests/unit/test_migrate_saved_records_script.py +++ b/tests/unit/test_migrate_saved_records_script.py @@ -10,6 +10,8 @@ from uuid import UUID import pytest + +from policyengine_api.constants import REPO from policyengine_api.services.v2.saved_record_migration.transformations import ( closing_check, ) @@ -20,8 +22,6 @@ SavedRecordKind, SavedRecordResult, ) - -from policyengine_api.constants import REPO from scripts import migrate_saved_records_to_detailed_save as command if TYPE_CHECKING: diff --git a/tests/unit/v2/test_saved_record_migration_rules.py b/tests/unit/v2/test_saved_record_migration_rules.py index d061092a4..3c60a72c9 100644 --- a/tests/unit/v2/test_saved_record_migration_rules.py +++ b/tests/unit/v2/test_saved_record_migration_rules.py @@ -12,6 +12,12 @@ from uuid import UUID import pytest + +from policyengine_api.data.v2.catalog.region_references import ( + load_region_references, +) +from policyengine_api.services.v2.policies.transformations import split_legacy_policy +from policyengine_api.services.v2.policies.types import LegacyPolicySnapshot from policyengine_api.services.v2.saved_record_migration.transformations import ( closing_check, detailed_save_report_definition, @@ -38,12 +44,6 @@ validate_v1_report, ) -from policyengine_api.data.v2.catalog.region_references import ( - load_region_references, -) -from policyengine_api.services.v2.policies.transformations import split_legacy_policy -from policyengine_api.services.v2.policies.types import LegacyPolicySnapshot - US_CTC_AMOUNT = "gov.irs.credits.ctc.amount.base" US_INCOME_ELASTICITY = "gov.simulation.labor_supply_responses.elasticities.income" UK_INCOME_ELASTICITY = "gov.simulation.labour_supply_responses.income_elasticity" From b82d621a057c86f48135cbf3566bc597b0d8904c Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:36:19 +0400 Subject: [PATCH 04/22] Add failing tests for the migration's sample comparison A separate run of the command (--compare-sample N) reads N migrated economy reports that have a successful run and prints API v1's stored budgetary impact next to the run's, with their relative difference and both country package versions (decided 2026-11-28). It writes nothing, starts no run and never fails on its own. Co-Authored-By: Claude Opus 5.5 --- .../test_v2_saved_record_migration.py | 152 ++++++++++++++++++ .../unit/test_migrate_saved_records_script.py | 41 +++++ .../v2/test_saved_record_migration_rules.py | 73 +++++++++ 3 files changed, 266 insertions(+) diff --git a/tests/integration/test_v2_saved_record_migration.py b/tests/integration/test_v2_saved_record_migration.py index 84849f0cd..3f15910a7 100644 --- a/tests/integration/test_v2_saved_record_migration.py +++ b/tests/integration/test_v2_saved_record_migration.py @@ -21,6 +21,7 @@ from policyengine_api.data.v1_models import Household as V1Household from policyengine_api.data.v1_models import Policy as V1Policy from policyengine_api.data.v1_models import ReportOutput as V1ReportOutput +from policyengine_api.data.v1_models import ReportOutputRun as V1ReportOutputRun from policyengine_api.data.v1_models import Simulation as V1Simulation from policyengine_api.data.v2.models import ( Dynamic, @@ -61,12 +62,15 @@ from policyengine_api.services.v2.saved_record_migration.validators import ( ReportSubmissionRefusedError, ) +from tests.fixtures.economy_results import us_economy_result from tests.integration.simulation_rows import add_row from tests.integration.stored_report_rows import ( CatalogRows, + RunSettings, delete_catalog, store_catalog, store_report, + store_report_run, ) if TYPE_CHECKING: @@ -193,6 +197,11 @@ def _store_v1_records(v1_sessions: sessionmaker[OrmSession]) -> None: def _delete_v1_records(v1_sessions: sessionmaker[OrmSession]) -> None: with v1_sessions.begin() as session: + session.execute( + delete(V1ReportOutputRun).where( + V1ReportOutputRun.report_output_id.in_(list(V1_REPORTS)) + ) + ) session.execute( delete(V1ReportOutput).where(V1ReportOutput.id.in_(list(V1_REPORTS))) ) @@ -968,3 +977,146 @@ def test_the_limit_leaves_rows_the_closing_check_counts( assert [result.outcome for result in run.results] == [RowOutcome.MIGRATED] assert _remaining(run, SavedRecordKind.SAVED_REFORM).not_attempted == 1 assert not run.closing_check.passed + + +# The sample comparison of migrated reports' results with v1's. + +RUN_VERSIONS = {"country_package_version": "2.2.2", "policyengine_version": "6.20.0"} + + +def _store_v1_result( + v1_sessions: sessionmaker[OrmSession], + report_id: int, + *, + budgetary_impact: float, + country_package_version: str, +) -> None: + """Give a v1 report output a stored result from a run on a package version.""" + run_id = str(uuid4()) + with v1_sessions.begin() as session: + session.add( + V1ReportOutputRun( + id=run_id, + report_output_id=report_id, + run_sequence=1, + status="complete", + trigger_type="initial", + country_package_version=country_package_version, + ) + ) + report = session.get(V1ReportOutput, report_id) + assert report is not None + report.output = {"budget": {"budgetary_impact": budgetary_impact}} + report.status = "complete" + report.latest_successful_run_id = run_id + + +def test_the_sample_compares_a_migrated_report_s_run_with_v1_s_result( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + catalog = stored_rows.report_catalog + assert catalog is not None + with v2_owner_sessions.begin() as session: + calculated = store_report(session, catalog) + run_ids = store_report_run( + session, + catalog, + calculated, + RunSettings(versions=RUN_VERSIONS), + result=us_economy_result(), + ) + never_run = store_report(session, catalog) + failed = store_report(session, catalog) + store_report_run( + session, + catalog, + failed, + RunSettings(versions=RUN_VERSIONS, status="failed", error_message="x"), + ) + for legacy_report_id, report_id in ( + (ECONOMY_REPORT, calculated.report_id), + (MISSING_PARAMETER_REPORT, never_run.report_id), + (UNKNOWN_REGION_REPORT, failed.report_id), + ): + _save( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=legacy_report_id, + report_id=report_id, + ) + # A saved report holding only its detailed-save report wasn't migrated. + _save( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.second_user, + report_id=calculated.report_id, + ) + _store_v1_result( + v1_sessions, + ECONOMY_REPORT, + budgetary_impact=-10.0e9, + country_package_version="1.420.0", + ) + simulation_service = _simulation_service(v2_owner_sessions, stored_rows) + service = _service(runtime_sessions, v1_sessions, simulation_service) + + comparison = service.compare_sample( + size=5, + country_ids=("us",), + user_ids=(stored_rows.first_user, stored_rows.second_user), + ) + + expected = us_economy_result()["budget"]["budgetary_impact"] + (item,) = comparison.comparisons + assert (item.legacy_report_id, item.report_id, item.report_run_id) == ( + ECONOMY_REPORT, + calculated.report_id, + run_ids.report_run_id, + ) + assert (item.v1_budgetary_impact, item.v1_country_package_version) == ( + -10.0e9, + "1.420.0", + ) + assert item.detailed_save_budgetary_impact == pytest.approx(expected) + assert item.detailed_save_country_package_version == "2.2.2" + assert item.relative_difference == pytest.approx((expected + 10.0e9) / 10.0e9) + assert simulation_service.definitions == [] + + +def test_the_sample_takes_at_most_its_size( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + catalog = stored_rows.report_catalog + assert catalog is not None + for legacy_report_id in (ECONOMY_REPORT, HOUSEHOLD_REPORT): + with v2_owner_sessions.begin() as session: + report = store_report(session, catalog) + store_report_run( + session, + catalog, + report, + RunSettings(versions=RUN_VERSIONS), + result=us_economy_result(), + ) + _save( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=legacy_report_id, + report_id=report.report_id, + ) + service = _service( + runtime_sessions, + v1_sessions, + _simulation_service(v2_owner_sessions, stored_rows), + ) + + comparison = service.compare_sample( + size=1, country_ids=("us",), user_ids=(stored_rows.first_user,) + ) + + (item,) = comparison.comparisons + # v1 stored no result for this report. + assert item.v1_budgetary_impact is None + assert item.relative_difference is None diff --git a/tests/unit/test_migrate_saved_records_script.py b/tests/unit/test_migrate_saved_records_script.py index ba7201a36..53b574ad0 100644 --- a/tests/unit/test_migrate_saved_records_script.py +++ b/tests/unit/test_migrate_saved_records_script.py @@ -19,6 +19,7 @@ MigrationOptions, MigrationRun, RowOutcome, + SampleComparison, SavedRecordKind, SavedRecordResult, ) @@ -38,6 +39,13 @@ class FakeMigrator: def __init__(self, remaining: set[UUID] | None = None) -> None: self.remaining = remaining or set() self.options: list[MigrationOptions] = [] + self.samples: list[tuple[int, tuple[str, ...]]] = [] + + def compare_sample( + self, *, size: int, country_ids: tuple[str, ...] + ) -> SampleComparison: + self.samples.append((size, country_ids)) + return SampleComparison(size=size, country_ids=country_ids, comparisons=()) def migrate(self, options: MigrationOptions) -> MigrationRun: self.options.append(options) @@ -161,6 +169,39 @@ def test_bad_arguments_exit_2_without_building_a_migrator(arguments) -> None: assert factory.dry_runs == [] +def test_a_sample_comparison_reads_only_and_migrates_nothing(capsys) -> None: + factory = RecordingFactory(FakeMigrator()) + + exit_code = _run(["--compare-sample", "20", "--country", "us"], factory) + + assert exit_code == 0 + assert factory.dry_runs == [True] + assert factory.migrator.samples == [(20, ("us",))] + assert factory.migrator.options == [] + document = json.loads(capsys.readouterr().out) + assert (document["mode"], document["sample_size"]) == ("compare_sample", 20) + + +@pytest.mark.parametrize( + "arguments", + [ + ["--compare-sample", "0"], + ["--compare-sample", "5", "--dry-run"], + ["--compare-sample", "5", "--drop-missing-parameters"], + ["--compare-sample", "5", "--limit", "3"], + ["--compare-sample", "5", "--user-id", str(FIRST_USER)], + ], +) +def test_a_sample_comparison_takes_no_migration_flag(arguments) -> None: + factory = RecordingFactory(FakeMigrator()) + + with pytest.raises(SystemExit) as stopped: + _run(arguments, factory) + + assert stopped.value.code == 2 + assert factory.dry_runs == [] + + def test_v1_is_read_as_the_read_only_role_through_the_proxy() -> None: url = command.v1_read_only_database_url( {"POLICYENGINE_DB_READONLY_PASSWORD": "reader-secret"} diff --git a/tests/unit/v2/test_saved_record_migration_rules.py b/tests/unit/v2/test_saved_record_migration_rules.py index 3c60a72c9..aaeffec04 100644 --- a/tests/unit/v2/test_saved_record_migration_rules.py +++ b/tests/unit/v2/test_saved_record_migration_rules.py @@ -23,6 +23,8 @@ detailed_save_report_definition, kept_policy_snapshot, migration_document, + relative_difference, + sample_comparison_document, ) from policyengine_api.services.v2.saved_record_migration.types import ( DetailedSaveReportKind, @@ -30,7 +32,9 @@ MigrationOptions, MigrationRun, PolicySide, + ReportComparison, RowOutcome, + SampleComparison, SavedRecordKind, SavedRecordResult, V1ReportDefinition, @@ -556,3 +560,72 @@ def test_a_dry_run_document_says_so() -> None: assert document["countries"] == ["uk", "us"] assert document["limit"] is None assert document["rows"] == [] + + +# The sample comparison of migrated reports' results with v1's. + + +@pytest.mark.parametrize( + ("v1_value", "detailed_save_value", "difference"), + [ + (-10.0e9, -10.4e9, -0.04), + (2.0e9, 2.0e9, 0.0), + (-5.0e9, 5.0e9, 2.0), + (0.0, 1.0e9, None), + (None, 1.0e9, None), + (1.0e9, None, None), + ], +) +def test_the_relative_difference_is_measured_from_v1_s_value( + v1_value: float | None, + detailed_save_value: float | None, + difference: float | None, +) -> None: + measured = relative_difference(v1_value, detailed_save_value) + + if difference is None: + assert measured is None + else: + assert measured == pytest.approx(difference) + + +def test_the_comparison_document_lists_each_report_s_two_results() -> None: + comparison = SampleComparison( + size=5, + country_ids=("us",), + comparisons=( + ReportComparison( + country_id="us", + legacy_report_id=900, + report_id=FIRST_ROW, + report_run_id=SECOND_ROW, + v1_budgetary_impact=-10.0e9, + v1_country_package_version="1.420.0", + detailed_save_budgetary_impact=-10.4e9, + detailed_save_country_package_version="2.2.2", + relative_difference=-0.04, + ), + ), + ) + + document = json.loads(json.dumps(sample_comparison_document(comparison))) + + assert document == { + "mode": "compare_sample", + "sample_size": 5, + "countries": ["us"], + "reports": [ + { + "country_id": "us", + "legacy_report_id": 900, + "report_id": str(FIRST_ROW), + "report_run_id": str(SECOND_ROW), + "v1_budgetary_impact": -10.0e9, + "v1_country_package_version": "1.420.0", + "detailed_save_budgetary_impact": -10.4e9, + "detailed_save_country_package_version": "2.2.2", + "relative_difference": -0.04, + "note": None, + } + ], + } From 256a6c22d7fec4f8144dcb1ef37c2cf23b5b5e05 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:39:42 +0400 Subject: [PATCH 05/22] Add the migration's sample comparison of reports' results with API v1's --compare-sample N reads up to N migrated economy reports, each named by a saved report that holds both its API v1 report output and its report and having a successful run, and prints API v1's stored budgetary impact next to the newest successful run's, rebuilt from its budget summary as /v2/reports does, with the relative difference and both country package versions. It reads both databases only, starts no run and exits 0: a person reads it, since a newer model alone can change the numbers. Co-Authored-By: Claude Opus 5.5 --- .../database_connectors/reads.py | 80 +++++++++++++++++ .../database_connectors/reads_v1_records.py | 38 +++++++- .../v2/saved_record_migration/services.py | 86 +++++++++++++++++++ .../saved_record_migration/transformations.py | 60 +++++++++++++ .../v2/saved_record_migration/types.py | 57 ++++++++++++ .../migrate_saved_records_to_detailed_save.py | 42 ++++++++- 6 files changed, 360 insertions(+), 3 deletions(-) diff --git a/policyengine_api/services/v2/saved_record_migration/database_connectors/reads.py b/policyengine_api/services/v2/saved_record_migration/database_connectors/reads.py index e4f4fcea0..84dafb454 100644 --- a/policyengine_api/services/v2/saved_record_migration/database_connectors/reads.py +++ b/policyengine_api/services/v2/saved_record_migration/database_connectors/reads.py @@ -13,12 +13,19 @@ from sqlmodel import col from policyengine_api.data.v2.models import ( + BudgetSummary, Household, + Report, + ReportRun, + ReportRunStatus, UserHouseholdAssociation, UserPolicy, UserReportAssociation, UserSimulationAssociation, ) +from policyengine_api.services.v2.saved_record_migration.types import ( + MigratedReportRun, +) if TYPE_CHECKING: from collections.abc import Sequence @@ -147,3 +154,76 @@ def read_household_default_year(session: Session, household_id: UUID) -> int | N return session.scalar( select(col(Household.default_year)).where(col(Household.id) == household_id) ) + + +def read_migrated_economy_report_runs( + session: Session, + *, + country_ids: Sequence[str], + user_ids: Sequence[UUID] | None, + limit: int, +) -> list[MigratedReportRun]: + """Return up to ``limit`` migrated economy reports and their newest successful runs. + + A migrated saved report holds both its v1 report output and its report; + each pair is returned once, ordered by report ID, which is random. A + budget window and a household report are left out, and so is a report + with no successful run. + """ + statement = ( + select( + col(UserReportAssociation.country_id), + col(UserReportAssociation.legacy_report_id), + col(UserReportAssociation.report_id), + col(ReportRun.id), + col(ReportRun.country_package_version), + ) + .join(Report, col(Report.id) == col(UserReportAssociation.report_id)) + .join(ReportRun, col(ReportRun.report_id) == col(Report.id)) + .where( + col(UserReportAssociation.legacy_report_id).is_not(None), + col(UserReportAssociation.country_id).in_(list(country_ids)), + col(Report.type) == "economy", + col(Report.budget_window_size).is_(None), + col(ReportRun.status) == ReportRunStatus.SUCCEEDED, + col(ReportRun.budget_window_run_id).is_(None), + ) + .order_by( + col(UserReportAssociation.report_id), + col(UserReportAssociation.legacy_report_id), + col(ReportRun.completed_at).desc(), + col(ReportRun.id), + ) + ) + if user_ids is not None: + statement = statement.where( + col(UserReportAssociation.user_id).in_(list(user_ids)) + ) + runs: dict[tuple[int, UUID], MigratedReportRun] = {} + for row in session.execute(statement): + key = (row.legacy_report_id, row.report_id) + if key in runs: + continue + if len(runs) == limit: + break + runs[key] = MigratedReportRun( + country_id=row.country_id, + legacy_report_id=row.legacy_report_id, + report_id=row.report_id, + report_run_id=row.id, + country_package_version=row.country_package_version, + ) + return list(runs.values()) + + +def read_budget_summary_rows( + session: Session, report_run_id: UUID +) -> tuple[BudgetSummary, ...]: + """Return a report run's budget summary rows.""" + return tuple( + session.scalars( + select(BudgetSummary).where( + col(BudgetSummary.report_run_id) == report_run_id + ) + ) + ) diff --git a/policyengine_api/services/v2/saved_record_migration/database_connectors/reads_v1_records.py b/policyengine_api/services/v2/saved_record_migration/database_connectors/reads_v1_records.py index 20a51b8a3..c79ce5f4a 100644 --- a/policyengine_api/services/v2/saved_record_migration/database_connectors/reads_v1_records.py +++ b/policyengine_api/services/v2/saved_record_migration/database_connectors/reads_v1_records.py @@ -11,11 +11,18 @@ from sqlalchemy import select -from policyengine_api.data.v1_models import Household, Policy, ReportOutput, Simulation +from policyengine_api.data.v1_models import ( + Household, + Policy, + ReportOutput, + ReportOutputRun, + Simulation, +) from policyengine_api.services.v2.households.types import LegacyHouseholdSnapshot from policyengine_api.services.v2.policies.types import LegacyPolicySnapshot from policyengine_api.services.v2.saved_record_migration.types import ( V1ReportRecord, + V1ReportResult, V1SimulationRecord, ) @@ -126,3 +133,32 @@ def read_v1_simulations( ) for row in rows } + + +def read_v1_report_result( + session: Session, *, country_id: str, report_id: int +) -> V1ReportResult | None: + """Return the v1 report output's stored result, or None when it doesn't exist. + + The package version is its latest successful run's, when v1 recorded one. + """ + row = session.execute( + select(ReportOutput.output, ReportOutput.latest_successful_run_id).where( + ReportOutput.id == report_id, ReportOutput.country_id == country_id + ) + ).first() + if row is None: + return None + country_package_version = ( + None + if row.latest_successful_run_id is None + else session.scalar( + select(ReportOutputRun.country_package_version).where( + ReportOutputRun.id == row.latest_successful_run_id + ) + ) + ) + return V1ReportResult( + output=copy.deepcopy(row.output), + country_package_version=country_package_version, + ) diff --git a/policyengine_api/services/v2/saved_record_migration/services.py b/policyengine_api/services/v2/saved_record_migration/services.py index 9b6cc787a..33759421a 100644 --- a/policyengine_api/services/v2/saved_record_migration/services.py +++ b/policyengine_api/services/v2/saved_record_migration/services.py @@ -41,6 +41,8 @@ load_region_references, ) from policyengine_api.services.v2.saved_record_migration.database_connectors.reads import ( # noqa: E501 # a dotted module path cannot be wrapped + read_budget_summary_rows, + read_migrated_economy_report_runs, read_saved_households_holding_only_v1_households, read_saved_reforms_holding_only_v1_policies, read_saved_reports_holding_only_v1_reports, @@ -50,6 +52,7 @@ read_v1_household_snapshot, read_v1_policy_snapshot, read_v1_report, + read_v1_report_result, read_v1_simulations, ) from policyengine_api.services.v2.saved_record_migration.database_connectors.updates import ( # noqa: E501 # a dotted module path cannot be wrapped @@ -64,11 +67,15 @@ pending_saved_reform, pending_saved_report, pending_saved_simulation, + relative_difference, + v1_budgetary_impact, ) from policyengine_api.services.v2.saved_record_migration.types import ( FailureReason, MigrationRun, + ReportComparison, RowOutcome, + SampleComparison, SavedRecordKind, SavedRecordResult, V1ReportKind, @@ -80,6 +87,12 @@ require_catalog_region_code, validate_v1_report, ) +from policyengine_api.services.v2.stored_reports.economy_results.transformations import ( # noqa: E501 # a dotted module path cannot be wrapped + budget_impact, +) +from policyengine_api.services.v2.stored_reports.economy_results.types import ( + EconomyResultUnreadableError, +) from policyengine_api.services.v2.user_dynamics.types import ( UserDynamicCreationInput, ) @@ -102,6 +115,7 @@ ) from policyengine_api.services.v2.saved_record_migration.types import ( DetailedSaveReportDefinition, + MigratedReportRun, MigrationOptions, PendingSavedRecord, PolicyMigrationPlan, @@ -219,6 +233,78 @@ def migrate(self, options: MigrationOptions) -> MigrationRun: closing_check=closing_check(remaining, results), ) + def compare_sample( + self, + *, + size: int, + country_ids: tuple[str, ...], + user_ids: tuple[UUID, ...] | None = None, + ) -> SampleComparison: + """Put up to ``size`` migrated reports' run results next to v1's. + + Each is a migrated economy report with a successful run: v1's + stored budgetary impact and the run's, with their package versions. + It writes nothing and starts no run. ``user_ids`` keeps it to those + owners' saved reports. + """ + with self._database.read() as session: + runs = read_migrated_economy_report_runs( + session, country_ids=country_ids, user_ids=user_ids, limit=size + ) + run_results = { + run.report_run_id: self._run_budgetary_impact(session, run) + for run in runs + } + comparisons = [] + for run in runs: + with self._v1_database.read() as session: + v1_result = read_v1_report_result( + session, country_id=run.country_id, report_id=run.legacy_report_id + ) + v1_value = ( + None if v1_result is None else v1_budgetary_impact(v1_result.output) + ) + run_value, run_note = run_results[run.report_run_id] + comparisons.append( + ReportComparison( + country_id=run.country_id, + legacy_report_id=run.legacy_report_id, + report_id=run.report_id, + report_run_id=run.report_run_id, + v1_budgetary_impact=v1_value, + v1_country_package_version=( + None if v1_result is None else v1_result.country_package_version + ), + detailed_save_budgetary_impact=run_value, + detailed_save_country_package_version=run.country_package_version, + relative_difference=relative_difference(v1_value, run_value), + note=( + run_note + if run_note is not None or v1_value is not None + else "v1 stored no budgetary impact for this report" + ), + ) + ) + return SampleComparison( + size=size, country_ids=country_ids, comparisons=tuple(comparisons) + ) + + @staticmethod + def _run_budgetary_impact( + session: Session, run: MigratedReportRun + ) -> tuple[float | None, str | None]: + """Return the run's budgetary impact, or None and why it can't be read.""" + try: + return ( + budget_impact( + country_id=run.country_id, + budget_summary=read_budget_summary_rows(session, run.report_run_id), + ).budgetary_impact, + None, + ) + except EconomyResultUnreadableError as error: + return None, f"the run's budget can't be read: {error}" + def _pending( self, options: MigrationOptions, *, limit: int | None ) -> list[PendingSavedRecord]: diff --git a/policyengine_api/services/v2/saved_record_migration/transformations.py b/policyengine_api/services/v2/saved_record_migration/transformations.py index 3cff901c7..f8767ae91 100644 --- a/policyengine_api/services/v2/saved_record_migration/transformations.py +++ b/policyengine_api/services/v2/saved_record_migration/transformations.py @@ -8,6 +8,7 @@ from __future__ import annotations +import json from collections import Counter from typing import TYPE_CHECKING @@ -37,6 +38,7 @@ from policyengine_api.services.v2.saved_record_migration.types import ( MigrationRun, PolicySide, + SampleComparison, SavedRecordResult, V1ReportDefinition, ) @@ -282,3 +284,61 @@ def migration_document(run: MigrationRun) -> dict[str, object]: }, }, } + + +def v1_budgetary_impact(output: object) -> float | None: + """Return the budgetary impact a v1 economy report output stored, if any. + + v1 stored the result as JSON, in some older rows as a JSON string; a + budget-window or household output, or none, has no single figure. + """ + if isinstance(output, str): + try: + output = json.loads(output) + except ValueError: + return None + if not isinstance(output, dict): + return None + budget = output.get("budget") + value = budget.get("budgetary_impact") if isinstance(budget, dict) else None + if isinstance(value, bool) or not isinstance(value, int | float): + return None + return float(value) + + +def relative_difference( + v1_value: float | None, detailed_save_value: float | None +) -> float | None: + """Return the detailed-save value's difference from v1's, as a fraction of v1's. + + None without both values, or when v1's is zero. + """ + if v1_value is None or detailed_save_value is None or v1_value == 0: + return None + return (detailed_save_value - v1_value) / abs(v1_value) + + +def sample_comparison_document(comparison: SampleComparison) -> dict[str, object]: + """Return the sample comparison as the JSON document the command prints.""" + return { + "mode": "compare_sample", + "sample_size": comparison.size, + "countries": list(comparison.country_ids), + "reports": [ + { + "country_id": item.country_id, + "legacy_report_id": item.legacy_report_id, + "report_id": str(item.report_id), + "report_run_id": str(item.report_run_id), + "v1_budgetary_impact": item.v1_budgetary_impact, + "v1_country_package_version": item.v1_country_package_version, + "detailed_save_budgetary_impact": (item.detailed_save_budgetary_impact), + "detailed_save_country_package_version": ( + item.detailed_save_country_package_version + ), + "relative_difference": item.relative_difference, + "note": item.note, + } + for item in comparison.comparisons + ], + } diff --git a/policyengine_api/services/v2/saved_record_migration/types.py b/policyengine_api/services/v2/saved_record_migration/types.py index febc628a0..26783b7a0 100644 --- a/policyengine_api/services/v2/saved_record_migration/types.py +++ b/policyengine_api/services/v2/saved_record_migration/types.py @@ -301,3 +301,60 @@ class MigrationRun: policyengine_version: str results: tuple[SavedRecordResult, ...] closing_check: ClosingCheck + + +@dataclass(frozen=True) +class MigratedReportRun: + """A migrated economy report's newest successful run. + + ``legacy_report_id`` is the v1 report output a saved report migrated + from, and ``report_id`` the report it now names. + """ + + country_id: str + legacy_report_id: int + report_id: UUID + report_run_id: UUID + country_package_version: str + + +@dataclass(frozen=True) +class V1ReportResult: + """A v1 report output's stored result and the package version it ran on. + + ``output`` is the stored JSON as v1 kept it; ``country_package_version`` + is its latest successful run's, or None when v1 recorded none. + """ + + output: object + country_package_version: str | None + + +@dataclass(frozen=True) +class ReportComparison: + """One migrated report's budgetary impact, as v1 stored it and as run since. + + ``relative_difference`` is the run's value minus v1's, as a fraction of + v1's, or None without both values or when v1's is zero. ``note`` says why + a value is missing. + """ + + country_id: str + legacy_report_id: int + report_id: UUID + report_run_id: UUID + v1_budgetary_impact: float | None + v1_country_package_version: str | None + detailed_save_budgetary_impact: float | None + detailed_save_country_package_version: str + relative_difference: float | None + note: str | None = None + + +@dataclass(frozen=True) +class SampleComparison: + """A sample of migrated reports' results next to v1's, for a person to read.""" + + size: int + country_ids: tuple[str, ...] + comparisons: tuple[ReportComparison, ...] diff --git a/scripts/migrate_saved_records_to_detailed_save.py b/scripts/migrate_saved_records_to_detailed_save.py index 1ba414685..b0be2749b 100755 --- a/scripts/migrate_saved_records_to_detailed_save.py +++ b/scripts/migrate_saved_records_to_detailed_save.py @@ -62,6 +62,7 @@ from policyengine_api.data.v2.settings import load_v2_runtime_database_settings from policyengine_api.services.v2.saved_record_migration.transformations import ( migration_document, + sample_comparison_document, ) from policyengine_api.services.v2.saved_record_migration.types import ( MigrationOptions, @@ -73,6 +74,7 @@ from policyengine_api.services.v2.saved_record_migration.types import ( MigrationRun, + SampleComparison, ) COUNTRIES = ("uk", "us") @@ -94,6 +96,12 @@ def migrate(self, options: MigrationOptions) -> MigrationRun: """Migrate the rows ``options`` selects and check what is left.""" ... + def compare_sample( + self, *, size: int, country_ids: tuple[str, ...] + ) -> SampleComparison: + """Put up to ``size`` migrated reports' run results next to v1's.""" + ... + def v1_read_only_database_url(environ: Mapping[str, str]) -> URL: """Return the URL of v1's database as its read-only role, through the proxy. @@ -198,6 +206,15 @@ def _parser() -> argparse.ArgumentParser: type=_positive_integer, help="Migrate at most this many rows of each kind, oldest first", ) + parser.add_argument( + "--compare-sample", + type=_positive_integer, + metavar="N", + help=( + "Migrate nothing: print v1's stored budgetary impact next to the " + "newest successful run's for N migrated economy reports" + ), + ) parser.add_argument( "--user-id", action="append", @@ -231,11 +248,32 @@ def main( ) -> int: """Run the migration and print its document; return 0 when its check passes. - Bad arguments exit 2 before anything connects. Any other failure, such + A sample comparison reads only, prints its document and returns 0. Bad + arguments exit 2 before anything connects. Any other failure, such as missing settings or an unreachable database, raises, so Python prints its traceback and exits with 1. """ - arguments = _parser().parse_args(argv) + parser = _parser() + arguments = parser.parse_args(argv) + countries = ( + COUNTRIES + if arguments.countries is None + else tuple(sorted(set(arguments.countries))) + ) + if arguments.compare_sample is not None: + if ( + arguments.dry_run + or arguments.drop_missing_parameters + or arguments.limit is not None + or arguments.user_ids is not None + ): + parser.error("--compare-sample takes only --country") + with migrator_factory(dry_run=True) as migrator: + comparison = migrator.compare_sample( + size=arguments.compare_sample, country_ids=countries + ) + print(json.dumps(sample_comparison_document(comparison), indent=2)) + return 0 options = _options(arguments) with migrator_factory(dry_run=arguments.dry_run) as migrator: run = migrator.migrate(options) From 4051b36ca2ff3d9bc5d1d905ce1bf25f02407a08 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:42:47 +0400 Subject: [PATCH 06/22] Name API v1 and API v2 in full in the saved-record migration The command becomes scripts/migrate_saved_records_to_api_v2.py, its output fields api_v2_id, api_v1_budgetary_impact and api_v2_budgetary_impact, and its types ApiV2ReportDefinition and ApiV2ReportKind. Docstrings, messages and the changelog fragment name API v1 and API v2 in full. Nothing else changes. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/v2-integration-check.yml | 2 +- changelog.d/saved-record-migration.added.md | 2 +- .../v2/saved_record_migration/__init__.py | 2 +- .../saved_record_migration/copies/services.py | 45 ++++---- .../database_connectors/reads.py | 16 +-- .../database_connectors/reads_v1_records.py | 16 +-- .../database_connectors/updates.py | 8 +- .../database_session.py | 12 +- .../v2/saved_record_migration/services.py | 107 +++++++++--------- .../saved_record_migration/transformations.py | 81 ++++++------- .../v2/saved_record_migration/types.py | 76 ++++++------- .../v2/saved_record_migration/validators.py | 38 ++++--- ....py => migrate_saved_records_to_api_v2.py} | 34 +++--- .../test_v2_saved_record_migration.py | 90 +++++++-------- .../unit/test_migrate_saved_records_script.py | 6 +- tests/unit/test_v2_integration_workflow.py | 2 +- .../v2/test_saved_record_migration_rules.py | 56 ++++----- 17 files changed, 294 insertions(+), 299 deletions(-) rename scripts/{migrate_saved_records_to_detailed_save.py => migrate_saved_records_to_api_v2.py} (88%) diff --git a/.github/workflows/v2-integration-check.yml b/.github/workflows/v2-integration-check.yml index 4822b754b..3f7134482 100644 --- a/.github/workflows/v2-integration-check.yml +++ b/.github/workflows/v2-integration-check.yml @@ -79,7 +79,7 @@ jobs: run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_policy_persistence.py tests/integration/test_v2_dynamic_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 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 the one-time migration of saved records' v1 references + - name: Test the one-time migration of saved records' API v1 references run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_saved_record_migration.py - name: Test comparison-run persistence, the simulation API's roles, shared reports and runs, privilege reconciliation as the managed roles, the v2 migration target checks as roles that don't own the database, and the tests' database sessions run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_stage12_comparison_persistence.py tests/integration/test_v2_simulation_role_privileges.py tests/integration/test_v2_shared_report_rows.py tests/integration/test_v2_privilege_reconciliation.py tests/integration/test_v2_migration_target_persistent.py tests/integration/test_database_sessions.py diff --git a/changelog.d/saved-record-migration.added.md b/changelog.d/saved-record-migration.added.md index 9ffdb50d3..7bcb27418 100644 --- a/changelog.d/saved-record-migration.added.md +++ b/changelog.d/saved-record-migration.added.md @@ -1 +1 @@ -Add API v1's one-time command that gives saved reforms, saved households and saved reports holding only a v1 reference their detailed-save records, splitting each v1 policy's model assumptions into a dynamic, with a dry run, a mode that drops parameters the running catalog lacks, and a closing check. +Add API v1's one-time command that gives saved reforms, saved households and saved reports holding only an API v1 reference their API v2 records, splitting each API v1 policy's model assumptions into a dynamic, with a dry run, a mode that drops parameters the running catalog lacks, and a closing check. diff --git a/policyengine_api/services/v2/saved_record_migration/__init__.py b/policyengine_api/services/v2/saved_record_migration/__init__.py index f2a2ac0f2..079f6a722 100644 --- a/policyengine_api/services/v2/saved_record_migration/__init__.py +++ b/policyengine_api/services/v2/saved_record_migration/__init__.py @@ -1 +1 @@ -"""The one-time migration of saved records' v1 references (D4 · 1).""" +"""The one-time migration of saved records' API v1 references (D4 · 1).""" diff --git a/policyengine_api/services/v2/saved_record_migration/copies/services.py b/policyengine_api/services/v2/saved_record_migration/copies/services.py index 000a3ed58..7800d9b5a 100644 --- a/policyengine_api/services/v2/saved_record_migration/copies/services.py +++ b/policyengine_api/services/v2/saved_record_migration/copies/services.py @@ -1,16 +1,17 @@ """The policy and household copies the one-time saved-record migration makes. -A v1 policy is planned before anything is written: its parameters are looked -up in the running catalog, its policy's among policy parameters and its -model assumptions among dynamic parameters, and the parameters the catalog -lacks are listed. A whole v1 policy is then copied by the v1-to-v2 copy -(``mirror_legacy_policy_in_session``), which splits its model assumptions -into a dynamic and maps the v1 ID to the pair. What the second mode keeps of -a policy with missing parameters is stored on its own, without a v1 ID -mapping, since it isn't a copy of the v1 policy (A1 · 6). A v1 household is -copied by ``mirror_legacy_household_in_session``. Each step works in the -caller's session, and a step that can't copy raises -SavedRecordMigrationRefusal with its reason. +An API v1 policy is planned before anything is written: its parameters are +looked up in the running catalog, its policy's among policy parameters and +its model assumptions among dynamic parameters, and the parameters the +catalog lacks are listed. A whole API v1 policy is then copied into API v2 by +API v1's policy copy (``mirror_legacy_policy_in_session``), which splits its +model assumptions into a dynamic and maps the API v1 ID to the pair. What the +second mode keeps of a policy with missing parameters is stored on its own, +without an API v1 ID mapping, since it isn't a copy of the API v1 policy +(A1 · 6). An API v1 household is copied by +``mirror_legacy_household_in_session``. Each step works in the caller's +session, and a step that can't copy raises SavedRecordMigrationRefusal with +its reason. """ from __future__ import annotations @@ -107,7 +108,7 @@ def _not_copyable( ) -> SavedRecordMigrationRefusal: return SavedRecordMigrationRefusal( FailureReason.POLICY_NOT_COPYABLE, - f"v1 policy {snapshot.legacy_policy_id} can't be copied: {error}", + f"API v1 policy {snapshot.legacy_policy_id} can't be copied: {error}", ) @@ -118,9 +119,9 @@ def plan_policy_in_session( drop_missing_parameters: bool, running_policyengine_version: str, ) -> PolicyMigrationPlan: - """Work out how the v1 policy migrates, writing nothing. + """Work out how the API v1 policy migrates, writing nothing. - A whole v1 policy without a copy is translated, so an error the copy + A whole API v1 policy without a copy is translated, so an error the copy would raise is found before anything is written. In the second mode, what is kept of a policy with missing parameters is translated too. """ @@ -208,9 +209,9 @@ def store_policy_in_session( ) -> StoredPolicy: """Store the planned policy and dynamic, or find the ones already stored. - A whole v1 policy is copied and mapped to its v1 ID by the v1-to-v2 copy, - which returns an existing copy. What the second mode keeps is stored on - its own, with no v1 ID mapping. + A whole API v1 policy is copied into API v2 and mapped to its API v1 ID by + API v1's policy copy, which returns an existing copy. What the second mode + keeps is stored on its own, with no API v1 ID mapping. """ from policyengine_api.services.v2.dynamics.services import ( create_resolved_dynamic, @@ -253,10 +254,10 @@ def report_side_in_session( apply: bool, running_policyengine_version: str, ) -> PolicySide: - """Return the report side a v1 policy is: its policy and dynamic, either maybe none. + """Return the report side an API v1 policy becomes: its policy and dynamic. A side whose policy keeps no value names no policy, and one with no model - assumptions no dynamic, so v1's current law names neither (C1 · 35, 9a). + assumptions no dynamic, so API v1's current law names neither (C1 · 35, 9a). A dry run names the existing copy, or none for one a run would make. """ if not plan.sets_policy_values and not plan.sets_dynamic_values: @@ -278,7 +279,7 @@ def report_side_in_session( def household_copy_in_session( session: Session, snapshot: LegacyHouseholdSnapshot, *, apply: bool ) -> tuple[UUID | None, int | None]: - """Return the v1 household's copy and the year it calculates. + """Return the API v1 household's copy and the year it calculates. A run finds or makes the copy. A dry run translates the household, to find the error a copy would raise, and names an existing copy or none. @@ -296,7 +297,9 @@ def household_copy_in_session( ) translated = normalize_creation_input(translate_legacy_household(snapshot)) except HOUSEHOLD_COPY_ERRORS as error: - msg = f"v1 household {snapshot.legacy_household_id} can't be copied: {error}" + msg = ( + f"API v1 household {snapshot.legacy_household_id} can't be copied: {error}" + ) raise SavedRecordMigrationRefusal( FailureReason.HOUSEHOLD_NOT_COPYABLE, msg ) from error diff --git a/policyengine_api/services/v2/saved_record_migration/database_connectors/reads.py b/policyengine_api/services/v2/saved_record_migration/database_connectors/reads.py index 84dafb454..9b7e472d9 100644 --- a/policyengine_api/services/v2/saved_record_migration/database_connectors/reads.py +++ b/policyengine_api/services/v2/saved_record_migration/database_connectors/reads.py @@ -1,7 +1,7 @@ -"""Reads of saved records holding only a v1 reference, for the migration. +"""Reads of saved records holding only an API v1 reference, for the migration. -Each read selects one kind's rows that hold a v1 reference and no -detailed-save reference, in the given countries and, optionally, of the +Each read selects one kind's rows that hold an API v1 reference and no +API v2 reference, in the given countries and, optionally, of the given owners, oldest first, up to ``limit`` rows (all without one). """ @@ -56,7 +56,7 @@ def read_saved_reforms_holding_only_v1_policies( user_ids: Sequence[UUID] | None, limit: int | None, ) -> list[UserPolicy]: - """Return saved reforms with a v1 policy and no detailed-save policy.""" + """Return saved reforms with an API v1 policy and no API v2 policy.""" statement = select(UserPolicy).where( col(UserPolicy.policy_id).is_(None), col(UserPolicy.legacy_policy_id).is_not(None), @@ -81,7 +81,7 @@ def read_saved_reports_holding_only_v1_reports( user_ids: Sequence[UUID] | None, limit: int | None, ) -> list[UserReportAssociation]: - """Return saved reports with a v1 report output and no detailed-save report.""" + """Return saved reports with an API v1 report output and no API v2 report.""" statement = select(UserReportAssociation).where( col(UserReportAssociation.report_id).is_(None), col(UserReportAssociation.legacy_report_id).is_not(None), @@ -106,7 +106,7 @@ def read_saved_households_holding_only_v1_households( user_ids: Sequence[UUID] | None, limit: int | None, ) -> list[UserHouseholdAssociation]: - """Return saved households with a v1 household and no detailed-save household.""" + """Return saved households with an API v1 household and no API v2 household.""" statement = select(UserHouseholdAssociation).where( col(UserHouseholdAssociation.household_id).is_(None), col(UserHouseholdAssociation.legacy_household_id).is_not(None), @@ -131,7 +131,7 @@ def read_saved_simulations_holding_only_v1_simulations( user_ids: Sequence[UUID] | None, limit: int | None, ) -> list[UserSimulationAssociation]: - """Return saved simulations with a v1 simulation and no detailed-save one.""" + """Return saved simulations with an API v1 simulation and no API v2 simulation.""" statement = select(UserSimulationAssociation).where( col(UserSimulationAssociation.simulation_id).is_(None), col(UserSimulationAssociation.legacy_simulation_id).is_not(None), @@ -165,7 +165,7 @@ def read_migrated_economy_report_runs( ) -> list[MigratedReportRun]: """Return up to ``limit`` migrated economy reports and their newest successful runs. - A migrated saved report holds both its v1 report output and its report; + A migrated saved report holds both its API v1 report output and its report; each pair is returned once, ordered by report ID, which is random. A budget window and a household report are left out, and so is a report with no successful run. diff --git a/policyengine_api/services/v2/saved_record_migration/database_connectors/reads_v1_records.py b/policyengine_api/services/v2/saved_record_migration/database_connectors/reads_v1_records.py index c79ce5f4a..ded1cb6a5 100644 --- a/policyengine_api/services/v2/saved_record_migration/database_connectors/reads_v1_records.py +++ b/policyengine_api/services/v2/saved_record_migration/database_connectors/reads_v1_records.py @@ -1,6 +1,6 @@ -"""Reads of the v1 records saved records name, through the v1 mapped models. +"""Reads of the API v1 records saved records name, through the API v1 mapped models. -The migration only reads v1's database. Each read returns detached values, +The migration only reads API v1's database. Each read returns detached values, so nothing it returns needs its session afterwards. """ @@ -35,7 +35,7 @@ def read_v1_policy_snapshot( session: Session, *, country_id: str, policy_id: int ) -> LegacyPolicySnapshot | None: - """Return a detached copy of the v1 policy, or None when it doesn't exist. + """Return a detached copy of the API v1 policy, or None when it doesn't exist. Raise pydantic's ValidationError when the stored row can't be a snapshot, such as a policy JSON that isn't an object. @@ -60,7 +60,7 @@ def read_v1_policy_snapshot( def read_v1_household_snapshot( session: Session, *, country_id: str, household_id: int ) -> LegacyHouseholdSnapshot | None: - """Return a detached copy of the v1 household, or None when it doesn't exist. + """Return a detached copy of the API v1 household, or None when it doesn't exist. Raise pydantic's ValidationError when the stored row can't be a snapshot. """ @@ -86,7 +86,7 @@ def read_v1_household_snapshot( def read_v1_report( session: Session, *, country_id: str, report_id: int ) -> V1ReportRecord | None: - """Return the v1 report output's defining fields, or None when it doesn't exist.""" + """Return the API v1 report output's defining fields, or None without one.""" row = session.execute( select( ReportOutput.country_id, @@ -110,7 +110,7 @@ def read_v1_report( def read_v1_simulations( session: Session, *, country_id: str, simulation_ids: Collection[int] ) -> dict[int, V1SimulationRecord]: - """Return the country's v1 simulations among ``simulation_ids``, by ID.""" + """Return the country's API v1 simulations among ``simulation_ids``, by ID.""" rows = session.execute( select( Simulation.id, @@ -138,9 +138,9 @@ def read_v1_simulations( def read_v1_report_result( session: Session, *, country_id: str, report_id: int ) -> V1ReportResult | None: - """Return the v1 report output's stored result, or None when it doesn't exist. + """Return the API v1 report output's stored result, or None when it doesn't exist. - The package version is its latest successful run's, when v1 recorded one. + The package version is its latest successful run's, when API v1 recorded one. """ row = session.execute( select(ReportOutput.output, ReportOutput.latest_successful_run_id).where( diff --git a/policyengine_api/services/v2/saved_record_migration/database_connectors/updates.py b/policyengine_api/services/v2/saved_record_migration/database_connectors/updates.py index cdca75834..68bad5f3f 100644 --- a/policyengine_api/services/v2/saved_record_migration/database_connectors/updates.py +++ b/policyengine_api/services/v2/saved_record_migration/database_connectors/updates.py @@ -1,7 +1,7 @@ -"""Updates that give saved records their detailed-save reference. +"""Updates that give saved records their API v2 reference. -Each sets the reference only on a row that still holds its v1 reference and -no detailed-save reference, and keeps the v1 reference: a row holding both +Each sets the reference only on a row that still holds its API v1 reference and +no API v2 reference, and keeps the API v1 reference: a row holding both is the record that it was migrated. Each returns whether it changed the row; a row a user deleted or repointed meanwhile is left as it is. """ @@ -64,7 +64,7 @@ def set_saved_report_report( def set_saved_household_household( session: Session, *, row_id: UUID, legacy_household_id: int, household_id: UUID ) -> bool: - """Point a saved household holding only its v1 household at ``household_id``.""" + """Point a saved household holding only its API v1 household at ``household_id``.""" changed = session.execute( update(UserHouseholdAssociation) .where( diff --git a/policyengine_api/services/v2/saved_record_migration/database_session.py b/policyengine_api/services/v2/saved_record_migration/database_session.py index a058ddfb9..29ddd7162 100644 --- a/policyengine_api/services/v2/saved_record_migration/database_session.py +++ b/policyengine_api/services/v2/saved_record_migration/database_session.py @@ -1,7 +1,7 @@ """Database session lifetimes of the one-time saved-record migration. -The detailed-save database is written in one short transaction per saved -record, and read in transactions that commit nothing. v1's database is only +The API v2 database is written in one short transaction per saved +record, and read in transactions that commit nothing. API v1's database is only read, in transactions that are always rolled back. """ @@ -19,7 +19,7 @@ class SavedRecordMigrationDatabaseSession: - """Open the detailed-save database's reads and transactions for the migration.""" + """Open the API v2 database's reads and transactions for the migration.""" def __init__(self, session_factory: sessionmaker[Session]) -> None: """Use ``session_factory``, the runtime role's, to open every session.""" @@ -43,15 +43,15 @@ def transaction(self) -> Iterator[Session]: class V1RecordDatabaseSession: - """Open v1 transactions that are always rolled back and closed.""" + """Open API v1 transactions that are always rolled back and closed.""" def __init__(self, session_factory: sessionmaker[OrmSession]) -> None: - """Use ``session_factory``, the v1 database's, to open every session.""" + """Use ``session_factory``, the API v1 database's, to open every session.""" self._session_factory = session_factory @contextmanager def read(self) -> Iterator[OrmSession]: - """Yield a v1 session whose transaction is rolled back on exit.""" + """Yield an API v1 session whose transaction is rolled back on exit.""" with self._session_factory() as session: transaction = session.begin() try: diff --git a/policyengine_api/services/v2/saved_record_migration/services.py b/policyengine_api/services/v2/saved_record_migration/services.py index 33759421a..1c15701c7 100644 --- a/policyengine_api/services/v2/saved_record_migration/services.py +++ b/policyengine_api/services/v2/saved_record_migration/services.py @@ -1,33 +1,34 @@ -"""The one-time migration of saved records' v1 references (D4 · 1). +"""The one-time migration of saved records' API v1 references (D4 · 1). A run reads the saved reforms, saved households, saved reports and saved -simulations that hold a v1 reference and no detailed-save reference, oldest -first, and gives each of the first three its detailed-save record: - -- a saved reform its v1 policy's copy, found or made by the v1-to-v2 copy - (``mirror_legacy_policy_in_session``), which splits the policy's model - assumptions into a dynamic; a v1 policy with assumptions also gives the - owner a saved dynamic with the saved reform's name and description; -- a saved household its v1 household's copy +simulations that hold an API v1 reference and no API v2 reference, oldest +first, and gives each of the first three its API v2 record: + +- a saved reform its API v1 policy's copy in API v2, found or made by API + v1's policy copy (``mirror_legacy_policy_in_session``), which splits the + policy's model assumptions into a dynamic; an API v1 policy with + assumptions also gives the owner a saved dynamic with the saved reform's + name and description; +- a saved household its API v1 household's copy (``mirror_legacy_household_in_session``); - a saved report the report the simulation service finds or creates by key - for the v1 report's definition, each side's v1 policy copied and split as - above. A side left with no policy values names no policy (C1 · 35, 9a), so - identical v1 reports end on one report. + for the API v1 report's definition, each side's API v1 policy copied and + split as above. A side left with no policy values names no policy + (C1 · 35, 9a), so identical API v1 reports end on one report. Saved simulations are only listed. A row whose policies set a parameter the -running catalog lacks is left on its v1 reference and listed (A1 · 6), +running catalog lacks is left on its API v1 reference and listed (A1 · 6), unless the run drops missing parameters (the second mode, for E1 · 4): then -it migrates from the parameters that still exist, stored without a v1 ID +it migrates from the parameters that still exist, stored without an API v1 ID mapping, and a row whose every parameter is missing is still left. A row -keeps its v1 reference too; a row holding both is the record that it was +keeps its API v1 reference too; a row holding both is the record that it was migrated. A dry run reads both databases, writes nothing and calls no other service. Each saved record is written in its own transaction, and a saved report's copies commit before the simulation service is asked for the report, since it reads them itself. A row the run can't migrate fails alone, with a -reason, and keeps its v1 reference. Running again picks up what is left. +reason, and keeps its API v1 reference. Running again picks up what is left. """ from __future__ import annotations @@ -61,14 +62,14 @@ set_saved_report_report, ) from policyengine_api.services.v2.saved_record_migration.transformations import ( + api_v1_budgetary_impact, + api_v2_report_definition, closing_check, - detailed_save_report_definition, pending_saved_household, pending_saved_reform, pending_saved_report, pending_saved_simulation, relative_difference, - v1_budgetary_impact, ) from policyengine_api.services.v2.saved_record_migration.types import ( FailureReason, @@ -114,7 +115,7 @@ V1RecordDatabaseSession, ) from policyengine_api.services.v2.saved_record_migration.types import ( - DetailedSaveReportDefinition, + ApiV2ReportDefinition, MigratedReportRun, MigrationOptions, PendingSavedRecord, @@ -135,7 +136,7 @@ def _result( # noqa: PLR0913 # the record and outcome, then each optional fiel record: PendingSavedRecord, outcome: RowOutcome, *, - detailed_save_id: UUID | None = None, + api_v2_id: UUID | None = None, saved_dynamic_id: UUID | None = None, missing_parameters: tuple[str, ...] = (), dropped_parameters: tuple[str, ...] = (), @@ -149,7 +150,7 @@ def _result( # noqa: PLR0913 # the record and outcome, then each optional fiel country_id=record.country_id, legacy_id=record.legacy_id, outcome=outcome, - detailed_save_id=detailed_save_id, + api_v2_id=api_v2_id, saved_dynamic_id=saved_dynamic_id, missing_parameters=missing_parameters, dropped_parameters=dropped_parameters, @@ -188,7 +189,7 @@ def _left_for_missing_parameters( class V2SavedRecordMigrationService: - """Migrate saved records' v1 references, one saved record at a time.""" + """Migrate saved records' API v1 references, one saved record at a time.""" def __init__( self, @@ -201,7 +202,7 @@ def __init__( load_region_references ), ) -> None: - """Read and write through ``database`` and read v1 through ``v1_database``. + """Read and write through ``database`` and read API v1 through ``v1_database``. ``report_submitter`` asks the simulation service for reports; a dry run doesn't need one. Copies bind to the catalog of @@ -240,9 +241,9 @@ def compare_sample( country_ids: tuple[str, ...], user_ids: tuple[UUID, ...] | None = None, ) -> SampleComparison: - """Put up to ``size`` migrated reports' run results next to v1's. + """Put up to ``size`` migrated reports' run results next to API v1's. - Each is a migrated economy report with a successful run: v1's + Each is a migrated economy report with a successful run: API v1's stored budgetary impact and the run's, with their package versions. It writes nothing and starts no run. ``user_ids`` keeps it to those owners' saved reports. @@ -262,7 +263,7 @@ def compare_sample( session, country_id=run.country_id, report_id=run.legacy_report_id ) v1_value = ( - None if v1_result is None else v1_budgetary_impact(v1_result.output) + None if v1_result is None else api_v1_budgetary_impact(v1_result.output) ) run_value, run_note = run_results[run.report_run_id] comparisons.append( @@ -271,17 +272,17 @@ def compare_sample( legacy_report_id=run.legacy_report_id, report_id=run.report_id, report_run_id=run.report_run_id, - v1_budgetary_impact=v1_value, - v1_country_package_version=( + api_v1_budgetary_impact=v1_value, + api_v1_country_package_version=( None if v1_result is None else v1_result.country_package_version ), - detailed_save_budgetary_impact=run_value, - detailed_save_country_package_version=run.country_package_version, + api_v2_budgetary_impact=run_value, + api_v2_country_package_version=run.country_package_version, relative_difference=relative_difference(v1_value, run_value), note=( run_note if run_note is not None or v1_value is not None - else "v1 stored no budgetary impact for this report" + else "API v1 stored no budgetary impact for this report" ), ) ) @@ -308,7 +309,7 @@ def _run_budgetary_impact( def _pending( self, options: MigrationOptions, *, limit: int | None ) -> list[PendingSavedRecord]: - """Return the rows holding only a v1 reference. + """Return the rows holding only an API v1 reference. Saved reforms come first, then households and reports, which reuse the copies they made, then simulations. @@ -402,7 +403,7 @@ def _migrate_saved_reform( return _result( record, RowOutcome.MIGRATED, - detailed_save_id=plan.existing_policy_id, + api_v2_id=plan.existing_policy_id, dropped_parameters=plan.missing_parameters, ) stored = store_policy_in_session( @@ -416,7 +417,7 @@ def _migrate_saved_reform( legacy_policy_id=record.legacy_id, policy_id=stored.policy_id, ): - msg = "the saved reform no longer holds only its v1 policy" + msg = "the saved reform no longer holds only its API v1 policy" raise _refusal(FailureReason.ROW_CHANGED, msg) saved_dynamic_id = ( None @@ -437,7 +438,7 @@ def _migrate_saved_reform( return _result( record, RowOutcome.MIGRATED, - detailed_save_id=stored.policy_id, + api_v2_id=stored.policy_id, saved_dynamic_id=saved_dynamic_id, dropped_parameters=plan.missing_parameters, ) @@ -451,10 +452,10 @@ def _v1_policy(self, country_id: str, policy_id: int) -> LegacyPolicySnapshot: session, country_id=country_id, policy_id=policy_id ) except ValidationError as error: - msg = f"v1 policy {policy_id} can't be read: {error}" + msg = f"API v1 policy {policy_id} can't be read: {error}" raise _refusal(FailureReason.POLICY_NOT_COPYABLE, msg) from error if snapshot is None: - msg = f"v1 policy {policy_id} doesn't exist" + msg = f"API v1 policy {policy_id} doesn't exist" raise _refusal(FailureReason.V1_RECORD_NOT_FOUND, msg) return snapshot @@ -469,10 +470,10 @@ def _v1_household( session, country_id=country_id, household_id=household_id ) except ValidationError as error: - msg = f"v1 household {household_id} can't be read: {error}" + msg = f"API v1 household {household_id} can't be read: {error}" raise _refusal(FailureReason.HOUSEHOLD_NOT_COPYABLE, msg) from error if snapshot is None: - msg = f"v1 household {household_id} doesn't exist" + msg = f"API v1 household {household_id} doesn't exist" raise _refusal(FailureReason.V1_RECORD_NOT_FOUND, msg) return snapshot @@ -497,9 +498,9 @@ def _migrate_saved_household( household_id=household_id, ) ): - msg = "the saved household no longer holds only its v1 household" + msg = "the saved household no longer holds only its API v1 household" raise _refusal(FailureReason.ROW_CHANGED, msg) - return _result(record, RowOutcome.MIGRATED, detailed_save_id=household_id) + return _result(record, RowOutcome.MIGRATED, api_v2_id=household_id) # Saved reports. @@ -510,13 +511,13 @@ def _v1_report( dict[int, LegacyPolicySnapshot], LegacyHouseholdSnapshot | None, ]: - """Read the v1 report's definition, its policies and its household.""" + """Read the API v1 report's definition, its policies and its household.""" with self._v1_database.read() as session: report = read_v1_report( session, country_id=record.country_id, report_id=record.legacy_id ) if report is None: - msg = f"v1 report {record.legacy_id} doesn't exist" + msg = f"API v1 report {record.legacy_id} doesn't exist" raise _refusal(FailureReason.V1_RECORD_NOT_FOUND, msg) simulation_ids = {report.simulation_1_id} if report.simulation_2_id is not None: @@ -526,7 +527,7 @@ def _v1_report( ) baseline = simulations.get(report.simulation_1_id) if baseline is None: - msg = f"v1 report {record.legacy_id}'s first simulation doesn't exist" + msg = f"API v1 report {record.legacy_id}'s first simulation doesn't exist" raise _refusal(FailureReason.V1_REPORT_UNREADABLE, msg) reform = ( None @@ -548,7 +549,7 @@ def _v1_report( ) return definition, snapshots, household - def _report_id(self, definition: DetailedSaveReportDefinition) -> UUID: + def _report_id(self, definition: ApiV2ReportDefinition) -> UUID: """Ask the simulation service to find or create the report.""" if self._report_submitter is None: msg = "migrating saved reports needs the simulation service" @@ -577,7 +578,7 @@ def _point_saved_report(self, record: PendingSavedRecord, report_id: UUID) -> No legacy_report_id=record.legacy_id, report_id=report_id, ): - msg = "the saved report no longer holds only its v1 report" + msg = "the saved report no longer holds only its API v1 report" raise _refusal(FailureReason.ROW_CHANGED, msg) def _migrate_saved_report( @@ -602,13 +603,13 @@ def _migrate_saved_report( ) earlier = reports_this_run.get(report_key) if earlier is not None: - # Another saved report of the same v1 report, migrated by this run. - if options.apply and earlier.detailed_save_id is not None: - self._point_saved_report(record, earlier.detailed_save_id) + # Another saved report of the same API v1 report, migrated by this run. + if options.apply and earlier.api_v2_id is not None: + self._point_saved_report(record, earlier.api_v2_id) return _result( record, RowOutcome.MIGRATED, - detailed_save_id=earlier.detailed_save_id, + api_v2_id=earlier.api_v2_id, dropped_parameters=earlier.dropped_parameters, notes=earlier.notes, ) @@ -671,7 +672,7 @@ def _migrate_saved_report( notes = ( ( f"the report calculates its household's year, {household_year}, " - f"not the v1 report's {definition.year}", + f"not the API v1 report's {definition.year}", ) if household is not None and household_year != definition.year else () @@ -679,7 +680,7 @@ def _migrate_saved_report( report_id = None if options.apply: report_id = self._report_id( - detailed_save_report_definition( + api_v2_report_definition( definition, baseline=sides[definition.baseline_policy_id], reform=( @@ -696,7 +697,7 @@ def _migrate_saved_report( result = _result( record, RowOutcome.MIGRATED, - detailed_save_id=report_id, + api_v2_id=report_id, dropped_parameters=missing, notes=notes, ) diff --git a/policyengine_api/services/v2/saved_record_migration/transformations.py b/policyengine_api/services/v2/saved_record_migration/transformations.py index f8767ae91..45c9ca085 100644 --- a/policyengine_api/services/v2/saved_record_migration/transformations.py +++ b/policyengine_api/services/v2/saved_record_migration/transformations.py @@ -1,9 +1,8 @@ """Conversions the one-time saved-record migration makes (D4 · 1). -They read saved records' rows into pending records, keep a v1 policy's -parameters that the running catalog still has, build the detailed-save -report definition, and work out the closing check and the command's JSON -document. +They read saved records' rows into pending records, keep an API v1 policy's +parameters that the running catalog still has, build the API v2 report +definition, and work out the closing check and the command's JSON document. """ from __future__ import annotations @@ -13,9 +12,9 @@ from typing import TYPE_CHECKING from policyengine_api.services.v2.saved_record_migration.types import ( + ApiV2ReportDefinition, + ApiV2ReportKind, ClosingCheck, - DetailedSaveReportDefinition, - DetailedSaveReportKind, PendingSavedRecord, RemainingV1References, RowOutcome, @@ -45,7 +44,7 @@ # A saved report's window of one year is the report itself. _SHORTEST_BUDGET_WINDOW = 2 -# Outcomes that leave a row on its v1 reference, by the count they go to. +# Outcomes that leave a row on its API v1 reference, by the count they go to. _LEFT_OUTCOMES = { RowOutcome.MISSING_PARAMETERS: "missing_parameters", RowOutcome.EVERY_PARAMETER_MISSING: "every_parameter_missing", @@ -55,9 +54,9 @@ def pending_saved_reform(row: UserPolicy) -> PendingSavedRecord: - """Read a saved reform holding only its v1 policy.""" + """Read a saved reform holding only its API v1 policy.""" if row.legacy_policy_id is None: - msg = "a pending saved reform holds a v1 policy" + msg = "a pending saved reform holds an API v1 policy" raise ValueError(msg) return PendingSavedRecord( kind=SavedRecordKind.SAVED_REFORM, @@ -71,9 +70,9 @@ def pending_saved_reform(row: UserPolicy) -> PendingSavedRecord: def pending_saved_report(row: UserReportAssociation) -> PendingSavedRecord: - """Read a saved report holding only its v1 report output.""" + """Read a saved report holding only its API v1 report output.""" if row.legacy_report_id is None: - msg = "a pending saved report holds a v1 report" + msg = "a pending saved report holds an API v1 report" raise ValueError(msg) return PendingSavedRecord( kind=SavedRecordKind.SAVED_REPORT, @@ -88,9 +87,9 @@ def pending_saved_report(row: UserReportAssociation) -> PendingSavedRecord: def pending_saved_household(row: UserHouseholdAssociation) -> PendingSavedRecord: - """Read a saved household holding only its v1 household.""" + """Read a saved household holding only its API v1 household.""" if row.legacy_household_id is None: - msg = "a pending saved household holds a v1 household" + msg = "a pending saved household holds an API v1 household" raise ValueError(msg) return PendingSavedRecord( kind=SavedRecordKind.SAVED_HOUSEHOLD, @@ -104,9 +103,9 @@ def pending_saved_household(row: UserHouseholdAssociation) -> PendingSavedRecord def pending_saved_simulation(row: UserSimulationAssociation) -> PendingSavedRecord: - """Read a saved simulation holding only its v1 simulation.""" + """Read a saved simulation holding only its API v1 simulation.""" if row.legacy_simulation_id is None: - msg = "a pending saved simulation holds a v1 simulation" + msg = "a pending saved simulation holds an API v1 simulation" raise ValueError(msg) return PendingSavedRecord( kind=SavedRecordKind.SAVED_SIMULATION, @@ -125,7 +124,7 @@ def kept_policy_snapshot( *, missing: Collection[str], ) -> LegacyPolicySnapshot: - """Return the v1 policy without the parameters the running catalog lacks. + """Return the API v1 policy without the parameters the running catalog lacks. ``split`` is the snapshot's split, whose names are the parameters' current ones (the UK's old labour-supply spelling rewritten), and @@ -140,7 +139,7 @@ def kept_policy_snapshot( return snapshot.model_copy(update={"policy_json": kept}) -def detailed_save_report_definition( # noqa: PLR0913 # the v1 definition, then each part the copies give +def api_v2_report_definition( # noqa: PLR0913 # the API v1 definition, then each part the copies give definition: V1ReportDefinition, *, baseline: PolicySide, @@ -148,7 +147,7 @@ def detailed_save_report_definition( # noqa: PLR0913 # the v1 definition, then region_code: str | None, household_id: UUID | None, budget_window_years: int | None, -) -> DetailedSaveReportDefinition: +) -> ApiV2ReportDefinition: """Return the report the simulation service is asked to find or create. A household report names its household and calculates the household's @@ -156,9 +155,9 @@ def detailed_save_report_definition( # noqa: PLR0913 # the v1 definition, then window when the saved report kept a window of two or more years. """ if definition.kind is V1ReportKind.HOUSEHOLD: - return DetailedSaveReportDefinition( + return ApiV2ReportDefinition( country_id=definition.country_id, - kind=DetailedSaveReportKind.HOUSEHOLD, + kind=ApiV2ReportKind.HOUSEHOLD, baseline=baseline, reform=reform, year=None, @@ -170,13 +169,9 @@ def detailed_save_report_definition( # noqa: PLR0913 # the v1 definition, then budget_window_years is not None and budget_window_years >= _SHORTEST_BUDGET_WINDOW ) - return DetailedSaveReportDefinition( + return ApiV2ReportDefinition( country_id=definition.country_id, - kind=( - DetailedSaveReportKind.BUDGET_WINDOW - if is_window - else DetailedSaveReportKind.ECONOMY - ), + kind=(ApiV2ReportKind.BUDGET_WINDOW if is_window else ApiV2ReportKind.ECONOMY), baseline=baseline, reform=reform, year=definition.year, @@ -190,9 +185,9 @@ def closing_check( remaining: Mapping[SavedRecordKind, Collection[UUID]], results: Sequence[SavedRecordResult], ) -> ClosingCheck: - """Count the rows still holding only a v1 reference by what the run did. + """Count the rows still holding only an API v1 reference by what the run did. - ``remaining`` holds, for each kind, the rows holding only a v1 reference + ``remaining`` holds, for each kind, the rows holding only an API v1 reference when the run ended. A row the run migrated, or in a dry run would migrate, isn't counted. Any other row is counted by its outcome, and one the run has no result for as not attempted. The check passes when @@ -234,7 +229,7 @@ def _result_document(result: SavedRecordResult) -> dict[str, object]: "country_id": result.country_id, "legacy_id": result.legacy_id, "outcome": result.outcome.value, - "detailed_save_id": _optional_text(result.detailed_save_id), + "api_v2_id": _optional_text(result.api_v2_id), "saved_dynamic_id": _optional_text(result.saved_dynamic_id), "missing_parameters": list(result.missing_parameters), "dropped_parameters": list(result.dropped_parameters), @@ -250,7 +245,7 @@ def migration_document(run: MigrationRun) -> dict[str, object]: """Return the run as the JSON document the command prints. It holds the options, counts of each kind's rows by outcome, every row's - result (a rollback clears the detailed-save reference of the rows it + result (a rollback clears the API v2 reference of the rows it lists as migrated), and the closing check. """ counts: dict[str, dict[str, int]] = {kind.value: {} for kind in SavedRecordKind} @@ -286,10 +281,10 @@ def migration_document(run: MigrationRun) -> dict[str, object]: } -def v1_budgetary_impact(output: object) -> float | None: - """Return the budgetary impact a v1 economy report output stored, if any. +def api_v1_budgetary_impact(output: object) -> float | None: + """Return the budgetary impact an API v1 economy report output stored, if any. - v1 stored the result as JSON, in some older rows as a JSON string; a + API v1 stored the result as JSON, in some older rows as a JSON string; a budget-window or household output, or none, has no single figure. """ if isinstance(output, str): @@ -307,15 +302,15 @@ def v1_budgetary_impact(output: object) -> float | None: def relative_difference( - v1_value: float | None, detailed_save_value: float | None + v1_value: float | None, api_v2_value: float | None ) -> float | None: - """Return the detailed-save value's difference from v1's, as a fraction of v1's. + """Return the API v2 value's difference from API v1's, as a fraction of API v1's. - None without both values, or when v1's is zero. + None without both values, or when API v1's is zero. """ - if v1_value is None or detailed_save_value is None or v1_value == 0: + if v1_value is None or api_v2_value is None or v1_value == 0: return None - return (detailed_save_value - v1_value) / abs(v1_value) + return (api_v2_value - v1_value) / abs(v1_value) def sample_comparison_document(comparison: SampleComparison) -> dict[str, object]: @@ -330,12 +325,10 @@ def sample_comparison_document(comparison: SampleComparison) -> dict[str, object "legacy_report_id": item.legacy_report_id, "report_id": str(item.report_id), "report_run_id": str(item.report_run_id), - "v1_budgetary_impact": item.v1_budgetary_impact, - "v1_country_package_version": item.v1_country_package_version, - "detailed_save_budgetary_impact": (item.detailed_save_budgetary_impact), - "detailed_save_country_package_version": ( - item.detailed_save_country_package_version - ), + "api_v1_budgetary_impact": item.api_v1_budgetary_impact, + "api_v1_country_package_version": item.api_v1_country_package_version, + "api_v2_budgetary_impact": (item.api_v2_budgetary_impact), + "api_v2_country_package_version": (item.api_v2_country_package_version), "relative_difference": item.relative_difference, "note": item.note, } diff --git a/policyengine_api/services/v2/saved_record_migration/types.py b/policyengine_api/services/v2/saved_record_migration/types.py index 26783b7a0..8d0ce7af6 100644 --- a/policyengine_api/services/v2/saved_record_migration/types.py +++ b/policyengine_api/services/v2/saved_record_migration/types.py @@ -1,8 +1,8 @@ -"""Types of the one-time migration of saved records' v1 references (D4 · 1). +"""Types of the one-time migration of saved records' API v1 references (D4 · 1). Saved reforms, saved reports and saved households that hold only a v1 -reference are given the detailed-save record that reference stands for; -saved simulations holding only a v1 reference are listed. Each row's outcome +reference are given the API v2 record that reference stands for; +saved simulations holding only an API v1 reference are listed. Each row's outcome is a ``SavedRecordResult``, and a run's is a ``MigrationRun`` with its closing check. """ @@ -34,7 +34,7 @@ class SavedRecordKind(StrEnum): class RowOutcome(StrEnum): """What a run did with one saved record, or, in a dry run, would do. - ``missing_parameters``: left on its v1 reference because a policy it + ``missing_parameters``: left on its API v1 reference because a policy it names sets a parameter the running catalog lacks (A1 · 6), and listed. ``every_parameter_missing``: in the second mode, left and listed because dropping those parameters leaves nothing the user set (decision (a)). @@ -49,7 +49,7 @@ class RowOutcome(StrEnum): class FailureReason(StrEnum): - """Why a saved record could not be migrated; it keeps its v1 reference.""" + """Why a saved record could not be migrated; it keeps its API v1 reference.""" V1_RECORD_NOT_FOUND = "v1_record_not_found" V1_REPORT_UNREADABLE = "v1_report_unreadable" @@ -63,13 +63,13 @@ class FailureReason(StrEnum): class V1ReportKind(StrEnum): - """Whether a v1 report simulates a region's population or one household.""" + """Whether an API v1 report simulates a region's population or one household.""" ECONOMY = "economy" HOUSEHOLD = "household" -class DetailedSaveReportKind(StrEnum): +class ApiV2ReportKind(StrEnum): """The kind of report the simulation service is asked to find or create.""" ECONOMY = "economy" @@ -98,7 +98,7 @@ class MigrationOptions: @dataclass(frozen=True) class PendingSavedRecord: - """A saved record that holds only its v1 reference, as a run reads it.""" + """A saved record that holds only its API v1 reference, as a run reads it.""" kind: SavedRecordKind row_id: UUID @@ -112,7 +112,7 @@ class PendingSavedRecord: @dataclass(frozen=True) class V1ReportRecord: - """The fields of a v1 report output that define the report.""" + """The fields of an API v1 report output that define the report.""" country_id: str report_id: int @@ -123,7 +123,7 @@ class V1ReportRecord: @dataclass(frozen=True) class V1SimulationRecord: - """The fields of a v1 simulation that define one side of a report.""" + """The fields of an API v1 simulation that define one side of a report.""" simulation_id: int country_id: str @@ -134,12 +134,12 @@ class V1SimulationRecord: @dataclass(frozen=True) class V1ReportDefinition: - """A v1 report as v1's report spec reads it (``ReportSpecService``). + """An API v1 report as API v1's report spec reads it (``ReportSpecService``). Simulation 1 is the baseline and simulation 2 the reform. A report of one economy simulation names that simulation's policy on both sides; a report of one household simulation has no reform. ``region`` is an economy - report's v1 region, and ``legacy_household_id`` a household report's v1 + report's API v1 region, and ``legacy_household_id`` a household report's v1 household. """ @@ -155,10 +155,10 @@ class V1ReportDefinition: @dataclass(frozen=True) class PolicySide: - """One side of a detailed-save report: its policy and dynamic, or neither. + """One side of an API v2 report: its policy and dynamic, or neither. Neither means current law and no model assumptions beyond the model's - defaults; a side whose v1 policy sets only model assumptions names its + defaults; a side whose API v1 policy sets only model assumptions names its dynamic and no policy (C1 · 35, 9a). """ @@ -168,16 +168,16 @@ class PolicySide: @dataclass(frozen=True) class PolicyMigrationPlan: - """How one v1 policy migrates, worked out before anything is written. + """How one API v1 policy migrates, worked out before anything is written. ``missing_parameters`` are the parameters it sets that the running catalog lacks, by their current names. ``sets_policy_values`` and ``sets_dynamic_values`` say whether the policy and its model assumptions keep any value, without the missing parameters in the second mode. ``kept_translation`` is, in the second mode, the translation of what is - kept, stored without a v1 ID mapping; it is None when the whole v1 policy + kept, stored without an API v1 ID mapping; it is None when the whole API v1 policy is copied. ``existing_policy_id`` and ``existing_dynamic_id`` name the - copy the v1 policy already maps to, if any. + copy the API v1 policy already maps to, if any. """ snapshot: LegacyPolicySnapshot @@ -198,25 +198,25 @@ def every_parameter_missing(self) -> bool: @dataclass(frozen=True) class StoredPolicy: - """The policy, and the dynamic if any, a v1 policy's values are stored as.""" + """The policy, and the dynamic if any, an API v1 policy's values are stored as.""" policy_id: UUID dynamic_id: UUID | None @dataclass(frozen=True) -class DetailedSaveReportDefinition: +class ApiV2ReportDefinition: """The report the simulation service is asked to find or create by key. An economy or budget-window report names its year and catalog region code, and a budget window its size; a household report names its household and calculates the household's own year, so it names neither. No definition names a dataset or a data source: the region's own dataset - is used, as for the v1 report. + is used, as for the API v1 report. """ country_id: str - kind: DetailedSaveReportKind + kind: ApiV2ReportKind baseline: PolicySide reform: PolicySide | None year: int | None @@ -228,7 +228,7 @@ class DetailedSaveReportDefinition: class ReportSubmitter(Protocol): """Finds or creates a report through the simulation service.""" - def find_or_create_report(self, definition: DetailedSaveReportDefinition) -> UUID: + def find_or_create_report(self, definition: ApiV2ReportDefinition) -> UUID: """Return the ID of the report the simulation service found or created. Raise ReportSubmissionRefusedError when the service refuses the @@ -241,7 +241,7 @@ def find_or_create_report(self, definition: DetailedSaveReportDefinition) -> UUI class SavedRecordResult: """What a run did with one saved record. - ``detailed_save_id`` is the policy, report or household ID the row now + ``api_v2_id`` is the policy, report or household ID the row now holds; in a dry run, the existing copy it would hold, or None when the run would make a new one. ``missing_parameters`` lists the parameters the running catalog lacks of a row left for them, and ``dropped_parameters`` @@ -254,7 +254,7 @@ class SavedRecordResult: country_id: str legacy_id: int outcome: RowOutcome - detailed_save_id: UUID | None = None + api_v2_id: UUID | None = None saved_dynamic_id: UUID | None = None missing_parameters: tuple[str, ...] = () dropped_parameters: tuple[str, ...] = () @@ -265,7 +265,7 @@ class SavedRecordResult: @dataclass(frozen=True) class RemainingV1References: - """The rows of one kind that still hold only a v1 reference after a run. + """The rows of one kind that still hold only an API v1 reference after a run. Each is counted once, by what the run did with it: left for missing parameters, left because every parameter is missing, failed, not reached @@ -283,7 +283,7 @@ class RemainingV1References: @dataclass(frozen=True) class ClosingCheck: - """The rows left holding only a v1 reference, by kind, and the verdict. + """The rows left holding only an API v1 reference, by kind, and the verdict. It passes when nothing failed and every row left is one the decisions leave: rows with missing parameters, and saved simulations. @@ -307,7 +307,7 @@ class MigrationRun: class MigratedReportRun: """A migrated economy report's newest successful run. - ``legacy_report_id`` is the v1 report output a saved report migrated + ``legacy_report_id`` is the API v1 report output a saved report migrated from, and ``report_id`` the report it now names. """ @@ -320,10 +320,10 @@ class MigratedReportRun: @dataclass(frozen=True) class V1ReportResult: - """A v1 report output's stored result and the package version it ran on. + """An API v1 report output's stored result and the package version it ran on. - ``output`` is the stored JSON as v1 kept it; ``country_package_version`` - is its latest successful run's, or None when v1 recorded none. + ``output`` is the stored JSON as API v1 kept it; ``country_package_version`` + is its latest successful run's, or None when API v1 recorded none. """ output: object @@ -332,10 +332,10 @@ class V1ReportResult: @dataclass(frozen=True) class ReportComparison: - """One migrated report's budgetary impact, as v1 stored it and as run since. + """One migrated report's budgetary impact, as API v1 stored it and as run since. - ``relative_difference`` is the run's value minus v1's, as a fraction of - v1's, or None without both values or when v1's is zero. ``note`` says why + ``relative_difference`` is the run's value minus API v1's, as a fraction of + API v1's, or None without both values or when API v1's is zero. ``note`` says why a value is missing. """ @@ -343,17 +343,17 @@ class ReportComparison: legacy_report_id: int report_id: UUID report_run_id: UUID - v1_budgetary_impact: float | None - v1_country_package_version: str | None - detailed_save_budgetary_impact: float | None - detailed_save_country_package_version: str + api_v1_budgetary_impact: float | None + api_v1_country_package_version: str | None + api_v2_budgetary_impact: float | None + api_v2_country_package_version: str relative_difference: float | None note: str | None = None @dataclass(frozen=True) class SampleComparison: - """A sample of migrated reports' results next to v1's, for a person to read.""" + """A sample of migrated reports' results next to API v1's, for a person to read.""" size: int country_ids: tuple[str, ...] diff --git a/policyengine_api/services/v2/saved_record_migration/validators.py b/policyengine_api/services/v2/saved_record_migration/validators.py index 43cc3e537..ce6270e73 100644 --- a/policyengine_api/services/v2/saved_record_migration/validators.py +++ b/policyengine_api/services/v2/saved_record_migration/validators.py @@ -1,11 +1,11 @@ """Checks the one-time migration makes on rows it has already read (D4 · 1). -A v1 report is rebuilt from its report output and simulations as v1's report +An API v1 report is rebuilt from its report output and simulations as API v1's report spec reads them (``policyengine_api.services.report_spec_service``), and a v1 region is translated through the catalog's region reference files, which -pair each catalog region with the v1 region it replaces (``v1_code``). A row +pair each catalog region with the API v1 region it replaces (``v1_code``). A row that can't be migrated raises ``SavedRecordMigrationRefusal`` with a reason, -and keeps its v1 reference. +and keeps its API v1 reference. """ from __future__ import annotations @@ -36,7 +36,7 @@ class SavedRecordMigrationRefusal(Exception): # noqa: N818 # a refusal, not a programming error - """A saved record can't be migrated, for ``reason``; it keeps its v1 reference.""" + """A saved record can't be migrated, for ``reason``; it keeps its API v1 ID.""" def __init__(self, reason: FailureReason, message: str) -> None: """Keep ``reason`` for the row's result and ``message`` as its detail.""" @@ -67,7 +67,7 @@ def _unreadable(message: str) -> SavedRecordMigrationRefusal: def _report_year(report: V1ReportRecord) -> int: year = (report.year or "").strip() if not year.isdigit(): - msg = f"v1 report {report.report_id}'s year isn't a number: {report.year!r}" + msg = f"API v1 report {report.report_id}'s year isn't a number: {report.year!r}" raise _unreadable(msg) return int(year) @@ -76,7 +76,7 @@ def _legacy_household_id(simulation: V1SimulationRecord) -> int: population = simulation.population_id.strip() if not population.isdigit(): msg = ( - f"v1 simulation {simulation.simulation_id} names household " + f"API v1 simulation {simulation.simulation_id} names household " f"{simulation.population_id!r}, not a household ID" ) raise _unreadable(msg) @@ -91,16 +91,18 @@ def _check_simulations( if baseline.simulation_id != report.simulation_1_id or ( (reform.simulation_id if reform is not None else None) != report.simulation_2_id ): - msg = f"v1 report {report.report_id}'s simulations are not the ones it names" + msg = ( + f"API v1 report {report.report_id}'s simulations are not the ones it names" + ) raise _unreadable(msg) simulations = [baseline] if reform is None else [baseline, reform] if any(simulation.country_id != report.country_id for simulation in simulations): - msg = f"v1 report {report.report_id} names a simulation of another country" + msg = f"API v1 report {report.report_id} names a simulation of another country" raise _unreadable(msg) kinds = {simulation.population_type for simulation in simulations} if len(kinds) != 1 or not kinds <= set(_POPULATION_KINDS): msg = ( - f"v1 report {report.report_id}'s simulations have population types " + f"API v1 report {report.report_id}'s simulations have population types " f"{sorted(kinds)}, not one of geography or household" ) raise _unreadable(msg) @@ -112,7 +114,7 @@ def validate_v1_report( baseline: V1SimulationRecord, reform: V1SimulationRecord | None, ) -> V1ReportDefinition: - """Return the v1 report's definition, as v1's report spec reads it. + """Return the API v1 report's definition, as API v1's report spec reads it. ``baseline`` is the report's simulation 1 and ``reform`` its simulation 2, None for a report of one simulation. Raise SavedRecordMigrationRefusal @@ -125,7 +127,7 @@ def validate_v1_report( if kind is V1ReportKind.HOUSEHOLD: household_id = _legacy_household_id(baseline) if reform is not None and _legacy_household_id(reform) != household_id: - msg = f"v1 report {report.report_id} compares two different households" + msg = f"API v1 report {report.report_id} compares two different households" raise _unreadable(msg) return V1ReportDefinition( country_id=report.country_id, @@ -138,7 +140,7 @@ def validate_v1_report( reform_policy_id=None if reform is None else reform.policy_id, ) if reform is not None and reform.population_id != baseline.population_id: - msg = f"v1 report {report.report_id} compares two different regions" + msg = f"API v1 report {report.report_id} compares two different regions" raise _unreadable(msg) return V1ReportDefinition( country_id=report.country_id, @@ -148,14 +150,14 @@ def validate_v1_report( region=baseline.population_id, legacy_household_id=None, baseline_policy_id=baseline.policy_id, - # v1 runs a report of one economy simulation with its policy on both + # API v1 runs a report of one economy simulation with its policy on both # sides (ReportSpecService.build_report_spec). reform_policy_id=(baseline if reform is None else reform).policy_id, ) def _spelled_as_v1_matches(country_id: str, v1_region: str) -> str: - """Spell a v1 region as v1 normalised it before running it. + """Spell an API v1 region as API v1 normalised it before running it. A blank region is the country. In the UK, a region without a type is a nation, lower-cased with spaces as underscores (``normalise_uk_region``); @@ -181,10 +183,10 @@ def _spelled_as_v1_matches(country_id: str, v1_region: str) -> str: def require_catalog_region_code( country_id: str, v1_region: str, references: Iterable[RegionReference] ) -> str: - """Return the catalog code of the region a v1 economy report ran on. + """Return the catalog code of the region an API v1 economy report ran on. - The v1 region matches a region's ``v1_code``, or its catalog code, ignoring - case: a UK constituency or local authority by name (its v1 code) or by + The API v1 region matches a region's ``v1_code``, or its catalog code, ignoring + case: a UK constituency or local authority by name (its API v1 code) or by ONS code (its catalog code). Raise SavedRecordMigrationRefusal (``unknown_region``) when no region of the country matches. """ @@ -195,6 +197,6 @@ def require_catalog_region_code( if reference.v1_code is not None: by_spelling.setdefault(reference.v1_code.casefold(), reference.code) if spelled not in by_spelling: - msg = f"{country_id} has no catalog region for v1 region {v1_region!r}" + msg = f"{country_id} has no catalog region for API v1 region {v1_region!r}" raise SavedRecordMigrationRefusal(FailureReason.UNKNOWN_REGION, msg) return by_spelling[spelled] diff --git a/scripts/migrate_saved_records_to_detailed_save.py b/scripts/migrate_saved_records_to_api_v2.py similarity index 88% rename from scripts/migrate_saved_records_to_detailed_save.py rename to scripts/migrate_saved_records_to_api_v2.py index b0be2749b..e91fdc0ea 100755 --- a/scripts/migrate_saved_records_to_detailed_save.py +++ b/scripts/migrate_saved_records_to_api_v2.py @@ -1,20 +1,20 @@ #!/usr/bin/env python3 -"""Give saved records that hold only a v1 reference their detailed-save records. +"""Give saved records that hold only an API v1 reference their API v2 records. The one-time migration (D4 · 1). Usage:: - migrate_saved_records_to_detailed_save.py [--dry-run] + migrate_saved_records_to_api_v2.py [--dry-run] [--drop-missing-parameters] [--country us|uk ...] [--limit N] [--user-id UUID ...] It reads every saved reform, saved household, saved report and saved -simulation that holds a v1 reference and no detailed-save reference, oldest -first, and gives each of the first three the detailed-save record that v1 -reference stands for: a saved reform its v1 policy's copy, split into a +simulation that holds an API v1 reference and no API v2 reference, oldest +first, and gives each of the first three the API v2 record that v1 +reference stands for: a saved reform its API v1 policy's copy, split into a policy and a dynamic, with a saved dynamic of the same name when the v1 -policy sets model assumptions; a saved household its v1 household's copy; a +policy sets model assumptions; a saved household its API v1 household's copy; a saved report the report the simulation service finds or creates for the v1 -report's definition. Each row keeps its v1 reference. Saved simulations are +report's definition. Each row keeps its API v1 reference. Saved simulations are only listed. Running it again picks up what is left. - ``--dry-run`` reads both databases and writes nothing; it calls no other @@ -28,8 +28,8 @@ The closing check covers the same rows. It prints one JSON document: counts of each kind's rows by outcome, every -row's result (the detailed-save ID it now holds, or why not), and the closing -check, which counts the rows still holding only a v1 reference by why. It +row's result (the API v2 ID it now holds, or why not), and the closing +check, which counts the rows still holding only an API v1 reference by why. It exits 0 when the check passes (nothing failed, and nothing is left but rows with missing parameters and saved simulations), 1 when it doesn't, and 2 for bad arguments. @@ -38,10 +38,10 @@ copies bind to the running .py version's catalog. It connects as the deployed API v1 does: -- the detailed-save database as the runtime role: ``V2_RUNTIME_DATABASE_URL`` +- the API v2 database as the runtime role: ``V2_RUNTIME_DATABASE_URL`` (or ``V2_RUNTIME_DATABASE_URL_SECRET_RESOURCE``), ``V2_SUPABASE_PROJECT_REF`` and ``V2_SUPABASE_ENVIRONMENT``; a dry run's transactions are read only; -- v1's database read only, as ``policyengine_schema_reader`` through the Cloud +- API v1's database read only, as ``policyengine_schema_reader`` through the Cloud SQL Auth Proxy on 127.0.0.1 (``POLICYENGINE_DB_READONLY_PASSWORD``, and ``POLICYENGINE_DB_PROXY_PORT``, 3307 without it). """ @@ -99,18 +99,18 @@ def migrate(self, options: MigrationOptions) -> MigrationRun: def compare_sample( self, *, size: int, country_ids: tuple[str, ...] ) -> SampleComparison: - """Put up to ``size`` migrated reports' run results next to v1's.""" + """Put up to ``size`` migrated reports' run results next to API v1's.""" ... def v1_read_only_database_url(environ: Mapping[str, str]) -> URL: - """Return the URL of v1's database as its read-only role, through the proxy. + """Return the URL of API v1's database as its read-only role, through the proxy. Raise MissingSettingError without ``POLICYENGINE_DB_READONLY_PASSWORD``. """ password = environ.get("POLICYENGINE_DB_READONLY_PASSWORD", "") if not password: - msg = "POLICYENGINE_DB_READONLY_PASSWORD is required to read v1's database" + msg = "POLICYENGINE_DB_READONLY_PASSWORD is required to read API v1's database" raise MissingSettingError(msg) return URL.create( drivername="mysql+pymysql", @@ -177,8 +177,8 @@ def _user_id(text: str) -> UUID: def _parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( description=( - "Give saved records that hold only a v1 reference their " - "detailed-save records, and check what is left." + "Give saved records that hold only an API v1 reference their " + "API v2 records, and check what is left." ) ) parser.add_argument( @@ -211,7 +211,7 @@ def _parser() -> argparse.ArgumentParser: type=_positive_integer, metavar="N", help=( - "Migrate nothing: print v1's stored budgetary impact next to the " + "Migrate nothing: print API v1's stored budgetary impact next to the " "newest successful run's for N migrated economy reports" ), ) diff --git a/tests/integration/test_v2_saved_record_migration.py b/tests/integration/test_v2_saved_record_migration.py index 3f15910a7..762279b0c 100644 --- a/tests/integration/test_v2_saved_record_migration.py +++ b/tests/integration/test_v2_saved_record_migration.py @@ -1,6 +1,6 @@ -"""The one-time migration of saved records' v1 references (D4 · 1). +"""The one-time migration of saved records' API v1 references (D4 · 1). -v1's rows are in MySQL and the detailed-save tables in PostgreSQL, where the +API v1's rows are in MySQL and the API v2 tables in PostgreSQL, where the command runs as API v1's runtime role, as it does in staging and production. A stand-in for the simulation service records each report definition it is sent and stores a report row for it, as the simulation service would, after @@ -50,8 +50,8 @@ V2SavedRecordMigrationService, ) from policyengine_api.services.v2.saved_record_migration.types import ( - DetailedSaveReportDefinition, - DetailedSaveReportKind, + ApiV2ReportDefinition, + ApiV2ReportKind, FailureReason, MigrationOptions, MigrationRun, @@ -91,7 +91,7 @@ PERIOD = "2026-01-01.2100-12-31" REFUSAL_CODE = "unknown_household" -# v1 IDs, chosen high so they don't meet other tests' rows. +# API v1 IDs, chosen high so they don't meet other tests' rows. CURRENT_LAW = 940_100 CTC_REFORM = 940_101 CTC_REFORM_WITH_ELASTICITY = 940_102 @@ -116,7 +116,7 @@ }, ONLY_REMOVED_PARAMETER: {REMOVED_PARAMETER: {PERIOD: True}}, } -# Each v1 simulation: its population type, population and policy. +# Each API v1 simulation: its population type, population and policy. V1_SIMULATIONS = { 940_201: ("geography", "us", CURRENT_LAW), 940_202: ("geography", "us", CTC_REFORM_WITH_ELASTICITY), @@ -126,7 +126,7 @@ 940_206: ("geography", "state/zz", CURRENT_LAW), 940_207: ("geography", "state/zz", CTC_REFORM), } -# Each v1 report output: its two simulations. +# Each API v1 report output: its two simulations. V1_REPORTS = { ECONOMY_REPORT: (940_201, 940_202), HOUSEHOLD_REPORT: (940_203, 940_204), @@ -155,7 +155,7 @@ def _store_v1_records(v1_sessions: sessionmaker[OrmSession]) -> None: V1Policy( id=policy_id, country_id="us", - label=f"v1 policy {policy_id}", + label=f"API v1 policy {policy_id}", api_version="1.0.0", policy_json=policy_json, policy_hash=f"d4-1-hash-{policy_id}", @@ -165,7 +165,7 @@ def _store_v1_records(v1_sessions: sessionmaker[OrmSession]) -> None: V1Household( id=V1_HOUSEHOLD, country_id="us", - label="v1 household", + label="API v1 household", api_version="1.0.0", household_json=_household_document(), household_hash="d4-1-household-hash", @@ -213,8 +213,8 @@ def _delete_v1_records(v1_sessions: sessionmaker[OrmSession]) -> None: @dataclass -class DetailedSaveRows: - """The rows each test stores in the detailed-save tables, to delete after.""" +class ApiV2Rows: + """The rows each test stores in the API v2 tables, to delete after.""" model_id: UUID created_model: bool @@ -235,11 +235,11 @@ class RecordingSimulationService: owner_sessions: sessionmaker[Session] catalog: CatalogRows - definitions: list[DetailedSaveReportDefinition] = field(default_factory=list) - reports: dict[DetailedSaveReportDefinition, UUID] = field(default_factory=dict) - refused: set[DetailedSaveReportKind] = field(default_factory=set) + definitions: list[ApiV2ReportDefinition] = field(default_factory=list) + reports: dict[ApiV2ReportDefinition, UUID] = field(default_factory=dict) + refused: set[ApiV2ReportKind] = field(default_factory=set) - def find_or_create_report(self, definition: DetailedSaveReportDefinition) -> UUID: + def find_or_create_report(self, definition: ApiV2ReportDefinition) -> UUID: self.definitions.append(definition) with self.owner_sessions() as session: # The simulation service reads what the definition names itself, @@ -272,7 +272,7 @@ def runtime_sessions( def stored_rows( v1_sessions: sessionmaker[OrmSession], v2_owner_sessions: sessionmaker[Session], -) -> Iterator[DetailedSaveRows]: +) -> Iterator[ApiV2Rows]: _store_v1_records(v1_sessions) with v2_owner_sessions.begin() as session: model_id = session.scalar( @@ -309,7 +309,7 @@ def stored_rows( name=INCOME_ELASTICITY, tax_benefit_model_version_id=version_id, ) - rows = DetailedSaveRows( + rows = ApiV2Rows( model_id=model_id, created_model=created_model, version_id=version_id, @@ -322,13 +322,11 @@ def stored_rows( try: yield rows finally: - _delete_detailed_save_rows(v2_owner_sessions, rows) + _delete_api_v2_rows(v2_owner_sessions, rows) _delete_v1_records(v1_sessions) -def _delete_detailed_save_rows( - owner_sessions: sessionmaker[Session], rows: DetailedSaveRows -) -> None: +def _delete_api_v2_rows(owner_sessions: sessionmaker[Session], rows: ApiV2Rows) -> None: users = [rows.first_user, rows.second_user] with owner_sessions.begin() as session: for model in ( @@ -419,7 +417,7 @@ def _service( def _simulation_service( - owner_sessions: sessionmaker[Session], rows: DetailedSaveRows + owner_sessions: sessionmaker[Session], rows: ApiV2Rows ) -> RecordingSimulationService: assert rows.report_catalog is not None return RecordingSimulationService(owner_sessions, rows.report_catalog) @@ -427,7 +425,7 @@ def _simulation_service( def _migrate( service: V2SavedRecordMigrationService, - rows: DetailedSaveRows, + rows: ApiV2Rows, **options: object, ) -> MigrationRun: return service.migrate( @@ -518,7 +516,7 @@ def test_a_saved_reform_is_pointed_at_its_v1_policy_s_copy( assert (row.policy_id, row.legacy_policy_id) == (mapping.policy_id, CTC_REFORM) result = _result(run, saved) assert result.outcome is RowOutcome.MIGRATED - assert result.detailed_save_id == mapping.policy_id + assert result.api_v2_id == mapping.policy_id assert result.saved_dynamic_id is None assert _policy_values(v2_owner_sessions, mapping.policy_id) == {(CTC_AMOUNT, 3000)} assert run.closing_check.passed @@ -621,13 +619,11 @@ def test_the_second_mode_keeps_the_parameters_that_still_exist( migrated = _result(run, partly_missing) assert migrated.outcome is RowOutcome.MIGRATED assert migrated.dropped_parameters == (REMOVED_PARAMETER,) - assert migrated.detailed_save_id is not None - assert _policy_values(v2_owner_sessions, migrated.detailed_save_id) == { - (EITC_RATE, 0.4) - } + assert migrated.api_v2_id is not None + assert _policy_values(v2_owner_sessions, migrated.api_v2_id) == {(EITC_RATE, 0.4)} row = _row(v2_owner_sessions, UserPolicy, partly_missing) - assert row.policy_id == migrated.detailed_save_id - # The kept policy isn't the v1 policy's copy, so the v1 ID gets no mapping. + assert row.policy_id == migrated.api_v2_id + # The kept policy isn't the API v1 policy's copy, so the API v1 ID gets no mapping. assert _mapping(v2_owner_sessions, CTC_REFORM_WITH_REMOVED_PARAMETER) is None left = _result(run, wholly_missing) assert left.outcome is RowOutcome.EVERY_PARAMETER_MISSING @@ -667,7 +663,7 @@ def test_a_saved_household_is_pointed_at_its_v1_household_s_copy( assert household_id is not None row = _row(v2_owner_sessions, UserHouseholdAssociation, saved) assert (row.household_id, row.legacy_household_id) == (household_id, V1_HOUSEHOLD) - assert _result(run, saved).detailed_save_id == household_id + assert _result(run, saved).api_v2_id == household_id assert run.closing_check.passed @@ -724,9 +720,9 @@ def test_identical_v1_reports_share_one_report_with_each_side_split( mapping = _mapping(v2_owner_sessions, CTC_REFORM_WITH_ELASTICITY) assert mapping is not None assert simulation_service.definitions == [ - DetailedSaveReportDefinition( + ApiV2ReportDefinition( country_id="us", - kind=DetailedSaveReportKind.ECONOMY, + kind=ApiV2ReportKind.ECONOMY, baseline=PolicySide(policy_id=None, dynamic_id=None), reform=PolicySide( policy_id=mapping.policy_id, dynamic_id=mapping.dynamic_id @@ -745,7 +741,7 @@ def test_identical_v1_reports_share_one_report_with_each_side_split( ECONOMY_REPORT, name, ) - assert _result(run, row_id).detailed_save_id == report_id + assert _result(run, row_id).api_v2_id == report_id assert run.closing_check.passed @@ -765,7 +761,7 @@ def test_a_saved_budget_window_becomes_a_budget_window_report( run = _migrate(service, stored_rows) (definition,) = simulation_service.definitions - assert definition.kind is DetailedSaveReportKind.BUDGET_WINDOW + assert definition.kind is ApiV2ReportKind.BUDGET_WINDOW assert (definition.year, definition.budget_window_size) == (2026, 10) row = _row(v2_owner_sessions, UserReportAssociation, saved) assert row.report_id == simulation_service.reports[definition] @@ -797,9 +793,9 @@ def test_a_household_report_names_the_household_s_copy( reform_mapping = _mapping(v2_owner_sessions, CTC_REFORM) assert reform_mapping is not None assert simulation_service.definitions == [ - DetailedSaveReportDefinition( + ApiV2ReportDefinition( country_id="us", - kind=DetailedSaveReportKind.HOUSEHOLD, + kind=ApiV2ReportKind.HOUSEHOLD, baseline=PolicySide(policy_id=None, dynamic_id=None), reform=PolicySide(policy_id=reform_mapping.policy_id, dynamic_id=None), year=None, @@ -840,7 +836,7 @@ def test_reports_that_cant_migrate_are_left_with_a_reason( legacy_report_id=940_399, ) simulation_service = _simulation_service(v2_owner_sessions, stored_rows) - simulation_service.refused.add(DetailedSaveReportKind.HOUSEHOLD) + simulation_service.refused.add(ApiV2ReportKind.HOUSEHOLD) service = _service(runtime_sessions, v1_sessions, simulation_service) run = _migrate(service, stored_rows) @@ -860,7 +856,7 @@ def test_reports_that_cant_migrate_are_left_with_a_reason( assert not run.closing_check.passed # Only the household report reached the simulation service. assert [item.kind for item in simulation_service.definitions] == [ - DetailedSaveReportKind.HOUSEHOLD + ApiV2ReportKind.HOUSEHOLD ] @@ -979,7 +975,7 @@ def test_the_limit_leaves_rows_the_closing_check_counts( assert not run.closing_check.passed -# The sample comparison of migrated reports' results with v1's. +# The sample comparison of migrated reports' results with API v1's. RUN_VERSIONS = {"country_package_version": "2.2.2", "policyengine_version": "6.20.0"} @@ -991,7 +987,7 @@ def _store_v1_result( budgetary_impact: float, country_package_version: str, ) -> None: - """Give a v1 report output a stored result from a run on a package version.""" + """Give an API v1 report output a stored result from a run on a package version.""" run_id = str(uuid4()) with v1_sessions.begin() as session: session.add( @@ -1045,7 +1041,7 @@ def test_the_sample_compares_a_migrated_report_s_run_with_v1_s_result( legacy_report_id=legacy_report_id, report_id=report_id, ) - # A saved report holding only its detailed-save report wasn't migrated. + # A saved report holding only its API v2 report wasn't migrated. _save( v2_owner_sessions, UserReportAssociation, @@ -1074,12 +1070,12 @@ def test_the_sample_compares_a_migrated_report_s_run_with_v1_s_result( calculated.report_id, run_ids.report_run_id, ) - assert (item.v1_budgetary_impact, item.v1_country_package_version) == ( + assert (item.api_v1_budgetary_impact, item.api_v1_country_package_version) == ( -10.0e9, "1.420.0", ) - assert item.detailed_save_budgetary_impact == pytest.approx(expected) - assert item.detailed_save_country_package_version == "2.2.2" + assert item.api_v2_budgetary_impact == pytest.approx(expected) + assert item.api_v2_country_package_version == "2.2.2" assert item.relative_difference == pytest.approx((expected + 10.0e9) / 10.0e9) assert simulation_service.definitions == [] @@ -1117,6 +1113,6 @@ def test_the_sample_takes_at_most_its_size( ) (item,) = comparison.comparisons - # v1 stored no result for this report. - assert item.v1_budgetary_impact is None + # API v1 stored no result for this report. + assert item.api_v1_budgetary_impact is None assert item.relative_difference is None diff --git a/tests/unit/test_migrate_saved_records_script.py b/tests/unit/test_migrate_saved_records_script.py index 53b574ad0..e5726c0c2 100644 --- a/tests/unit/test_migrate_saved_records_script.py +++ b/tests/unit/test_migrate_saved_records_script.py @@ -1,4 +1,4 @@ -"""Tests for the one-time command that migrates saved records' v1 references.""" +"""Tests for the one-time command that migrates saved records' API v1 references.""" from __future__ import annotations @@ -23,7 +23,7 @@ SavedRecordKind, SavedRecordResult, ) -from scripts import migrate_saved_records_to_detailed_save as command +from scripts import migrate_saved_records_to_api_v2 as command if TYPE_CHECKING: from collections.abc import Iterator @@ -243,7 +243,7 @@ def test_loading_the_command_leaves_the_observability_runtime_unbuilt() -> None: """ import_check = ( "import sys\n" - "import scripts.migrate_saved_records_to_detailed_save\n" + "import scripts.migrate_saved_records_to_api_v2\n" "import policyengine_api.data.v2.database\n" "import policyengine_api.data.v1_sessions\n" "import policyengine_api.services.v2.saved_record_migration.database_session\n" diff --git a/tests/unit/test_v2_integration_workflow.py b/tests/unit/test_v2_integration_workflow.py index 38a4bece0..77f4265b3 100644 --- a/tests/unit/test_v2_integration_workflow.py +++ b/tests/unit/test_v2_integration_workflow.py @@ -118,7 +118,7 @@ def test_the_job_publishes_dynamic_parameters_into_their_own_tables() -> None: def test_the_job_runs_the_saved_record_migration_tests() -> None: """The one-time saved-record migration's cross-database tests run (D4 · 1). - They read v1's rows in MySQL and write the detailed-save tables in + They read API v1's rows in MySQL and write the API v2 tables in PostgreSQL as policyengine_v2_runtime, after the schema upgrades and the role grants. """ diff --git a/tests/unit/v2/test_saved_record_migration_rules.py b/tests/unit/v2/test_saved_record_migration_rules.py index aaeffec04..9d1d1d672 100644 --- a/tests/unit/v2/test_saved_record_migration_rules.py +++ b/tests/unit/v2/test_saved_record_migration_rules.py @@ -1,8 +1,8 @@ """The one-time migration's rules that need no database (D4 · 1). -They rebuild a v1 report's definition from its v1 rows, translate a v1 region -into a catalog region code, keep only the parameters a running catalog still -has, build the detailed-save report definition, and work out the closing +They rebuild an API v1 report's definition from its API v1 rows, translate +an API v1 region into a catalog region code, keep only the parameters a +running catalog still has, build the API v2 report definition, and work out the closing check and the command's JSON document. """ @@ -19,15 +19,15 @@ from policyengine_api.services.v2.policies.transformations import split_legacy_policy from policyengine_api.services.v2.policies.types import LegacyPolicySnapshot from policyengine_api.services.v2.saved_record_migration.transformations import ( + api_v2_report_definition, closing_check, - detailed_save_report_definition, kept_policy_snapshot, migration_document, relative_difference, sample_comparison_document, ) from policyengine_api.services.v2.saved_record_migration.types import ( - DetailedSaveReportKind, + ApiV2ReportKind, FailureReason, MigrationOptions, MigrationRun, @@ -128,7 +128,7 @@ def _remaining(**rows_by_kind: set[UUID]) -> dict[SavedRecordKind, set[UUID]]: return remaining -# A v1 report's definition, from its report output and simulations. +# An API v1 report's definition, from its report output and simulations. def test_an_economy_comparison_compares_simulation_one_with_simulation_two() -> None: @@ -252,7 +252,7 @@ def test_a_v1_report_that_cant_be_rebuilt_is_refused( assert refusal.value.reason is FailureReason.V1_REPORT_UNREADABLE -# v1 regions, as catalog region codes. +# API v1 regions, as catalog region codes. @pytest.mark.parametrize( @@ -342,7 +342,7 @@ def test_kept_uk_parameters_take_their_current_spelling() -> None: assert kept.policy_json == {UK_INCOME_ELASTICITY: {"2026-01-01.2100-12-31": 0.2}} -# The detailed-save report definition. +# The API v2 report definition. def _v1_definition( @@ -366,7 +366,7 @@ def test_an_economy_report_without_a_window_is_an_economy_report( ) -> None: reform = PolicySide(policy_id=POLICY_ID, dynamic_id=DYNAMIC_ID) - definition = detailed_save_report_definition( + definition = api_v2_report_definition( _v1_definition(), baseline=PolicySide(policy_id=None, dynamic_id=None), reform=reform, @@ -375,7 +375,7 @@ def test_an_economy_report_without_a_window_is_an_economy_report( budget_window_years=budget_window_years, ) - assert definition.kind is DetailedSaveReportKind.ECONOMY + assert definition.kind is ApiV2ReportKind.ECONOMY assert definition.year == 2026 assert definition.region_code == "state/ca" assert definition.budget_window_size is None @@ -384,7 +384,7 @@ def test_an_economy_report_without_a_window_is_an_economy_report( def test_a_saved_window_of_two_or_more_years_makes_a_budget_window() -> None: - definition = detailed_save_report_definition( + definition = api_v2_report_definition( _v1_definition(), baseline=PolicySide(policy_id=None, dynamic_id=None), reform=PolicySide(policy_id=POLICY_ID, dynamic_id=None), @@ -393,13 +393,13 @@ def test_a_saved_window_of_two_or_more_years_makes_a_budget_window() -> None: budget_window_years=10, ) - assert definition.kind is DetailedSaveReportKind.BUDGET_WINDOW + assert definition.kind is ApiV2ReportKind.BUDGET_WINDOW assert definition.budget_window_size == 10 assert definition.year == 2026 def test_a_household_report_names_its_household_and_no_year_or_region() -> None: - definition = detailed_save_report_definition( + definition = api_v2_report_definition( _v1_definition(V1ReportKind.HOUSEHOLD, reform_policy_id=None), baseline=PolicySide(policy_id=POLICY_ID, dynamic_id=None), reform=None, @@ -408,7 +408,7 @@ def test_a_household_report_names_its_household_and_no_year_or_region() -> None: budget_window_years=None, ) - assert definition.kind is DetailedSaveReportKind.HOUSEHOLD + assert definition.kind is ApiV2ReportKind.HOUSEHOLD assert definition.household_id == HOUSEHOLD_ID assert definition.reform is None assert definition.year is None @@ -497,7 +497,7 @@ def test_the_document_lists_every_row_its_counts_and_the_check() -> None: _result( FIRST_ROW, RowOutcome.MIGRATED, - detailed_save_id=POLICY_ID, + api_v2_id=POLICY_ID, saved_dynamic_id=DYNAMIC_ID, dropped_parameters=(REMOVED_PARAMETER,), ), @@ -533,7 +533,7 @@ def test_the_document_lists_every_row_its_counts_and_the_check() -> None: "country_id": "us", "legacy_id": 55, "outcome": "migrated", - "detailed_save_id": str(POLICY_ID), + "api_v2_id": str(POLICY_ID), "saved_dynamic_id": str(DYNAMIC_ID), "missing_parameters": [], "dropped_parameters": [REMOVED_PARAMETER], @@ -562,11 +562,11 @@ def test_a_dry_run_document_says_so() -> None: assert document["rows"] == [] -# The sample comparison of migrated reports' results with v1's. +# The sample comparison of migrated reports' results with API v1's. @pytest.mark.parametrize( - ("v1_value", "detailed_save_value", "difference"), + ("v1_value", "api_v2_value", "difference"), [ (-10.0e9, -10.4e9, -0.04), (2.0e9, 2.0e9, 0.0), @@ -578,10 +578,10 @@ def test_a_dry_run_document_says_so() -> None: ) def test_the_relative_difference_is_measured_from_v1_s_value( v1_value: float | None, - detailed_save_value: float | None, + api_v2_value: float | None, difference: float | None, ) -> None: - measured = relative_difference(v1_value, detailed_save_value) + measured = relative_difference(v1_value, api_v2_value) if difference is None: assert measured is None @@ -599,10 +599,10 @@ def test_the_comparison_document_lists_each_report_s_two_results() -> None: legacy_report_id=900, report_id=FIRST_ROW, report_run_id=SECOND_ROW, - v1_budgetary_impact=-10.0e9, - v1_country_package_version="1.420.0", - detailed_save_budgetary_impact=-10.4e9, - detailed_save_country_package_version="2.2.2", + api_v1_budgetary_impact=-10.0e9, + api_v1_country_package_version="1.420.0", + api_v2_budgetary_impact=-10.4e9, + api_v2_country_package_version="2.2.2", relative_difference=-0.04, ), ), @@ -620,10 +620,10 @@ def test_the_comparison_document_lists_each_report_s_two_results() -> None: "legacy_report_id": 900, "report_id": str(FIRST_ROW), "report_run_id": str(SECOND_ROW), - "v1_budgetary_impact": -10.0e9, - "v1_country_package_version": "1.420.0", - "detailed_save_budgetary_impact": -10.4e9, - "detailed_save_country_package_version": "2.2.2", + "api_v1_budgetary_impact": -10.0e9, + "api_v1_country_package_version": "1.420.0", + "api_v2_budgetary_impact": -10.4e9, + "api_v2_country_package_version": "2.2.2", "relative_difference": -0.04, "note": None, } From c3113021caa48cf5624a2138b1626e01a696dc60 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:44:08 +0400 Subject: [PATCH 07/22] Add failing tests for the migration's --kind filter A run can take some kinds of saved record only (decided 2026-11-30), so a rehearsal on a copy of production whose simulation service can't calculate migrates saved reforms and households without asking it for any report. The closing check and the JSON document cover only those kinds and name them, and the document says the sample comparison wasn't run. Co-Authored-By: Claude Opus 5.5 --- .../test_v2_saved_record_migration.py | 36 ++++++++++++++++ .../unit/test_migrate_saved_records_script.py | 21 ++++++++++ .../v2/test_saved_record_migration_rules.py | 41 +++++++++++++++++++ 3 files changed, 98 insertions(+) diff --git a/tests/integration/test_v2_saved_record_migration.py b/tests/integration/test_v2_saved_record_migration.py index 762279b0c..511cf42df 100644 --- a/tests/integration/test_v2_saved_record_migration.py +++ b/tests/integration/test_v2_saved_record_migration.py @@ -975,6 +975,42 @@ def test_the_limit_leaves_rows_the_closing_check_counts( assert not run.closing_check.passed +def test_a_run_of_some_kinds_leaves_the_others_alone( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + saved_reform = _save( + v2_owner_sessions, + UserPolicy, + user_id=stored_rows.first_user, + legacy_policy_id=CTC_REFORM, + ) + saved_report = _save( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=ECONOMY_REPORT, + ) + simulation_service = _simulation_service(v2_owner_sessions, stored_rows) + service = _service(runtime_sessions, v1_sessions, simulation_service) + + run = _migrate( + service, + stored_rows, + kinds=(SavedRecordKind.SAVED_REFORM, SavedRecordKind.SAVED_HOUSEHOLD), + ) + + assert [result.row_id for result in run.results] == [saved_reform] + assert ( + _row(v2_owner_sessions, UserReportAssociation, saved_report).report_id is None + ) + assert simulation_service.definitions == [] + assert [item.kind for item in run.closing_check.remaining] == [ + SavedRecordKind.SAVED_REFORM, + SavedRecordKind.SAVED_HOUSEHOLD, + ] + assert run.closing_check.passed + + # The sample comparison of migrated reports' results with API v1's. RUN_VERSIONS = {"country_package_version": "2.2.2", "policyengine_version": "6.20.0"} diff --git a/tests/unit/test_migrate_saved_records_script.py b/tests/unit/test_migrate_saved_records_script.py index e5726c0c2..4a4402638 100644 --- a/tests/unit/test_migrate_saved_records_script.py +++ b/tests/unit/test_migrate_saved_records_script.py @@ -139,6 +139,25 @@ def test_both_countries_are_migrated_unless_one_is_named() -> None: assert factory.migrator.options[0].country_ids == ("uk", "us") +def test_kinds_named_are_migrated_in_the_order_rows_are_taken() -> None: + factory = RecordingFactory(FakeMigrator()) + + _run(["--kind", "saved_household", "--kind", "saved_reform"], factory) + + assert factory.migrator.options[0].kinds == ( + SavedRecordKind.SAVED_REFORM, + SavedRecordKind.SAVED_HOUSEHOLD, + ) + + +def test_every_kind_is_migrated_unless_one_is_named() -> None: + factory = RecordingFactory(FakeMigrator()) + + _run([], factory) + + assert factory.migrator.options[0].kinds == tuple(SavedRecordKind) + + def test_rows_left_behind_make_the_command_exit_1(capsys) -> None: factory = RecordingFactory(FakeMigrator(remaining={SAVED_ROW})) @@ -156,6 +175,7 @@ def test_rows_left_behind_make_the_command_exit_1(capsys) -> None: ["--limit", "many"], ["--country", "ca"], ["--user-id", "not-a-uuid"], + ["--kind", "saved_policy"], ["--apply"], ], ) @@ -190,6 +210,7 @@ def test_a_sample_comparison_reads_only_and_migrates_nothing(capsys) -> None: ["--compare-sample", "5", "--drop-missing-parameters"], ["--compare-sample", "5", "--limit", "3"], ["--compare-sample", "5", "--user-id", str(FIRST_USER)], + ["--compare-sample", "5", "--kind", "saved_report"], ], ) def test_a_sample_comparison_takes_no_migration_flag(arguments) -> None: diff --git a/tests/unit/v2/test_saved_record_migration_rules.py b/tests/unit/v2/test_saved_record_migration_rules.py index 9d1d1d672..6f5596436 100644 --- a/tests/unit/v2/test_saved_record_migration_rules.py +++ b/tests/unit/v2/test_saved_record_migration_rules.py @@ -629,3 +629,44 @@ def test_the_comparison_document_lists_each_report_s_two_results() -> None: } ], } + + +# A run of some kinds only (--kind). + + +def test_the_check_covers_only_the_kinds_the_run_took() -> None: + check = closing_check( + { + SavedRecordKind.SAVED_REFORM: {FIRST_ROW}, + SavedRecordKind.SAVED_HOUSEHOLD: set(), + }, + [_result(FIRST_ROW, RowOutcome.MIGRATED)], + ) + + assert [remaining.kind for remaining in check.remaining] == [ + SavedRecordKind.SAVED_REFORM, + SavedRecordKind.SAVED_HOUSEHOLD, + ] + assert check.passed + + +def test_the_document_names_its_kinds_and_says_the_comparison_wasnt_run() -> None: + kinds = (SavedRecordKind.SAVED_REFORM, SavedRecordKind.SAVED_HOUSEHOLD) + run = MigrationRun( + options=MigrationOptions(apply=True, kinds=kinds), + policyengine_version="6.20.0", + results=(), + closing_check=closing_check({kind: set() for kind in kinds}, ()), + ) + + document = migration_document(run) + + assert document["kinds"] == ["saved_reform", "saved_household"] + assert list(document["counts"]) == ["saved_reform", "saved_household"] + assert list(document["closing_check"]["remaining"]) == [ + "saved_reform", + "saved_household", + ] + assert document["sample_comparison"] == ( + "not run: run the command with --compare-sample N for it" + ) From 7b87054c2e9fc016e657d1dde0b6502ceadd2b3f Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:45:53 +0400 Subject: [PATCH 08/22] Add the migration's --kind filter --kind (repeatable: saved_reform, saved_household, saved_report, saved_simulation; every kind without it) keeps a run to those kinds of saved record. The closing check and the JSON document cover only those kinds and name them (kinds), and the document says the sample comparison wasn't run. --compare-sample takes no --kind. Docstrings that still had a bare `v1` at the end of a line of text now name API v1 in full. Co-Authored-By: Claude Opus 5.5 --- .../v2/saved_record_migration/services.py | 28 +++++---- .../saved_record_migration/transformations.py | 19 ++++-- .../v2/saved_record_migration/types.py | 18 +++--- .../v2/saved_record_migration/validators.py | 13 ++-- scripts/migrate_saved_records_to_api_v2.py | 62 +++++++++++++------ 5 files changed, 88 insertions(+), 52 deletions(-) diff --git a/policyengine_api/services/v2/saved_record_migration/services.py b/policyengine_api/services/v2/saved_record_migration/services.py index 1c15701c7..077ccfa35 100644 --- a/policyengine_api/services/v2/saved_record_migration/services.py +++ b/policyengine_api/services/v2/saved_record_migration/services.py @@ -223,7 +223,7 @@ def migrate(self, options: MigrationOptions) -> MigrationRun: for record in self._pending(options, limit=options.limit) ) remaining: dict[SavedRecordKind, set[UUID]] = { - kind: set() for kind in SavedRecordKind + kind: set() for kind in options.kinds } for record in self._pending(options, limit=None): remaining[record.kind].add(record.row_id) @@ -309,40 +309,44 @@ def _run_budgetary_impact( def _pending( self, options: MigrationOptions, *, limit: int | None ) -> list[PendingSavedRecord]: - """Return the rows holding only an API v1 reference. + """Return the rows of the chosen kinds holding only an API v1 reference. Saved reforms come first, then households and reports, which reuse the copies they made, then simulations. """ countries = options.country_ids users = options.user_ids + pending: list[PendingSavedRecord] = [] with self._database.read() as session: - return [ - *( + if SavedRecordKind.SAVED_REFORM in options.kinds: + pending.extend( pending_saved_reform(row) for row in read_saved_reforms_holding_only_v1_policies( session, country_ids=countries, user_ids=users, limit=limit ) - ), - *( + ) + if SavedRecordKind.SAVED_HOUSEHOLD in options.kinds: + pending.extend( pending_saved_household(row) for row in read_saved_households_holding_only_v1_households( session, country_ids=countries, user_ids=users, limit=limit ) - ), - *( + ) + if SavedRecordKind.SAVED_REPORT in options.kinds: + pending.extend( pending_saved_report(row) for row in read_saved_reports_holding_only_v1_reports( session, country_ids=countries, user_ids=users, limit=limit ) - ), - *( + ) + if SavedRecordKind.SAVED_SIMULATION in options.kinds: + pending.extend( pending_saved_simulation(row) for row in read_saved_simulations_holding_only_v1_simulations( session, country_ids=countries, user_ids=users, limit=limit ) - ), - ] + ) + return pending def _migrate_record( self, diff --git a/policyengine_api/services/v2/saved_record_migration/transformations.py b/policyengine_api/services/v2/saved_record_migration/transformations.py index 45c9ca085..b474b0d97 100644 --- a/policyengine_api/services/v2/saved_record_migration/transformations.py +++ b/policyengine_api/services/v2/saved_record_migration/transformations.py @@ -187,15 +187,18 @@ def closing_check( ) -> ClosingCheck: """Count the rows still holding only an API v1 reference by what the run did. - ``remaining`` holds, for each kind, the rows holding only an API v1 reference - when the run ended. A row the run migrated, or in a dry run would - migrate, isn't counted. Any other row is counted by its outcome, and one - the run has no result for as not attempted. The check passes when - nothing failed and nothing was left unattempted. + ``remaining`` holds, for each kind the run took, the rows holding only an + API v1 reference when the run ended; the check covers those kinds only. A + row the run migrated, or in a dry run would migrate, isn't counted. Any + other row is counted by its outcome, and one the run has no result for as + not attempted. The check passes when nothing failed and nothing was left + unattempted. """ outcomes = {(result.kind, result.row_id): result.outcome for result in results} counted: list[RemainingV1References] = [] for kind in SavedRecordKind: + if kind not in remaining: + continue counts: Counter[str] = Counter() for row_id in remaining.get(kind, ()): outcome = outcomes.get((kind, row_id)) @@ -248,7 +251,7 @@ def migration_document(run: MigrationRun) -> dict[str, object]: result (a rollback clears the API v2 reference of the rows it lists as migrated), and the closing check. """ - counts: dict[str, dict[str, int]] = {kind.value: {} for kind in SavedRecordKind} + counts: dict[str, dict[str, int]] = {kind.value: {} for kind in run.options.kinds} for result in run.results: by_outcome = counts[result.kind.value] by_outcome[result.outcome.value] = by_outcome.get(result.outcome.value, 0) + 1 @@ -256,6 +259,7 @@ def migration_document(run: MigrationRun) -> dict[str, object]: "mode": "migrate" if run.options.apply else "dry_run", "drop_missing_parameters": run.options.drop_missing_parameters, "countries": list(run.options.country_ids), + "kinds": [kind.value for kind in run.options.kinds], "limit": run.options.limit, "user_ids": ( None @@ -278,6 +282,9 @@ def migration_document(run: MigrationRun) -> dict[str, object]: for item in run.closing_check.remaining }, }, + "sample_comparison": ( + "not run: run the command with --compare-sample N for it" + ), } diff --git a/policyengine_api/services/v2/saved_record_migration/types.py b/policyengine_api/services/v2/saved_record_migration/types.py index 8d0ce7af6..6a1402e35 100644 --- a/policyengine_api/services/v2/saved_record_migration/types.py +++ b/policyengine_api/services/v2/saved_record_migration/types.py @@ -1,10 +1,10 @@ """Types of the one-time migration of saved records' API v1 references (D4 · 1). -Saved reforms, saved reports and saved households that hold only a v1 -reference are given the API v2 record that reference stands for; -saved simulations holding only an API v1 reference are listed. Each row's outcome -is a ``SavedRecordResult``, and a run's is a ``MigrationRun`` with its closing -check. +Saved reforms, saved reports and saved households that hold only an API v1 +reference are given the API v2 record that reference stands for; saved +simulations holding only an API v1 reference are listed. Each row's outcome +is a ``SavedRecordResult``, and a run's is a ``MigrationRun`` with its +closing check. """ from __future__ import annotations @@ -86,7 +86,8 @@ class MigrationOptions: (E1 · 4): rows whose policies set parameters the running catalog lacks migrate from the parameters that still exist. ``limit`` caps the rows of each kind a run takes, oldest first; ``user_ids`` keeps the run to those - owners' rows. The closing check covers the same countries and owners. + owners' rows, and ``kinds`` to those kinds of saved record. The closing + check covers the same countries, owners and kinds. """ apply: bool @@ -94,6 +95,7 @@ class MigrationOptions: country_ids: tuple[str, ...] = ("uk", "us") limit: int | None = None user_ids: tuple[UUID, ...] | None = None + kinds: tuple[SavedRecordKind, ...] = tuple(SavedRecordKind) @dataclass(frozen=True) @@ -139,8 +141,8 @@ class V1ReportDefinition: Simulation 1 is the baseline and simulation 2 the reform. A report of one economy simulation names that simulation's policy on both sides; a report of one household simulation has no reform. ``region`` is an economy - report's API v1 region, and ``legacy_household_id`` a household report's v1 - household. + report's API v1 region, and ``legacy_household_id`` a household report's + API v1 household. """ country_id: str diff --git a/policyengine_api/services/v2/saved_record_migration/validators.py b/policyengine_api/services/v2/saved_record_migration/validators.py index ce6270e73..0c73f3cf5 100644 --- a/policyengine_api/services/v2/saved_record_migration/validators.py +++ b/policyengine_api/services/v2/saved_record_migration/validators.py @@ -1,11 +1,12 @@ """Checks the one-time migration makes on rows it has already read (D4 · 1). -An API v1 report is rebuilt from its report output and simulations as API v1's report -spec reads them (``policyengine_api.services.report_spec_service``), and a v1 -region is translated through the catalog's region reference files, which -pair each catalog region with the API v1 region it replaces (``v1_code``). A row -that can't be migrated raises ``SavedRecordMigrationRefusal`` with a reason, -and keeps its API v1 reference. +An API v1 report is rebuilt from its report output and simulations as API +v1's report spec reads them (``policyengine_api.services.report_spec_service``), +and an API v1 region is translated through the catalog's region reference +files, which pair each catalog region with the API v1 region it replaces +(``v1_code``). A row that can't be migrated raises +``SavedRecordMigrationRefusal`` with a reason, and keeps its API v1 +reference. """ from __future__ import annotations diff --git a/scripts/migrate_saved_records_to_api_v2.py b/scripts/migrate_saved_records_to_api_v2.py index e91fdc0ea..a06dc9112 100755 --- a/scripts/migrate_saved_records_to_api_v2.py +++ b/scripts/migrate_saved_records_to_api_v2.py @@ -4,18 +4,19 @@ The one-time migration (D4 · 1). Usage:: migrate_saved_records_to_api_v2.py [--dry-run] - [--drop-missing-parameters] [--country us|uk ...] [--limit N] - [--user-id UUID ...] + [--drop-missing-parameters] [--kind KIND ...] [--country us|uk ...] + [--limit N] [--user-id UUID ...] + migrate_saved_records_to_api_v2.py --compare-sample N [--country us|uk ...] It reads every saved reform, saved household, saved report and saved simulation that holds an API v1 reference and no API v2 reference, oldest -first, and gives each of the first three the API v2 record that v1 +first, and gives each of the first three the API v2 record that API v1 reference stands for: a saved reform its API v1 policy's copy, split into a -policy and a dynamic, with a saved dynamic of the same name when the v1 -policy sets model assumptions; a saved household its API v1 household's copy; a -saved report the report the simulation service finds or creates for the v1 -report's definition. Each row keeps its API v1 reference. Saved simulations are -only listed. Running it again picks up what is left. +policy and a dynamic, with a saved dynamic of the same name when the API v1 +policy sets model assumptions; a saved household its API v1 household's +copy; a saved report the report the simulation service finds or creates for +the API v1 report's definition. Each row keeps its API v1 reference. Saved +simulations are only listed. Running it again picks up what is left. - ``--dry-run`` reads both databases and writes nothing; it calls no other service. @@ -23,27 +24,32 @@ and listed. ``--drop-missing-parameters`` (the last run, E1 · 4) migrates it from the parameters that still exist and lists those it dropped; a row whose every parameter is missing is still left and listed. -- ``--country`` keeps the run to one country (both without it), ``--limit`` - to the oldest N rows of each kind, and ``--user-id`` to those owners' rows. - The closing check covers the same rows. +- ``--kind`` keeps the run to those kinds of saved record (``saved_reform``, + ``saved_household``, ``saved_report``, ``saved_simulation``; all without + it), ``--country`` to one country (both without it), ``--limit`` to the + oldest N rows of each kind, and ``--user-id`` to those owners' rows. The + closing check covers the same rows. +- ``--compare-sample N`` migrates nothing: it prints API v1's stored + budgetary impact next to the newest successful run's for N migrated + economy reports, starts no run and exits 0. It prints one JSON document: counts of each kind's rows by outcome, every row's result (the API v2 ID it now holds, or why not), and the closing -check, which counts the rows still holding only an API v1 reference by why. It -exits 0 when the check passes (nothing failed, and nothing is left but rows -with missing parameters and saved simulations), 1 when it doesn't, and 2 for -bad arguments. +check, which counts the rows still holding only an API v1 reference by why. +It exits 0 when the check passes (nothing failed, and nothing is left but +rows with missing parameters and saved simulations), 1 when it doesn't, and +2 for bad arguments. Run it from a checkout of the commit deployed in that environment, since copies bind to the running .py version's catalog. It connects as the deployed API v1 does: -- the API v2 database as the runtime role: ``V2_RUNTIME_DATABASE_URL`` - (or ``V2_RUNTIME_DATABASE_URL_SECRET_RESOURCE``), ``V2_SUPABASE_PROJECT_REF`` +- the API v2 database as the runtime role: ``V2_RUNTIME_DATABASE_URL`` (or + ``V2_RUNTIME_DATABASE_URL_SECRET_RESOURCE``), ``V2_SUPABASE_PROJECT_REF`` and ``V2_SUPABASE_ENVIRONMENT``; a dry run's transactions are read only; -- API v1's database read only, as ``policyengine_schema_reader`` through the Cloud - SQL Auth Proxy on 127.0.0.1 (``POLICYENGINE_DB_READONLY_PASSWORD``, and - ``POLICYENGINE_DB_PROXY_PORT``, 3307 without it). +- API v1's database read only, as ``policyengine_schema_reader`` through + the Cloud SQL Auth Proxy on 127.0.0.1 (``POLICYENGINE_DB_READONLY_PASSWORD``, + and ``POLICYENGINE_DB_PROXY_PORT``, 3307 without it). """ from __future__ import annotations @@ -66,6 +72,7 @@ ) from policyengine_api.services.v2.saved_record_migration.types import ( MigrationOptions, + SavedRecordKind, ) if TYPE_CHECKING: @@ -206,6 +213,13 @@ def _parser() -> argparse.ArgumentParser: type=_positive_integer, help="Migrate at most this many rows of each kind, oldest first", ) + parser.add_argument( + "--kind", + action="append", + choices=[kind.value for kind in SavedRecordKind], + dest="kinds", + help="Migrate this kind of saved record only; repeat for more (all without it)", + ) parser.add_argument( "--compare-sample", type=_positive_integer, @@ -236,6 +250,13 @@ def _options(arguments: argparse.Namespace) -> MigrationOptions: ), limit=arguments.limit, user_ids=None if arguments.user_ids is None else tuple(arguments.user_ids), + kinds=( + tuple(SavedRecordKind) + if arguments.kinds is None + else tuple( + kind for kind in SavedRecordKind if kind.value in arguments.kinds + ) + ), ) @@ -266,6 +287,7 @@ def main( or arguments.drop_missing_parameters or arguments.limit is not None or arguments.user_ids is not None + or arguments.kinds is not None ): parser.error("--compare-sample takes only --country") with migrator_factory(dry_run=True) as migrator: From 6978bd6f0530fe2f65695b6f53918097adebf880 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:03:41 +0400 Subject: [PATCH 09/22] Add failing tests for review round 1's findings - A saved reform whose description a saved dynamic can't take fails its row alone, in the dry run too, and the run goes on. - A refused report is asked for once for all its saved reports. - An unexpected error fails its row, and the run still prints its rows. - In the second mode, a report keeps what still exists on both sides, and a report left because every parameter of its own policy is missing lists both sides' missing parameters. - A dry run fails an API v1 policy mapped from another source, as a run does. - A UK nation typed with spaces matches its region. - One rule says which saved windows are budget windows. Tests for a row changed during the run, saved reforms sharing a copy and a dry run through a read-only connection pass already and add coverage. Co-Authored-By: Claude Opus 5.5 --- .../test_v2_saved_record_migration.py | 309 +++++++++++++++++- .../v2/test_saved_record_migration_rules.py | 11 + 2 files changed, 318 insertions(+), 2 deletions(-) diff --git a/tests/integration/test_v2_saved_record_migration.py b/tests/integration/test_v2_saved_record_migration.py index 511cf42df..1a9e6640a 100644 --- a/tests/integration/test_v2_saved_record_migration.py +++ b/tests/integration/test_v2_saved_record_migration.py @@ -23,6 +23,7 @@ from policyengine_api.data.v1_models import ReportOutput as V1ReportOutput from policyengine_api.data.v1_models import ReportOutputRun as V1ReportOutputRun from policyengine_api.data.v1_models import Simulation as V1Simulation +from policyengine_api.data.v2.database import build_v2_session_factory from policyengine_api.data.v2.models import ( Dynamic, DynamicParameter, @@ -88,6 +89,7 @@ EITC_RATE = "gov.irs.credits.eitc.phase_in_rate" INCOME_ELASTICITY = "gov.simulation.labor_supply_responses.elasticities.income" REMOVED_PARAMETER = "gov.simulation.reported_snap" +OTHER_REMOVED_PARAMETER = "gov.irs.credits.eitc.removed_rate" PERIOD = "2026-01-01.2100-12-31" REFUSAL_CODE = "unknown_household" @@ -97,11 +99,14 @@ CTC_REFORM_WITH_ELASTICITY = 940_102 CTC_REFORM_WITH_REMOVED_PARAMETER = 940_103 ONLY_REMOVED_PARAMETER = 940_104 +EITC_REFORM_WITH_OTHER_REMOVED_PARAMETER = 940_105 V1_HOUSEHOLD = 940_501 ECONOMY_REPORT = 940_301 HOUSEHOLD_REPORT = 940_303 MISSING_PARAMETER_REPORT = 940_304 UNKNOWN_REGION_REPORT = 940_305 +EVERY_PARAMETER_MISSING_REPORT = 940_306 +BASELINE_MISSING_REPORT = 940_307 SAVED_SIMULATION = 940_211 V1_POLICIES = { CURRENT_LAW: {}, @@ -115,6 +120,10 @@ REMOVED_PARAMETER: {PERIOD: True}, }, ONLY_REMOVED_PARAMETER: {REMOVED_PARAMETER: {PERIOD: True}}, + EITC_REFORM_WITH_OTHER_REMOVED_PARAMETER: { + EITC_RATE: {PERIOD: 0.3}, + OTHER_REMOVED_PARAMETER: {PERIOD: 0.1}, + }, } # Each API v1 simulation: its population type, population and policy. V1_SIMULATIONS = { @@ -125,6 +134,9 @@ 940_205: ("geography", "us", CTC_REFORM_WITH_REMOVED_PARAMETER), 940_206: ("geography", "state/zz", CURRENT_LAW), 940_207: ("geography", "state/zz", CTC_REFORM), + 940_208: ("geography", "us", ONLY_REMOVED_PARAMETER), + 940_209: ("geography", "us", EITC_REFORM_WITH_OTHER_REMOVED_PARAMETER), + 940_210: ("geography", "us", CTC_REFORM), } # Each API v1 report output: its two simulations. V1_REPORTS = { @@ -132,6 +144,11 @@ HOUSEHOLD_REPORT: (940_203, 940_204), MISSING_PARAMETER_REPORT: (940_201, 940_205), UNKNOWN_REGION_REPORT: (940_206, 940_207), + # A reform whose every parameter is missing, compared with a baseline + # that sets one that still exists and another that is missing. + EVERY_PARAMETER_MISSING_REPORT: (940_209, 940_208), + # A baseline whose every parameter is missing, and a reform that is whole. + BASELINE_MISSING_REPORT: (940_208, 940_210), } @@ -230,7 +247,10 @@ class RecordingSimulationService: Each definition gets one report row, stored as the database's owner, and the same definition gets the same report again. ``refused`` lists the - definitions it refuses, as the simulation service answers 400. + kinds of definition it refuses, as the simulation service answers 400, + and ``broken`` those it fails on with an error the migration doesn't + expect. ``while_answering`` runs before it answers, as a user's change + to a saved row would. """ owner_sessions: sessionmaker[Session] @@ -238,6 +258,8 @@ class RecordingSimulationService: definitions: list[ApiV2ReportDefinition] = field(default_factory=list) reports: dict[ApiV2ReportDefinition, UUID] = field(default_factory=dict) refused: set[ApiV2ReportKind] = field(default_factory=set) + broken: set[ApiV2ReportKind] = field(default_factory=set) + while_answering: Callable[[], None] | None = None def find_or_create_report(self, definition: ApiV2ReportDefinition) -> UUID: self.definitions.append(definition) @@ -254,6 +276,11 @@ def find_or_create_report(self, definition: ApiV2ReportDefinition) -> UUID: if definition.kind in self.refused: message = "the simulation service refused the household report" raise ReportSubmissionRefusedError(REFUSAL_CODE, message) + if definition.kind in self.broken: + message = "the stand-in simulation service broke" + raise RuntimeError(message) + if self.while_answering is not None: + self.while_answering() if definition not in self.reports: with self.owner_sessions.begin() as session: self.reports[definition] = store_report(session, self.catalog).report_id @@ -416,6 +443,16 @@ def _service( ) +def _read_only(sessions: sessionmaker[Session]) -> sessionmaker[Session]: + """Return the same role's sessions with every transaction READ ONLY. + + The command opens a dry run's sessions this way, so PostgreSQL refuses + any write it tried. + """ + engine = sessions.kw["bind"] + return build_v2_session_factory(engine.execution_options(postgresql_readonly=True)) + + def _simulation_service( owner_sessions: sessionmaker[Session], rows: ApiV2Rows ) -> RecordingSimulationService: @@ -908,9 +945,12 @@ def test_a_dry_run_writes_nothing_and_predicts_the_real_run( ) simulation_service = _simulation_service(v2_owner_sessions, stored_rows) service = _service(runtime_sessions, v1_sessions, simulation_service) + read_only_service = _service( + _read_only(runtime_sessions), v1_sessions, simulation_service + ) before = _row_counts(v2_owner_sessions) - dry_run = _migrate(service, stored_rows, apply=False) + dry_run = _migrate(read_only_service, stored_rows, apply=False) assert _row_counts(v2_owner_sessions) == before assert simulation_service.definitions == [] @@ -1152,3 +1192,268 @@ def test_the_sample_takes_at_most_its_size( # API v1 stored no result for this report. assert item.api_v1_budgetary_impact is None assert item.relative_difference is None + + +# Review round 1. + + +def test_a_saved_dynamic_that_cant_take_the_description_fails_its_row_alone( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + # A saved dynamic's description takes at most 10,000 characters, while a + # saved reform's is unbounded. + too_long = _save( + v2_owner_sessions, + UserPolicy, + user_id=stored_rows.first_user, + legacy_policy_id=CTC_REFORM_WITH_ELASTICITY, + description="x" * 10_001, + ) + later = _save( + v2_owner_sessions, + UserPolicy, + user_id=stored_rows.second_user, + legacy_policy_id=CTC_REFORM, + ) + service = _service( + runtime_sessions, + v1_sessions, + _simulation_service(v2_owner_sessions, stored_rows), + ) + + dry_run = _migrate(service, stored_rows, apply=False) + run = _migrate(service, stored_rows) + + for checked in (dry_run, run): + result = _result(checked, too_long) + assert (result.outcome, result.failure_reason) == ( + RowOutcome.FAILED, + FailureReason.SAVED_DYNAMIC_NOT_VALID, + ) + assert _result(run, later).outcome is RowOutcome.MIGRATED + assert _row(v2_owner_sessions, UserPolicy, too_long).policy_id is None + with v2_owner_sessions() as session: + assert ( + session.scalar( + select(func.count()) + .select_from(UserDynamic) + .where(col(UserDynamic.user_id) == stored_rows.first_user) + ) + == 0 + ) + + +def test_a_refused_report_is_asked_for_once_for_all_its_saved_reports( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + saved_rows = [ + _save( + v2_owner_sessions, + UserReportAssociation, + user_id=user_id, + legacy_report_id=HOUSEHOLD_REPORT, + ) + for user_id in (stored_rows.first_user, stored_rows.second_user) + ] + simulation_service = _simulation_service(v2_owner_sessions, stored_rows) + simulation_service.refused.add(ApiV2ReportKind.HOUSEHOLD) + service = _service(runtime_sessions, v1_sessions, simulation_service) + + run = _migrate(service, stored_rows) + + assert len(simulation_service.definitions) == 1 + for row_id in saved_rows: + assert _result(run, row_id).failure_reason is FailureReason.REPORT_REFUSED + assert _row(v2_owner_sessions, UserReportAssociation, row_id).report_id is None + + +def test_an_unexpected_error_fails_its_row_and_the_run_goes_on( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + broken = _save( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=HOUSEHOLD_REPORT, + ) + later = _save( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=ECONOMY_REPORT, + ) + simulation_service = _simulation_service(v2_owner_sessions, stored_rows) + simulation_service.broken.add(ApiV2ReportKind.HOUSEHOLD) + service = _service(runtime_sessions, v1_sessions, simulation_service) + + run = _migrate(service, stored_rows) + + failed = _result(run, broken) + assert (failed.outcome, failed.failure_reason) == ( + RowOutcome.FAILED, + FailureReason.UNEXPECTED_ERROR, + ) + assert failed.failure_detail is not None + assert "RuntimeError" in failed.failure_detail + assert _result(run, later).outcome is RowOutcome.MIGRATED + assert not run.closing_check.passed + + +def test_the_second_mode_drops_missing_parameters_from_both_sides_of_a_report( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + reduced = _save( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=MISSING_PARAMETER_REPORT, + ) + every_parameter_missing = _save( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=EVERY_PARAMETER_MISSING_REPORT, + ) + baseline_missing = _save( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=BASELINE_MISSING_REPORT, + ) + simulation_service = _simulation_service(v2_owner_sessions, stored_rows) + service = _service(runtime_sessions, v1_sessions, simulation_service) + + run = _migrate(service, stored_rows, drop_missing_parameters=True) + + migrated = _result(run, reduced) + assert (migrated.outcome, migrated.dropped_parameters) == ( + RowOutcome.MIGRATED, + (REMOVED_PARAMETER,), + ) + left = _result(run, every_parameter_missing) + # Both sides' missing parameters are listed. + assert (left.outcome, left.missing_parameters) == ( + RowOutcome.EVERY_PARAMETER_MISSING, + (OTHER_REMOVED_PARAMETER, REMOVED_PARAMETER), + ) + assert ( + _row( + v2_owner_sessions, UserReportAssociation, every_parameter_missing + ).report_id + is None + ) + baseline_result = _result(run, baseline_missing) + assert (baseline_result.outcome, baseline_result.dropped_parameters) == ( + RowOutcome.MIGRATED, + (REMOVED_PARAMETER,), + ) + reduced_definition, baseline_definition = simulation_service.definitions + assert reduced_definition.baseline == PolicySide(policy_id=None, dynamic_id=None) + assert reduced_definition.reform is not None + assert reduced_definition.reform.policy_id is not None + assert _policy_values(v2_owner_sessions, reduced_definition.reform.policy_id) == { + (EITC_RATE, 0.4) + } + # The kept part isn't a copy of the API v1 policy, so it gets no mapping. + assert _mapping(v2_owner_sessions, CTC_REFORM_WITH_REMOVED_PARAMETER) is None + ctc_mapping = _mapping(v2_owner_sessions, CTC_REFORM) + assert ctc_mapping is not None + assert baseline_definition.baseline == PolicySide(policy_id=None, dynamic_id=None) + assert baseline_definition.reform == PolicySide( + policy_id=ctc_mapping.policy_id, dynamic_id=None + ) + + +def test_a_saved_report_changed_while_its_report_is_found_is_left_alone( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + saved = _save( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=ECONOMY_REPORT, + ) + simulation_service = _simulation_service(v2_owner_sessions, stored_rows) + + def delete_the_saved_report() -> None: + with v2_owner_sessions.begin() as session: + session.execute( + delete(UserReportAssociation).where( + col(UserReportAssociation.id) == saved + ) + ) + + simulation_service.while_answering = delete_the_saved_report + service = _service(runtime_sessions, v1_sessions, simulation_service) + + run = _migrate(service, stored_rows) + + result = _result(run, saved) + assert (result.outcome, result.failure_reason) == ( + RowOutcome.FAILED, + FailureReason.ROW_CHANGED, + ) + + +def test_saved_reforms_of_one_api_v1_policy_share_its_copy( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + saved_rows = [ + _save( + v2_owner_sessions, + UserPolicy, + user_id=user_id, + legacy_policy_id=CTC_REFORM, + ) + for user_id in (stored_rows.first_user, stored_rows.second_user) + ] + service = _service( + runtime_sessions, + v1_sessions, + _simulation_service(v2_owner_sessions, stored_rows), + ) + + _migrate(service, stored_rows) + + mapping = _mapping(v2_owner_sessions, CTC_REFORM) + assert mapping is not None + assert { + _row(v2_owner_sessions, UserPolicy, row_id).policy_id for row_id in saved_rows + } == {mapping.policy_id} + + +def test_a_policy_mapped_from_another_source_fails_in_the_dry_run_too( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + assert stored_rows.report_catalog is not None + with v2_owner_sessions.begin() as session: + add_row( + session, + LegacyPolicyMapping, + id=uuid4(), + country_id="us", + legacy_policy_id=CTC_REFORM, + policy_id=stored_rows.report_catalog.policy_id, + source_policy_hash="another-source-hash", + ) + saved = _save( + v2_owner_sessions, + UserPolicy, + user_id=stored_rows.first_user, + legacy_policy_id=CTC_REFORM, + ) + service = _service( + runtime_sessions, + v1_sessions, + _simulation_service(v2_owner_sessions, stored_rows), + ) + + dry_run = _migrate(service, stored_rows, apply=False) + run = _migrate(service, stored_rows) + + for checked in (dry_run, run): + result = _result(checked, saved) + assert (result.outcome, result.failure_reason) == ( + RowOutcome.FAILED, + FailureReason.POLICY_NOT_COPYABLE, + ) diff --git a/tests/unit/v2/test_saved_record_migration_rules.py b/tests/unit/v2/test_saved_record_migration_rules.py index 6f5596436..2af520fac 100644 --- a/tests/unit/v2/test_saved_record_migration_rules.py +++ b/tests/unit/v2/test_saved_record_migration_rules.py @@ -20,6 +20,7 @@ from policyengine_api.services.v2.policies.types import LegacyPolicySnapshot from policyengine_api.services.v2.saved_record_migration.transformations import ( api_v2_report_definition, + budget_window_size, closing_check, kept_policy_snapshot, migration_document, @@ -263,6 +264,7 @@ def test_a_v1_report_that_cant_be_rebuilt_is_refused( ("uk", "constituency/E14001063", "constituency/E14001063"), ("uk", "local_authority/Hartlepool", "local_authority/E06000001"), ("uk", "country/wales", "country/wales"), + ("uk", "country/Northern Ireland", "country/northern_ireland"), ("uk", "Wales", "country/wales"), ("uk", "uk", "uk"), ("uk", "", "uk"), @@ -670,3 +672,12 @@ def test_the_document_names_its_kinds_and_says_the_comparison_wasnt_run() -> Non assert document["sample_comparison"] == ( "not run: run the command with --compare-sample N for it" ) + + +@pytest.mark.parametrize( + ("budget_window_years", "size"), [(None, None), (1, None), (2, 2), (10, 10)] +) +def test_only_a_window_of_two_years_or_more_is_a_budget_window( + budget_window_years: int | None, size: int | None +) -> None: + assert budget_window_size(budget_window_years) == size From 45325376cbe0cda688ac92c827d9032528e5e8cc Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:06:48 +0400 Subject: [PATCH 10/22] Fix review round 1's findings in the saved-record migration - A saved reform's saved dynamic is checked before anything is written: one that can't take the saved reform's name or description, such as a description over 10,000 characters, fails its row alone (saved_dynamic_not_valid), in a dry run too. - Any error other than a refusal fails its row (unexpected_error, with the error's type and message), so the run goes on and prints every row's result. - What happens to an API v1 report is worked out once per run and window, whatever its outcome, so a refused report is asked for once for all its saved reports; each saved row is then pointed at it. - A report left because every parameter of its own policy is missing lists both sides' missing parameters. - A dry run checks an existing policy mapping's source hash and a household mapping's fingerprint, as a run's copies do. - A UK nation typed with spaces matches its region. - One rule (budget_window_size) says which saved windows are budget windows, and two docstrings are corrected. Co-Authored-By: Claude Opus 5.5 --- .../saved_record_migration/copies/services.py | 25 ++++ .../v2/saved_record_migration/services.py | 114 +++++++++++------- .../saved_record_migration/transformations.py | 22 +++- .../v2/saved_record_migration/types.py | 14 ++- .../v2/saved_record_migration/validators.py | 38 ++++++ scripts/migrate_saved_records_to_api_v2.py | 6 +- 6 files changed, 160 insertions(+), 59 deletions(-) diff --git a/policyengine_api/services/v2/saved_record_migration/copies/services.py b/policyengine_api/services/v2/saved_record_migration/copies/services.py index 7800d9b5a..fb26d10a9 100644 --- a/policyengine_api/services/v2/saved_record_migration/copies/services.py +++ b/policyengine_api/services/v2/saved_record_migration/copies/services.py @@ -36,6 +36,8 @@ read_legacy_household_mapping, ) from policyengine_api.services.v2.households.transformations import ( + LEGACY_HOUSEHOLD_FINGERPRINT_VERSION, + legacy_household_fingerprint, translate_legacy_household, ) from policyengine_api.services.v2.households.validators import ( @@ -43,6 +45,7 @@ HouseholdValidationError, LegacyHouseholdMappingIntegrityError, LegacyHouseholdTranslationError, + verify_legacy_household_mapping, ) from policyengine_api.services.v2.policies.database_connectors.reads import ( read_legacy_policy_mapping, @@ -58,6 +61,7 @@ LegacyPolicyTranslationError, PolicyCatalogValidationError, PolicyCreationIntegrityError, + verify_legacy_policy_mapping, ) from policyengine_api.services.v2.saved_record_migration.database_connectors.reads import ( # noqa: E501 # a dotted module path cannot be wrapped read_household_default_year, @@ -171,6 +175,11 @@ def plan_policy_in_session( translate_legacy_policy( snapshot, selected=selected, parameters=parameters ) + else: + # A mapping from another source fails the copy, so the plan too. + verify_legacy_policy_mapping( + mapping, source_policy_hash=snapshot.source_policy_hash + ) return PolicyMigrationPlan( snapshot=snapshot, missing_parameters=(), @@ -309,4 +318,20 @@ def household_copy_in_session( legacy_household_id=snapshot.legacy_household_id, lock=False, ) + if mapping is not None: + # A mapping from another source fails the copy, so the dry run too. + try: + verify_legacy_household_mapping( + mapping, + fingerprint_version=LEGACY_HOUSEHOLD_FINGERPRINT_VERSION, + fingerprint_sha256=legacy_household_fingerprint(snapshot), + ) + except HOUSEHOLD_COPY_ERRORS as error: + msg = ( + f"API v1 household {snapshot.legacy_household_id} can't be copied: " + f"{error}" + ) + raise SavedRecordMigrationRefusal( + FailureReason.HOUSEHOLD_NOT_COPYABLE, msg + ) from error return None if mapping is None else mapping.household_id, translated.default_year diff --git a/policyengine_api/services/v2/saved_record_migration/services.py b/policyengine_api/services/v2/saved_record_migration/services.py index 077ccfa35..560c97eba 100644 --- a/policyengine_api/services/v2/saved_record_migration/services.py +++ b/policyengine_api/services/v2/saved_record_migration/services.py @@ -33,7 +33,9 @@ from __future__ import annotations +from dataclasses import replace from typing import TYPE_CHECKING +from uuid import UUID from pydantic import ValidationError @@ -64,6 +66,7 @@ from policyengine_api.services.v2.saved_record_migration.transformations import ( api_v1_budgetary_impact, api_v2_report_definition, + budget_window_size, closing_check, pending_saved_household, pending_saved_reform, @@ -86,6 +89,7 @@ ReportSubmissionUnavailableError, SavedRecordMigrationRefusal, require_catalog_region_code, + saved_dynamic_input, validate_v1_report, ) from policyengine_api.services.v2.stored_reports.economy_results.transformations import ( # noqa: E501 # a dotted module path cannot be wrapped @@ -94,14 +98,10 @@ from policyengine_api.services.v2.stored_reports.economy_results.types import ( EconomyResultUnreadableError, ) -from policyengine_api.services.v2.user_dynamics.types import ( - UserDynamicCreationInput, -) if TYPE_CHECKING: from collections.abc import Callable from contextlib import AbstractContextManager - from uuid import UUID from sqlmodel import Session @@ -124,9 +124,6 @@ V1ReportDefinition, ) -# A saved report's window of one year is the report itself. -_SHORTEST_BUDGET_WINDOW = 2 - def _refusal(reason: FailureReason, message: str) -> SavedRecordMigrationRefusal: return SavedRecordMigrationRefusal(reason, message) @@ -160,6 +157,16 @@ def _result( # noqa: PLR0913 # the record and outcome, then each optional fiel ) +def _unexpected(record: PendingSavedRecord, error: Exception) -> SavedRecordResult: + """Return the result of a row an unexpected error failed; it keeps its reference.""" + return _result( + record, + RowOutcome.FAILED, + failure_reason=FailureReason.UNEXPECTED_ERROR, + failure_detail=f"{type(error).__name__}: {error}", + ) + + def _left_for_missing_parameters( record: PendingSavedRecord, plan: PolicyMigrationPlan, @@ -183,7 +190,7 @@ def _left_for_missing_parameters( return _result( record, RowOutcome.EVERY_PARAMETER_MISSING, - missing_parameters=plan.missing_parameters, + missing_parameters=missing_parameters, ) return None @@ -369,6 +376,8 @@ def _migrate_record( failure_reason=refusal.reason, failure_detail=str(refusal), ) + except Exception as error: # noqa: BLE001 # recorded on its row, so the run still prints every row's result + return _unexpected(record, error) def _session(self, options: MigrationOptions) -> AbstractContextManager[Session]: """Open a transaction that commits for a run, or a read for a dry run.""" @@ -403,6 +412,11 @@ def _migrate_saved_reform( ) if left is not None: return left + if plan.sets_dynamic_values: + # The saved dynamic the assumptions get must take the saved + # reform's name and description; the copy's ID isn't known + # yet, so a placeholder stands for it. + saved_dynamic_input(record, plan.existing_dynamic_id or UUID(int=0)) if not options.apply: return _result( record, @@ -427,16 +441,7 @@ def _migrate_saved_reform( None if stored.dynamic_id is None else create_user_dynamic_in_session( - session, - UserDynamicCreationInput.model_validate( - { - "country_id": record.country_id, - "user_id": record.user_id, - "dynamic_id": stored.dynamic_id, - "name": record.name, - "description": record.description, - } - ), + session, saved_dynamic_input(record, stored.dynamic_id) ).id ) return _result( @@ -591,32 +596,52 @@ def _migrate_saved_report( options: MigrationOptions, reports_this_run: dict[tuple[str, int, int | None], SavedRecordResult], ) -> SavedRecordResult: + """Give a saved report its API v1 report's report, found once per run. + + What happens to the report doesn't depend on the saved row, so it is + worked out once for each API v1 report and window in a run, whatever + its outcome, and only then is each saved row of it pointed at the + report. + """ + window = budget_window_size(record.budget_window_years) + report_key = (record.country_id, record.legacy_id, window) + report = reports_this_run.get(report_key) + if report is None: + try: + report = self._report_of(record, options, window) + except SavedRecordMigrationRefusal as refusal: + report = _result( + record, + RowOutcome.FAILED, + failure_reason=refusal.reason, + failure_detail=str(refusal), + ) + except Exception as error: # noqa: BLE001 # recorded for every saved report of it, so the run goes on + report = _unexpected(record, error) + reports_this_run[report_key] = report + if ( + options.apply + and report.outcome is RowOutcome.MIGRATED + and report.api_v2_id is not None + ): + self._point_saved_report(record, report.api_v2_id) + return replace(report, row_id=record.row_id) + + def _report_of( + self, record: PendingSavedRecord, options: MigrationOptions, window: int | None + ) -> SavedRecordResult: + """Find or create the report of the saved report's API v1 report. + + Its copies are committed before the simulation service is asked for + the report. The result names the report, or why there is none; it + doesn't point the saved row at it. + """ from policyengine_api.services.v2.saved_record_migration.copies.services import ( # noqa: E501 # a dotted module path cannot be wrapped household_copy_in_session, plan_policy_in_session, report_side_in_session, ) - window = record.budget_window_years - report_key = ( - record.country_id, - record.legacy_id, - window - if window is not None and window >= _SHORTEST_BUDGET_WINDOW - else None, - ) - earlier = reports_this_run.get(report_key) - if earlier is not None: - # Another saved report of the same API v1 report, migrated by this run. - if options.apply and earlier.api_v2_id is not None: - self._point_saved_report(record, earlier.api_v2_id) - return _result( - record, - RowOutcome.MIGRATED, - api_v2_id=earlier.api_v2_id, - dropped_parameters=earlier.dropped_parameters, - notes=earlier.notes, - ) definition, snapshots, household = self._v1_report(record) region_code = ( require_catalog_region_code( @@ -681,9 +706,8 @@ def _migrate_saved_report( if household is not None and household_year != definition.year else () ) - report_id = None - if options.apply: - report_id = self._report_id( + report_id = ( + self._report_id( api_v2_report_definition( definition, baseline=sides[definition.baseline_policy_id], @@ -697,13 +721,13 @@ def _migrate_saved_report( budget_window_years=window, ) ) - self._point_saved_report(record, report_id) - result = _result( + if options.apply + else None + ) + return _result( record, RowOutcome.MIGRATED, api_v2_id=report_id, dropped_parameters=missing, notes=notes, ) - reports_this_run[report_key] = result - return result diff --git a/policyengine_api/services/v2/saved_record_migration/transformations.py b/policyengine_api/services/v2/saved_record_migration/transformations.py index b474b0d97..baa1d4457 100644 --- a/policyengine_api/services/v2/saved_record_migration/transformations.py +++ b/policyengine_api/services/v2/saved_record_migration/transformations.py @@ -139,6 +139,17 @@ def kept_policy_snapshot( return snapshot.model_copy(update={"policy_json": kept}) +def budget_window_size(budget_window_years: int | None) -> int | None: + """Return a saved report's budget window, or None when it isn't one. + + A saved window of one year is the report itself, so only two years or + more make a budget window. + """ + if budget_window_years is None or budget_window_years < _SHORTEST_BUDGET_WINDOW: + return None + return budget_window_years + + def api_v2_report_definition( # noqa: PLR0913 # the API v1 definition, then each part the copies give definition: V1ReportDefinition, *, @@ -165,18 +176,17 @@ def api_v2_report_definition( # noqa: PLR0913 # the API v1 definition, then ea budget_window_size=None, household_id=household_id, ) - is_window = ( - budget_window_years is not None - and budget_window_years >= _SHORTEST_BUDGET_WINDOW - ) + window = budget_window_size(budget_window_years) return ApiV2ReportDefinition( country_id=definition.country_id, - kind=(ApiV2ReportKind.BUDGET_WINDOW if is_window else ApiV2ReportKind.ECONOMY), + kind=( + ApiV2ReportKind.ECONOMY if window is None else ApiV2ReportKind.BUDGET_WINDOW + ), baseline=baseline, reform=reform, year=definition.year, region_code=region_code, - budget_window_size=budget_window_years if is_window else None, + budget_window_size=window, household_id=None, ) diff --git a/policyengine_api/services/v2/saved_record_migration/types.py b/policyengine_api/services/v2/saved_record_migration/types.py index 6a1402e35..17b1c0887 100644 --- a/policyengine_api/services/v2/saved_record_migration/types.py +++ b/policyengine_api/services/v2/saved_record_migration/types.py @@ -60,6 +60,8 @@ class FailureReason(StrEnum): REPORT_REFUSED = "report_refused" SIMULATION_SERVICE_UNAVAILABLE = "simulation_service_unavailable" ROW_CHANGED = "row_changed" + SAVED_DYNAMIC_NOT_VALID = "saved_dynamic_not_valid" + UNEXPECTED_ERROR = "unexpected_error" class V1ReportKind(StrEnum): @@ -244,11 +246,13 @@ class SavedRecordResult: """What a run did with one saved record. ``api_v2_id`` is the policy, report or household ID the row now - holds; in a dry run, the existing copy it would hold, or None when the run - would make a new one. ``missing_parameters`` lists the parameters the - running catalog lacks of a row left for them, and ``dropped_parameters`` - those the second mode left out of a row it migrated. ``notes`` hold facts - about a migrated row a reviewer should see. + holds. In a dry run it is the existing copy a saved reform or saved + household would hold, or None when a run would make a new one, and None + for a saved report, whose report only a run asks for. + ``missing_parameters`` lists the parameters the running catalog lacks of a + row left for them, and ``dropped_parameters`` those the second mode left + out of a row it migrated. ``notes`` hold facts about a migrated row a + reviewer should see. """ kind: SavedRecordKind diff --git a/policyengine_api/services/v2/saved_record_migration/validators.py b/policyengine_api/services/v2/saved_record_migration/validators.py index 0c73f3cf5..2b2025597 100644 --- a/policyengine_api/services/v2/saved_record_migration/validators.py +++ b/policyengine_api/services/v2/saved_record_migration/validators.py @@ -13,17 +13,24 @@ from typing import TYPE_CHECKING +from pydantic import ValidationError + from policyengine_api.services.v2.saved_record_migration.types import ( FailureReason, V1ReportDefinition, V1ReportKind, ) +from policyengine_api.services.v2.user_dynamics.types import ( + UserDynamicCreationInput, +) if TYPE_CHECKING: from collections.abc import Iterable + from uuid import UUID from policyengine_api.data.v2.catalog.region_references import RegionReference from policyengine_api.services.v2.saved_record_migration.types import ( + PendingSavedRecord, V1ReportRecord, V1SimulationRecord, ) @@ -157,6 +164,34 @@ def validate_v1_report( ) +def saved_dynamic_input( + record: PendingSavedRecord, dynamic_id: UUID +) -> UserDynamicCreationInput: + """Return the saved dynamic a saved reform's model assumptions get. + + It has the saved reform's owner, country, name and description. Raise + SavedRecordMigrationRefusal (``saved_dynamic_not_valid``) when a saved + dynamic can't take them, such as a description over 10,000 characters, + which a saved reform's unbounded description may be. + """ + try: + return UserDynamicCreationInput.model_validate( + { + "country_id": record.country_id, + "user_id": record.user_id, + "dynamic_id": dynamic_id, + "name": record.name, + "description": record.description, + } + ) + except ValidationError as error: + fields = ", ".join(str(detail["loc"][0]) for detail in error.errors()) + msg = f"a saved dynamic can't take the saved reform's {fields}" + raise SavedRecordMigrationRefusal( + FailureReason.SAVED_DYNAMIC_NOT_VALID, msg + ) from error + + def _spelled_as_v1_matches(country_id: str, v1_region: str) -> str: """Spell an API v1 region as API v1 normalised it before running it. @@ -169,6 +204,9 @@ def _spelled_as_v1_matches(country_id: str, v1_region: str) -> str: if region == "": return _NATIONAL_REGIONS[country_id] if "/" in region: + region_type, _, value = region.partition("/") + if country_id == "uk" and region_type.lower() == "country": + return f"country/{value.strip().lower().replace(' ', '_')}" return region if country_id == "uk" and region.lower() != "uk": return f"country/{region.lower().replace(' ', '_')}" diff --git a/scripts/migrate_saved_records_to_api_v2.py b/scripts/migrate_saved_records_to_api_v2.py index a06dc9112..da408b1fc 100755 --- a/scripts/migrate_saved_records_to_api_v2.py +++ b/scripts/migrate_saved_records_to_api_v2.py @@ -30,8 +30,8 @@ oldest N rows of each kind, and ``--user-id`` to those owners' rows. The closing check covers the same rows. - ``--compare-sample N`` migrates nothing: it prints API v1's stored - budgetary impact next to the newest successful run's for N migrated - economy reports, starts no run and exits 0. + budgetary impact next to the newest successful run's for up to N + migrated economy reports, starts no run and exits 0. It prints one JSON document: counts of each kind's rows by outcome, every row's result (the API v2 ID it now holds, or why not), and the closing @@ -226,7 +226,7 @@ def _parser() -> argparse.ArgumentParser: metavar="N", help=( "Migrate nothing: print API v1's stored budgetary impact next to the " - "newest successful run's for N migrated economy reports" + "newest successful run's for up to N migrated economy reports" ), ) parser.add_argument( From de660ac1c5df7f148ab815133dbe05cf84e061c3 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:19:34 +0400 Subject: [PATCH 11/22] Add failing tests for review round 2's quality findings - A run without a client for the simulation service fails each saved report as simulation_service_unavailable before writing anything for it. - An unexpected error keeps only its type and first line, so no row's contents reach the output. - CI also runs the failures' integration tests. Tests for an unexpected error in a saved household, an unexpected report error met once for all its saved reports, and a read-only dry run of the second mode over household, budget-window and missing-parameter reports pass already and add coverage. The integration tests are split, under the test file length limit, into saved_record_migration_support (rows, the stand-in for the simulation service and helpers) and two test modules; the tests themselves don't change. Co-Authored-By: Claude Opus 5.5 --- .../saved_record_migration_support.py | 566 +++++++++ .../test_v2_saved_record_migration.py | 1074 +++-------------- ...test_v2_saved_record_migration_failures.py | 499 ++++++++ tests/unit/test_v2_integration_workflow.py | 15 +- 4 files changed, 1244 insertions(+), 910 deletions(-) create mode 100644 tests/integration/saved_record_migration_support.py create mode 100644 tests/integration/test_v2_saved_record_migration_failures.py diff --git a/tests/integration/saved_record_migration_support.py b/tests/integration/saved_record_migration_support.py new file mode 100644 index 000000000..ad5b26527 --- /dev/null +++ b/tests/integration/saved_record_migration_support.py @@ -0,0 +1,566 @@ +"""Rows, stand-ins and helpers of the saved-record migration's integration tests. + +API v1's rows are in MySQL and API v2's tables in PostgreSQL, where the +command runs as API v1's runtime role, as it does in staging and production. +A stand-in for the simulation service records each report definition it is +sent and stores a report row for it, as the simulation service would, after +checking that the policies, dynamics and household the definition names are +already committed. The test modules wrap ``runtime_role_sessions`` and +``stored_rows_in`` in fixtures. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import TYPE_CHECKING +from uuid import UUID, uuid4 + +from sqlalchemy import delete, func, select +from sqlmodel import col + +from policyengine_api.data.v1_models import Household as V1Household +from policyengine_api.data.v1_models import Policy as V1Policy +from policyengine_api.data.v1_models import ReportOutput as V1ReportOutput +from policyengine_api.data.v1_models import ReportOutputRun as V1ReportOutputRun +from policyengine_api.data.v1_models import Simulation as V1Simulation +from policyengine_api.data.v2.database import build_v2_session_factory +from policyengine_api.data.v2.models import ( + Dynamic, + DynamicParameter, + DynamicParameterValue, + Household, + LegacyHouseholdMapping, + LegacyPolicyMapping, + Parameter, + ParameterValue, + Policy, + TaxBenefitModel, + TaxBenefitModelVersion, + User, + UserDynamic, + UserHouseholdAssociation, + UserPolicy, + UserReportAssociation, + UserSimulationAssociation, +) +from policyengine_api.services.v2.saved_record_migration.database_session import ( + SavedRecordMigrationDatabaseSession, + V1RecordDatabaseSession, +) +from policyengine_api.services.v2.saved_record_migration.services import ( + V2SavedRecordMigrationService, +) +from policyengine_api.services.v2.saved_record_migration.types import ( + ApiV2ReportDefinition, + ApiV2ReportKind, + MigrationOptions, + MigrationRun, + SavedRecordKind, +) +from policyengine_api.services.v2.saved_record_migration.validators import ( + ReportSubmissionRefusedError, +) +from tests.integration.simulation_rows import add_row +from tests.integration.stored_report_rows import ( + CatalogRows, + delete_catalog, + store_catalog, + store_report, +) + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + + from sqlalchemy.orm import Session as OrmSession + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + from tests.integration.conftest import ManagedV2Roles + +# A catalog version of its own, so it meets no other test's catalog. +RUNNING_VERSION = "940.1.0" +CTC_AMOUNT = "gov.irs.credits.ctc.amount.base" +EITC_RATE = "gov.irs.credits.eitc.phase_in_rate" +INCOME_ELASTICITY = "gov.simulation.labor_supply_responses.elasticities.income" +REMOVED_PARAMETER = "gov.simulation.reported_snap" +OTHER_REMOVED_PARAMETER = "gov.irs.credits.eitc.removed_rate" +PERIOD = "2026-01-01.2100-12-31" +REFUSAL_CODE = "unknown_household" +# What a database error's second line holds: the statement and the row's values. +ROW_CONTENTS = "[parameters: {'household_json': 'a person's details'}]" + +# API v1 IDs, chosen high so they don't meet other tests' rows. +CURRENT_LAW = 940_100 +CTC_REFORM = 940_101 +CTC_REFORM_WITH_ELASTICITY = 940_102 +CTC_REFORM_WITH_REMOVED_PARAMETER = 940_103 +ONLY_REMOVED_PARAMETER = 940_104 +EITC_REFORM_WITH_OTHER_REMOVED_PARAMETER = 940_105 +V1_HOUSEHOLD = 940_501 +ECONOMY_REPORT = 940_301 +HOUSEHOLD_REPORT = 940_303 +MISSING_PARAMETER_REPORT = 940_304 +UNKNOWN_REGION_REPORT = 940_305 +EVERY_PARAMETER_MISSING_REPORT = 940_306 +BASELINE_MISSING_REPORT = 940_307 +SAVED_SIMULATION = 940_211 +V1_POLICIES = { + CURRENT_LAW: {}, + CTC_REFORM: {CTC_AMOUNT: {PERIOD: 3000}}, + CTC_REFORM_WITH_ELASTICITY: { + CTC_AMOUNT: {PERIOD: 3500}, + INCOME_ELASTICITY: {PERIOD: 0.1}, + }, + CTC_REFORM_WITH_REMOVED_PARAMETER: { + EITC_RATE: {PERIOD: 0.4}, + REMOVED_PARAMETER: {PERIOD: True}, + }, + ONLY_REMOVED_PARAMETER: {REMOVED_PARAMETER: {PERIOD: True}}, + EITC_REFORM_WITH_OTHER_REMOVED_PARAMETER: { + EITC_RATE: {PERIOD: 0.3}, + OTHER_REMOVED_PARAMETER: {PERIOD: 0.1}, + }, +} +# Each API v1 simulation: its population type, population and policy. +V1_SIMULATIONS = { + 940_201: ("geography", "us", CURRENT_LAW), + 940_202: ("geography", "us", CTC_REFORM_WITH_ELASTICITY), + 940_203: ("household", str(V1_HOUSEHOLD), CURRENT_LAW), + 940_204: ("household", str(V1_HOUSEHOLD), CTC_REFORM), + 940_205: ("geography", "us", CTC_REFORM_WITH_REMOVED_PARAMETER), + 940_206: ("geography", "state/zz", CURRENT_LAW), + 940_207: ("geography", "state/zz", CTC_REFORM), + 940_208: ("geography", "us", ONLY_REMOVED_PARAMETER), + 940_209: ("geography", "us", EITC_REFORM_WITH_OTHER_REMOVED_PARAMETER), + 940_210: ("geography", "us", CTC_REFORM), +} +# Each API v1 report output: its two simulations. +V1_REPORTS = { + ECONOMY_REPORT: (940_201, 940_202), + HOUSEHOLD_REPORT: (940_203, 940_204), + MISSING_PARAMETER_REPORT: (940_201, 940_205), + UNKNOWN_REGION_REPORT: (940_206, 940_207), + # A reform whose every parameter is missing, compared with a baseline + # that sets one that still exists and another that is missing. + EVERY_PARAMETER_MISSING_REPORT: (940_209, 940_208), + # A baseline whose every parameter is missing, and a reform that is whole. + BASELINE_MISSING_REPORT: (940_208, 940_210), +} + + +def _household_document() -> dict[str, object]: + members = {"members": ["adult"]} + return { + "people": {"adult": {"age": {"2026": 41}}}, + "households": {"home": members}, + "families": {"family": members}, + "tax_units": {"tax unit": members}, + "spm_units": {"spm unit": members}, + "marital_units": {"marital unit": members}, + } + + +def _store_v1_records(v1_sessions: sessionmaker[OrmSession]) -> None: + _delete_v1_records(v1_sessions) + with v1_sessions.begin() as session: + for policy_id, policy_json in V1_POLICIES.items(): + session.add( + V1Policy( + id=policy_id, + country_id="us", + label=f"API v1 policy {policy_id}", + api_version="1.0.0", + policy_json=policy_json, + policy_hash=f"d4-1-hash-{policy_id}", + ) + ) + session.add( + V1Household( + id=V1_HOUSEHOLD, + country_id="us", + label="API v1 household", + api_version="1.0.0", + household_json=_household_document(), + household_hash="d4-1-household-hash", + ) + ) + for simulation_id, (kind, population, policy_id) in V1_SIMULATIONS.items(): + session.add( + V1Simulation( + id=simulation_id, + country_id="us", + api_version="1.0.0", + population_type=kind, + population_id=population, + policy_id=policy_id, + ) + ) + for report_id, (first, second) in V1_REPORTS.items(): + session.add( + V1ReportOutput( + id=report_id, + country_id="us", + simulation_1_id=first, + simulation_2_id=second, + api_version="1.0.0", + year="2026", + ) + ) + + +def _delete_v1_records(v1_sessions: sessionmaker[OrmSession]) -> None: + with v1_sessions.begin() as session: + session.execute( + delete(V1ReportOutputRun).where( + V1ReportOutputRun.report_output_id.in_(list(V1_REPORTS)) + ) + ) + session.execute( + delete(V1ReportOutput).where(V1ReportOutput.id.in_(list(V1_REPORTS))) + ) + session.execute( + delete(V1Simulation).where(V1Simulation.id.in_(list(V1_SIMULATIONS))) + ) + session.execute(delete(V1Household).where(V1Household.id == V1_HOUSEHOLD)) + session.execute(delete(V1Policy).where(V1Policy.id.in_(list(V1_POLICIES)))) + + +@dataclass +class ApiV2Rows: + """The rows each test stores in the API v2 tables, to delete after.""" + + model_id: UUID + created_model: bool + version_id: UUID + first_user: UUID + second_user: UUID + report_catalog: CatalogRows | None = None + + +@dataclass +class RecordingSimulationService: + """Stands in for the simulation service's find-or-create of reports by key. + + Each definition gets one report row, stored as the database's owner, and + the same definition gets the same report again. ``refused`` lists the + kinds of definition it refuses, as the simulation service answers 400, + and ``broken`` those it fails on with an error the migration doesn't + expect. ``while_answering`` runs before it answers, as a user's change + to a saved row would. + """ + + owner_sessions: sessionmaker[Session] + catalog: CatalogRows + definitions: list[ApiV2ReportDefinition] = field(default_factory=list) + reports: dict[ApiV2ReportDefinition, UUID] = field(default_factory=dict) + refused: set[ApiV2ReportKind] = field(default_factory=set) + broken: set[ApiV2ReportKind] = field(default_factory=set) + while_answering: Callable[[], None] | None = None + + def find_or_create_report(self, definition: ApiV2ReportDefinition) -> UUID: + self.definitions.append(definition) + with self.owner_sessions() as session: + # The simulation service reads what the definition names itself, + # so it must already be committed. + for side in (definition.baseline, definition.reform): + if side is not None and side.policy_id is not None: + assert session.get(Policy, side.policy_id) is not None + if side is not None and side.dynamic_id is not None: + assert session.get(Dynamic, side.dynamic_id) is not None + if definition.household_id is not None: + assert session.get(Household, definition.household_id) is not None + if definition.kind in self.refused: + message = "the simulation service refused the household report" + raise ReportSubmissionRefusedError(REFUSAL_CODE, message) + if definition.kind in self.broken: + message = f"the stand-in simulation service broke\n{ROW_CONTENTS}" + raise RuntimeError(message) + if self.while_answering is not None: + self.while_answering() + if definition not in self.reports: + with self.owner_sessions.begin() as session: + self.reports[definition] = store_report(session, self.catalog).report_id + return self.reports[definition] + + +def runtime_role_sessions( + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], + managed_v2_roles: ManagedV2Roles, +) -> sessionmaker[Session]: + return v2_sessions_as_role(managed_v2_roles.runtime) + + +def stored_rows_in( + v1_sessions: sessionmaker[OrmSession], + v2_owner_sessions: sessionmaker[Session], +) -> Iterator[ApiV2Rows]: + _store_v1_records(v1_sessions) + with v2_owner_sessions.begin() as session: + model_id = session.scalar( + select(TaxBenefitModel.id).where( + col(TaxBenefitModel.name) == "policyengine-us" + ) + ) + created_model = model_id is None + if model_id is None: + model_id = uuid4() + add_row(session, TaxBenefitModel, id=model_id, name="policyengine-us") + version_id = uuid4() + add_row( + session, + TaxBenefitModelVersion, + id=version_id, + model_id=model_id, + version=RUNNING_VERSION, + current_law_id=1, + metadata_time_periods=[2026], + ) + for name in (CTC_AMOUNT, EITC_RATE): + add_row( + session, + Parameter, + id=uuid4(), + name=name, + tax_benefit_model_version_id=version_id, + ) + add_row( + session, + DynamicParameter, + id=uuid4(), + name=INCOME_ELASTICITY, + tax_benefit_model_version_id=version_id, + ) + rows = ApiV2Rows( + model_id=model_id, + created_model=created_model, + version_id=version_id, + first_user=uuid4(), + second_user=uuid4(), + ) + for user_id in (rows.first_user, rows.second_user): + add_row(session, User, id=user_id, primary_country="us") + rows.report_catalog = store_catalog(session, "us") + try: + yield rows + finally: + _delete_api_v2_rows(v2_owner_sessions, rows) + _delete_v1_records(v1_sessions) + + +def _delete_api_v2_rows(owner_sessions: sessionmaker[Session], rows: ApiV2Rows) -> None: + users = [rows.first_user, rows.second_user] + with owner_sessions.begin() as session: + for model in ( + UserReportAssociation, + UserSimulationAssociation, + UserHouseholdAssociation, + UserDynamic, + UserPolicy, + ): + session.execute(delete(model).where(col(model.user_id).in_(users))) + session.execute(delete(User).where(col(User.id).in_(users))) + session.execute( + delete(LegacyPolicyMapping).where( + col(LegacyPolicyMapping.legacy_policy_id).in_(list(V1_POLICIES)) + ) + ) + # The household copy is deleted after its mapping, which names it. + households = list( + session.scalars( + select(LegacyHouseholdMapping.household_id).where( + col(LegacyHouseholdMapping.legacy_household_id) == V1_HOUSEHOLD + ) + ) + ) + session.execute( + delete(LegacyHouseholdMapping).where( + col(LegacyHouseholdMapping.legacy_household_id) == V1_HOUSEHOLD + ) + ) + if rows.report_catalog is not None: + delete_catalog(session, rows.report_catalog) + version_policies = select(Policy.id).where( + col(Policy.tax_benefit_model_version_id) == rows.version_id + ) + version_dynamics = select(Dynamic.id).where( + col(Dynamic.tax_benefit_model_version_id) == rows.version_id + ) + session.execute( + delete(ParameterValue).where( + col(ParameterValue.policy_id).in_(version_policies) + ) + ) + session.execute( + delete(DynamicParameterValue).where( + col(DynamicParameterValue.dynamic_id).in_(version_dynamics) + ) + ) + session.execute( + delete(Policy).where( + col(Policy.tax_benefit_model_version_id) == rows.version_id + ) + ) + session.execute( + delete(Dynamic).where( + col(Dynamic.tax_benefit_model_version_id) == rows.version_id + ) + ) + session.execute(delete(Household).where(col(Household.id).in_(households))) + session.execute( + delete(TaxBenefitModelVersion).where( + col(TaxBenefitModelVersion.id) == rows.version_id + ) + ) + if rows.created_model: + session.execute( + delete(TaxBenefitModel).where(col(TaxBenefitModel.id) == rows.model_id) + ) + + +def save_row( + owner_sessions: sessionmaker[Session], model: type, **values: object +) -> UUID: + row_id = uuid4() + with owner_sessions.begin() as session: + add_row(session, model, id=row_id, country_id="us", **values) + return row_id + + +def migration_service( + runtime_sessions: sessionmaker[Session], + v1_sessions: sessionmaker[OrmSession], + simulation_service: RecordingSimulationService, +) -> V2SavedRecordMigrationService: + return V2SavedRecordMigrationService( + SavedRecordMigrationDatabaseSession(runtime_sessions), + V1RecordDatabaseSession(v1_sessions), + report_submitter=simulation_service, + running_policyengine_version=RUNNING_VERSION, + ) + + +def read_only_sessions(sessions: sessionmaker[Session]) -> sessionmaker[Session]: + """Return the same role's sessions with every transaction READ ONLY. + + The command opens a dry run's sessions this way, so PostgreSQL refuses + any write it tried. + """ + engine = sessions.kw["bind"] + return build_v2_session_factory(engine.execution_options(postgresql_readonly=True)) + + +def simulation_service_for( + owner_sessions: sessionmaker[Session], rows: ApiV2Rows +) -> RecordingSimulationService: + assert rows.report_catalog is not None + return RecordingSimulationService(owner_sessions, rows.report_catalog) + + +def migrate( + service: V2SavedRecordMigrationService, + rows: ApiV2Rows, + **options: object, +) -> MigrationRun: + return service.migrate( + MigrationOptions( + user_ids=(rows.first_user, rows.second_user), + **{"apply": True, **options}, + ) + ) + + +def result_of(run: MigrationRun, row_id: UUID): + (result,) = [result for result in run.results if result.row_id == row_id] + return result + + +def remaining_of(run: MigrationRun, kind: SavedRecordKind): + (remaining,) = [item for item in run.closing_check.remaining if item.kind is kind] + return remaining + + +def policy_values(owner_sessions: sessionmaker[Session], policy_id: UUID) -> set: + with owner_sessions() as session: + return set( + session.execute( + select(Parameter.name, ParameterValue.value_json) + .join(Parameter, col(Parameter.id) == col(ParameterValue.parameter_id)) + .where(col(ParameterValue.policy_id) == policy_id) + ).all() + ) + + +def dynamic_values(owner_sessions: sessionmaker[Session], dynamic_id: UUID) -> set: + with owner_sessions() as session: + return set( + session.execute( + select(DynamicParameter.name, DynamicParameterValue.value_json) + .join( + DynamicParameter, + col(DynamicParameter.id) + == col(DynamicParameterValue.dynamic_parameter_id), + ) + .where(col(DynamicParameterValue.dynamic_id) == dynamic_id) + ).all() + ) + + +def policy_mapping(owner_sessions: sessionmaker[Session], legacy_policy_id: int): + with owner_sessions() as session: + return session.scalar( + select(LegacyPolicyMapping).where( + col(LegacyPolicyMapping.legacy_policy_id) == legacy_policy_id + ) + ) + + +def stored_row(owner_sessions: sessionmaker[Session], model: type, row_id: UUID): + with owner_sessions() as session: + row = session.get(model, row_id) + session.expunge_all() + return row + + +def row_counts(owner_sessions: sessionmaker[Session]) -> dict[str, int]: + with owner_sessions() as session: + return { + model.__name__: session.scalar(select(func.count()).select_from(model)) + for model in ( + Policy, + Dynamic, + Household, + LegacyPolicyMapping, + LegacyHouseholdMapping, + UserDynamic, + ) + } + + +RUN_VERSIONS = {"country_package_version": "2.2.2", "policyengine_version": "6.20.0"} + + +def store_v1_result( + v1_sessions: sessionmaker[OrmSession], + report_id: int, + *, + budgetary_impact: float, + country_package_version: str, +) -> None: + """Give an API v1 report output a stored result from a run on a package version.""" + run_id = str(uuid4()) + with v1_sessions.begin() as session: + session.add( + V1ReportOutputRun( + id=run_id, + report_output_id=report_id, + run_sequence=1, + status="complete", + trigger_type="initial", + country_package_version=country_package_version, + ) + ) + report = session.get(V1ReportOutput, report_id) + assert report is not None + report.output = {"budget": {"budgetary_impact": budgetary_impact}} + report.status = "complete" + report.latest_successful_run_id = run_id diff --git a/tests/integration/test_v2_saved_record_migration.py b/tests/integration/test_v2_saved_record_migration.py index 1a9e6640a..51fc320de 100644 --- a/tests/integration/test_v2_saved_record_migration.py +++ b/tests/integration/test_v2_saved_record_migration.py @@ -1,75 +1,70 @@ """The one-time migration of saved records' API v1 references (D4 · 1). -API v1's rows are in MySQL and the API v2 tables in PostgreSQL, where the -command runs as API v1's runtime role, as it does in staging and production. -A stand-in for the simulation service records each report definition it is -sent and stores a report row for it, as the simulation service would, after -checking that the policies, dynamics and household the definition names are -already committed. +Saved reforms, households, reports and simulations, dry runs, running again, +the kind filter and the sample comparison. The rows, the stand-in for the +simulation service and the helpers are in ``saved_record_migration_support``. """ from __future__ import annotations -from dataclasses import dataclass, field from typing import TYPE_CHECKING -from uuid import UUID, uuid4 import pytest -from sqlalchemy import delete, func, select +from sqlalchemy import select from sqlmodel import col -from policyengine_api.data.v1_models import Household as V1Household -from policyengine_api.data.v1_models import Policy as V1Policy -from policyengine_api.data.v1_models import ReportOutput as V1ReportOutput -from policyengine_api.data.v1_models import ReportOutputRun as V1ReportOutputRun -from policyengine_api.data.v1_models import Simulation as V1Simulation -from policyengine_api.data.v2.database import build_v2_session_factory from policyengine_api.data.v2.models import ( - Dynamic, - DynamicParameter, - DynamicParameterValue, - Household, LegacyHouseholdMapping, - LegacyPolicyMapping, - Parameter, - ParameterValue, - Policy, - TaxBenefitModel, - TaxBenefitModelVersion, - User, UserDynamic, UserHouseholdAssociation, UserPolicy, UserReportAssociation, UserSimulationAssociation, ) -from policyengine_api.services.v2.saved_record_migration.database_session import ( - SavedRecordMigrationDatabaseSession, - V1RecordDatabaseSession, -) -from policyengine_api.services.v2.saved_record_migration.services import ( - V2SavedRecordMigrationService, -) from policyengine_api.services.v2.saved_record_migration.types import ( ApiV2ReportDefinition, ApiV2ReportKind, FailureReason, - MigrationOptions, - MigrationRun, PolicySide, RowOutcome, SavedRecordKind, ) -from policyengine_api.services.v2.saved_record_migration.validators import ( - ReportSubmissionRefusedError, -) from tests.fixtures.economy_results import us_economy_result -from tests.integration.simulation_rows import add_row +from tests.integration.saved_record_migration_support import ( + CTC_AMOUNT, + CTC_REFORM, + CTC_REFORM_WITH_ELASTICITY, + CTC_REFORM_WITH_REMOVED_PARAMETER, + ECONOMY_REPORT, + EITC_RATE, + HOUSEHOLD_REPORT, + INCOME_ELASTICITY, + MISSING_PARAMETER_REPORT, + ONLY_REMOVED_PARAMETER, + REMOVED_PARAMETER, + RUN_VERSIONS, + SAVED_SIMULATION, + UNKNOWN_REGION_REPORT, + V1_HOUSEHOLD, + ApiV2Rows, + dynamic_values, + migrate, + migration_service, + policy_mapping, + policy_values, + read_only_sessions, + remaining_of, + result_of, + row_counts, + runtime_role_sessions, + save_row, + simulation_service_for, + store_v1_result, + stored_row, + stored_rows_in, +) from tests.integration.stored_report_rows import ( - CatalogRows, RunSettings, - delete_catalog, - store_catalog, store_report, store_report_run, ) @@ -83,216 +78,13 @@ from tests.integration.conftest import ManagedV2Roles -# A catalog version of its own, so it meets no other test's catalog. -RUNNING_VERSION = "940.1.0" -CTC_AMOUNT = "gov.irs.credits.ctc.amount.base" -EITC_RATE = "gov.irs.credits.eitc.phase_in_rate" -INCOME_ELASTICITY = "gov.simulation.labor_supply_responses.elasticities.income" -REMOVED_PARAMETER = "gov.simulation.reported_snap" -OTHER_REMOVED_PARAMETER = "gov.irs.credits.eitc.removed_rate" -PERIOD = "2026-01-01.2100-12-31" -REFUSAL_CODE = "unknown_household" - -# API v1 IDs, chosen high so they don't meet other tests' rows. -CURRENT_LAW = 940_100 -CTC_REFORM = 940_101 -CTC_REFORM_WITH_ELASTICITY = 940_102 -CTC_REFORM_WITH_REMOVED_PARAMETER = 940_103 -ONLY_REMOVED_PARAMETER = 940_104 -EITC_REFORM_WITH_OTHER_REMOVED_PARAMETER = 940_105 -V1_HOUSEHOLD = 940_501 -ECONOMY_REPORT = 940_301 -HOUSEHOLD_REPORT = 940_303 -MISSING_PARAMETER_REPORT = 940_304 -UNKNOWN_REGION_REPORT = 940_305 -EVERY_PARAMETER_MISSING_REPORT = 940_306 -BASELINE_MISSING_REPORT = 940_307 -SAVED_SIMULATION = 940_211 -V1_POLICIES = { - CURRENT_LAW: {}, - CTC_REFORM: {CTC_AMOUNT: {PERIOD: 3000}}, - CTC_REFORM_WITH_ELASTICITY: { - CTC_AMOUNT: {PERIOD: 3500}, - INCOME_ELASTICITY: {PERIOD: 0.1}, - }, - CTC_REFORM_WITH_REMOVED_PARAMETER: { - EITC_RATE: {PERIOD: 0.4}, - REMOVED_PARAMETER: {PERIOD: True}, - }, - ONLY_REMOVED_PARAMETER: {REMOVED_PARAMETER: {PERIOD: True}}, - EITC_REFORM_WITH_OTHER_REMOVED_PARAMETER: { - EITC_RATE: {PERIOD: 0.3}, - OTHER_REMOVED_PARAMETER: {PERIOD: 0.1}, - }, -} -# Each API v1 simulation: its population type, population and policy. -V1_SIMULATIONS = { - 940_201: ("geography", "us", CURRENT_LAW), - 940_202: ("geography", "us", CTC_REFORM_WITH_ELASTICITY), - 940_203: ("household", str(V1_HOUSEHOLD), CURRENT_LAW), - 940_204: ("household", str(V1_HOUSEHOLD), CTC_REFORM), - 940_205: ("geography", "us", CTC_REFORM_WITH_REMOVED_PARAMETER), - 940_206: ("geography", "state/zz", CURRENT_LAW), - 940_207: ("geography", "state/zz", CTC_REFORM), - 940_208: ("geography", "us", ONLY_REMOVED_PARAMETER), - 940_209: ("geography", "us", EITC_REFORM_WITH_OTHER_REMOVED_PARAMETER), - 940_210: ("geography", "us", CTC_REFORM), -} -# Each API v1 report output: its two simulations. -V1_REPORTS = { - ECONOMY_REPORT: (940_201, 940_202), - HOUSEHOLD_REPORT: (940_203, 940_204), - MISSING_PARAMETER_REPORT: (940_201, 940_205), - UNKNOWN_REGION_REPORT: (940_206, 940_207), - # A reform whose every parameter is missing, compared with a baseline - # that sets one that still exists and another that is missing. - EVERY_PARAMETER_MISSING_REPORT: (940_209, 940_208), - # A baseline whose every parameter is missing, and a reform that is whole. - BASELINE_MISSING_REPORT: (940_208, 940_210), -} - - -def _household_document() -> dict[str, object]: - members = {"members": ["adult"]} - return { - "people": {"adult": {"age": {"2026": 41}}}, - "households": {"home": members}, - "families": {"family": members}, - "tax_units": {"tax unit": members}, - "spm_units": {"spm unit": members}, - "marital_units": {"marital unit": members}, - } - - -def _store_v1_records(v1_sessions: sessionmaker[OrmSession]) -> None: - _delete_v1_records(v1_sessions) - with v1_sessions.begin() as session: - for policy_id, policy_json in V1_POLICIES.items(): - session.add( - V1Policy( - id=policy_id, - country_id="us", - label=f"API v1 policy {policy_id}", - api_version="1.0.0", - policy_json=policy_json, - policy_hash=f"d4-1-hash-{policy_id}", - ) - ) - session.add( - V1Household( - id=V1_HOUSEHOLD, - country_id="us", - label="API v1 household", - api_version="1.0.0", - household_json=_household_document(), - household_hash="d4-1-household-hash", - ) - ) - for simulation_id, (kind, population, policy_id) in V1_SIMULATIONS.items(): - session.add( - V1Simulation( - id=simulation_id, - country_id="us", - api_version="1.0.0", - population_type=kind, - population_id=population, - policy_id=policy_id, - ) - ) - for report_id, (first, second) in V1_REPORTS.items(): - session.add( - V1ReportOutput( - id=report_id, - country_id="us", - simulation_1_id=first, - simulation_2_id=second, - api_version="1.0.0", - year="2026", - ) - ) - - -def _delete_v1_records(v1_sessions: sessionmaker[OrmSession]) -> None: - with v1_sessions.begin() as session: - session.execute( - delete(V1ReportOutputRun).where( - V1ReportOutputRun.report_output_id.in_(list(V1_REPORTS)) - ) - ) - session.execute( - delete(V1ReportOutput).where(V1ReportOutput.id.in_(list(V1_REPORTS))) - ) - session.execute( - delete(V1Simulation).where(V1Simulation.id.in_(list(V1_SIMULATIONS))) - ) - session.execute(delete(V1Household).where(V1Household.id == V1_HOUSEHOLD)) - session.execute(delete(V1Policy).where(V1Policy.id.in_(list(V1_POLICIES)))) - - -@dataclass -class ApiV2Rows: - """The rows each test stores in the API v2 tables, to delete after.""" - - model_id: UUID - created_model: bool - version_id: UUID - first_user: UUID - second_user: UUID - report_catalog: CatalogRows | None = None - - -@dataclass -class RecordingSimulationService: - """Stands in for the simulation service's find-or-create of reports by key. - - Each definition gets one report row, stored as the database's owner, and - the same definition gets the same report again. ``refused`` lists the - kinds of definition it refuses, as the simulation service answers 400, - and ``broken`` those it fails on with an error the migration doesn't - expect. ``while_answering`` runs before it answers, as a user's change - to a saved row would. - """ - - owner_sessions: sessionmaker[Session] - catalog: CatalogRows - definitions: list[ApiV2ReportDefinition] = field(default_factory=list) - reports: dict[ApiV2ReportDefinition, UUID] = field(default_factory=dict) - refused: set[ApiV2ReportKind] = field(default_factory=set) - broken: set[ApiV2ReportKind] = field(default_factory=set) - while_answering: Callable[[], None] | None = None - - def find_or_create_report(self, definition: ApiV2ReportDefinition) -> UUID: - self.definitions.append(definition) - with self.owner_sessions() as session: - # The simulation service reads what the definition names itself, - # so it must already be committed. - for side in (definition.baseline, definition.reform): - if side is not None and side.policy_id is not None: - assert session.get(Policy, side.policy_id) is not None - if side is not None and side.dynamic_id is not None: - assert session.get(Dynamic, side.dynamic_id) is not None - if definition.household_id is not None: - assert session.get(Household, definition.household_id) is not None - if definition.kind in self.refused: - message = "the simulation service refused the household report" - raise ReportSubmissionRefusedError(REFUSAL_CODE, message) - if definition.kind in self.broken: - message = "the stand-in simulation service broke" - raise RuntimeError(message) - if self.while_answering is not None: - self.while_answering() - if definition not in self.reports: - with self.owner_sessions.begin() as session: - self.reports[definition] = store_report(session, self.catalog).report_id - return self.reports[definition] - @pytest.fixture def runtime_sessions( v2_sessions_as_role: Callable[[str], sessionmaker[Session]], managed_v2_roles: ManagedV2Roles, ) -> sessionmaker[Session]: - return v2_sessions_as_role(managed_v2_roles.runtime) + return runtime_role_sessions(v2_sessions_as_role, managed_v2_roles) @pytest.fixture @@ -300,229 +92,7 @@ def stored_rows( v1_sessions: sessionmaker[OrmSession], v2_owner_sessions: sessionmaker[Session], ) -> Iterator[ApiV2Rows]: - _store_v1_records(v1_sessions) - with v2_owner_sessions.begin() as session: - model_id = session.scalar( - select(TaxBenefitModel.id).where( - col(TaxBenefitModel.name) == "policyengine-us" - ) - ) - created_model = model_id is None - if model_id is None: - model_id = uuid4() - add_row(session, TaxBenefitModel, id=model_id, name="policyengine-us") - version_id = uuid4() - add_row( - session, - TaxBenefitModelVersion, - id=version_id, - model_id=model_id, - version=RUNNING_VERSION, - current_law_id=1, - metadata_time_periods=[2026], - ) - for name in (CTC_AMOUNT, EITC_RATE): - add_row( - session, - Parameter, - id=uuid4(), - name=name, - tax_benefit_model_version_id=version_id, - ) - add_row( - session, - DynamicParameter, - id=uuid4(), - name=INCOME_ELASTICITY, - tax_benefit_model_version_id=version_id, - ) - rows = ApiV2Rows( - model_id=model_id, - created_model=created_model, - version_id=version_id, - first_user=uuid4(), - second_user=uuid4(), - ) - for user_id in (rows.first_user, rows.second_user): - add_row(session, User, id=user_id, primary_country="us") - rows.report_catalog = store_catalog(session, "us") - try: - yield rows - finally: - _delete_api_v2_rows(v2_owner_sessions, rows) - _delete_v1_records(v1_sessions) - - -def _delete_api_v2_rows(owner_sessions: sessionmaker[Session], rows: ApiV2Rows) -> None: - users = [rows.first_user, rows.second_user] - with owner_sessions.begin() as session: - for model in ( - UserReportAssociation, - UserSimulationAssociation, - UserHouseholdAssociation, - UserDynamic, - UserPolicy, - ): - session.execute(delete(model).where(col(model.user_id).in_(users))) - session.execute(delete(User).where(col(User.id).in_(users))) - session.execute( - delete(LegacyPolicyMapping).where( - col(LegacyPolicyMapping.legacy_policy_id).in_(list(V1_POLICIES)) - ) - ) - # The household copy is deleted after its mapping, which names it. - households = list( - session.scalars( - select(LegacyHouseholdMapping.household_id).where( - col(LegacyHouseholdMapping.legacy_household_id) == V1_HOUSEHOLD - ) - ) - ) - session.execute( - delete(LegacyHouseholdMapping).where( - col(LegacyHouseholdMapping.legacy_household_id) == V1_HOUSEHOLD - ) - ) - if rows.report_catalog is not None: - delete_catalog(session, rows.report_catalog) - version_policies = select(Policy.id).where( - col(Policy.tax_benefit_model_version_id) == rows.version_id - ) - version_dynamics = select(Dynamic.id).where( - col(Dynamic.tax_benefit_model_version_id) == rows.version_id - ) - session.execute( - delete(ParameterValue).where( - col(ParameterValue.policy_id).in_(version_policies) - ) - ) - session.execute( - delete(DynamicParameterValue).where( - col(DynamicParameterValue.dynamic_id).in_(version_dynamics) - ) - ) - session.execute( - delete(Policy).where( - col(Policy.tax_benefit_model_version_id) == rows.version_id - ) - ) - session.execute( - delete(Dynamic).where( - col(Dynamic.tax_benefit_model_version_id) == rows.version_id - ) - ) - session.execute(delete(Household).where(col(Household.id).in_(households))) - session.execute( - delete(TaxBenefitModelVersion).where( - col(TaxBenefitModelVersion.id) == rows.version_id - ) - ) - if rows.created_model: - session.execute( - delete(TaxBenefitModel).where(col(TaxBenefitModel.id) == rows.model_id) - ) - - -def _save(owner_sessions: sessionmaker[Session], model: type, **values: object) -> UUID: - row_id = uuid4() - with owner_sessions.begin() as session: - add_row(session, model, id=row_id, country_id="us", **values) - return row_id - - -def _service( - runtime_sessions: sessionmaker[Session], - v1_sessions: sessionmaker[OrmSession], - simulation_service: RecordingSimulationService, -) -> V2SavedRecordMigrationService: - return V2SavedRecordMigrationService( - SavedRecordMigrationDatabaseSession(runtime_sessions), - V1RecordDatabaseSession(v1_sessions), - report_submitter=simulation_service, - running_policyengine_version=RUNNING_VERSION, - ) - - -def _read_only(sessions: sessionmaker[Session]) -> sessionmaker[Session]: - """Return the same role's sessions with every transaction READ ONLY. - - The command opens a dry run's sessions this way, so PostgreSQL refuses - any write it tried. - """ - engine = sessions.kw["bind"] - return build_v2_session_factory(engine.execution_options(postgresql_readonly=True)) - - -def _simulation_service( - owner_sessions: sessionmaker[Session], rows: ApiV2Rows -) -> RecordingSimulationService: - assert rows.report_catalog is not None - return RecordingSimulationService(owner_sessions, rows.report_catalog) - - -def _migrate( - service: V2SavedRecordMigrationService, - rows: ApiV2Rows, - **options: object, -) -> MigrationRun: - return service.migrate( - MigrationOptions( - user_ids=(rows.first_user, rows.second_user), - **{"apply": True, **options}, - ) - ) - - -def _result(run: MigrationRun, row_id: UUID): - (result,) = [result for result in run.results if result.row_id == row_id] - return result - - -def _remaining(run: MigrationRun, kind: SavedRecordKind): - (remaining,) = [item for item in run.closing_check.remaining if item.kind is kind] - return remaining - - -def _policy_values(owner_sessions: sessionmaker[Session], policy_id: UUID) -> set: - with owner_sessions() as session: - return set( - session.execute( - select(Parameter.name, ParameterValue.value_json) - .join(Parameter, col(Parameter.id) == col(ParameterValue.parameter_id)) - .where(col(ParameterValue.policy_id) == policy_id) - ).all() - ) - - -def _dynamic_values(owner_sessions: sessionmaker[Session], dynamic_id: UUID) -> set: - with owner_sessions() as session: - return set( - session.execute( - select(DynamicParameter.name, DynamicParameterValue.value_json) - .join( - DynamicParameter, - col(DynamicParameter.id) - == col(DynamicParameterValue.dynamic_parameter_id), - ) - .where(col(DynamicParameterValue.dynamic_id) == dynamic_id) - ).all() - ) - - -def _mapping(owner_sessions: sessionmaker[Session], legacy_policy_id: int): - with owner_sessions() as session: - return session.scalar( - select(LegacyPolicyMapping).where( - col(LegacyPolicyMapping.legacy_policy_id) == legacy_policy_id - ) - ) - - -def _row(owner_sessions: sessionmaker[Session], model: type, row_id: UUID): - with owner_sessions() as session: - row = session.get(model, row_id) - session.expunge_all() - return row + yield from stored_rows_in(v1_sessions, v2_owner_sessions) # Saved reforms. @@ -531,38 +101,38 @@ def _row(owner_sessions: sessionmaker[Session], model: type, row_id: UUID): def test_a_saved_reform_is_pointed_at_its_v1_policy_s_copy( runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows ) -> None: - saved = _save( + saved = save_row( v2_owner_sessions, UserPolicy, user_id=stored_rows.first_user, legacy_policy_id=CTC_REFORM, name="Bigger CTC", ) - service = _service( + service = migration_service( runtime_sessions, v1_sessions, - _simulation_service(v2_owner_sessions, stored_rows), + simulation_service_for(v2_owner_sessions, stored_rows), ) - run = _migrate(service, stored_rows) + run = migrate(service, stored_rows) - mapping = _mapping(v2_owner_sessions, CTC_REFORM) + mapping = policy_mapping(v2_owner_sessions, CTC_REFORM) assert mapping is not None assert mapping.dynamic_id is None - row = _row(v2_owner_sessions, UserPolicy, saved) + row = stored_row(v2_owner_sessions, UserPolicy, saved) assert (row.policy_id, row.legacy_policy_id) == (mapping.policy_id, CTC_REFORM) - result = _result(run, saved) + result = result_of(run, saved) assert result.outcome is RowOutcome.MIGRATED assert result.api_v2_id == mapping.policy_id assert result.saved_dynamic_id is None - assert _policy_values(v2_owner_sessions, mapping.policy_id) == {(CTC_AMOUNT, 3000)} + assert policy_values(v2_owner_sessions, mapping.policy_id) == {(CTC_AMOUNT, 3000)} assert run.closing_check.passed def test_model_assumptions_become_a_dynamic_and_a_saved_dynamic_with_its_name( runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows ) -> None: - saved = _save( + saved = save_row( v2_owner_sessions, UserPolicy, user_id=stored_rows.first_user, @@ -570,24 +140,24 @@ def test_model_assumptions_become_a_dynamic_and_a_saved_dynamic_with_its_name( name="CTC with responses", description="With labour supply responses", ) - service = _service( + service = migration_service( runtime_sessions, v1_sessions, - _simulation_service(v2_owner_sessions, stored_rows), + simulation_service_for(v2_owner_sessions, stored_rows), ) - run = _migrate(service, stored_rows) + run = migrate(service, stored_rows) - mapping = _mapping(v2_owner_sessions, CTC_REFORM_WITH_ELASTICITY) + mapping = policy_mapping(v2_owner_sessions, CTC_REFORM_WITH_ELASTICITY) assert mapping is not None assert mapping.dynamic_id is not None - assert _policy_values(v2_owner_sessions, mapping.policy_id) == {(CTC_AMOUNT, 3500)} - assert _dynamic_values(v2_owner_sessions, mapping.dynamic_id) == { + assert policy_values(v2_owner_sessions, mapping.policy_id) == {(CTC_AMOUNT, 3500)} + assert dynamic_values(v2_owner_sessions, mapping.dynamic_id) == { (INCOME_ELASTICITY, 0.1) } - result = _result(run, saved) + result = result_of(run, saved) assert result.saved_dynamic_id is not None - saved_dynamic = _row(v2_owner_sessions, UserDynamic, result.saved_dynamic_id) + saved_dynamic = stored_row(v2_owner_sessions, UserDynamic, result.saved_dynamic_id) assert ( saved_dynamic.user_id, saved_dynamic.country_id, @@ -601,72 +171,74 @@ def test_model_assumptions_become_a_dynamic_and_a_saved_dynamic_with_its_name( "CTC with responses", "With labour supply responses", ) - assert _row(v2_owner_sessions, UserPolicy, saved).policy_id == mapping.policy_id + assert ( + stored_row(v2_owner_sessions, UserPolicy, saved).policy_id == mapping.policy_id + ) def test_a_saved_reform_with_a_missing_parameter_is_left_and_listed( runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows ) -> None: - saved = _save( + saved = save_row( v2_owner_sessions, UserPolicy, user_id=stored_rows.first_user, legacy_policy_id=CTC_REFORM_WITH_REMOVED_PARAMETER, ) - service = _service( + service = migration_service( runtime_sessions, v1_sessions, - _simulation_service(v2_owner_sessions, stored_rows), + simulation_service_for(v2_owner_sessions, stored_rows), ) - run = _migrate(service, stored_rows) + run = migrate(service, stored_rows) - result = _result(run, saved) + result = result_of(run, saved) assert result.outcome is RowOutcome.MISSING_PARAMETERS assert result.missing_parameters == (REMOVED_PARAMETER,) - assert _row(v2_owner_sessions, UserPolicy, saved).policy_id is None - assert _mapping(v2_owner_sessions, CTC_REFORM_WITH_REMOVED_PARAMETER) is None - assert _remaining(run, SavedRecordKind.SAVED_REFORM).missing_parameters == 1 + assert stored_row(v2_owner_sessions, UserPolicy, saved).policy_id is None + assert policy_mapping(v2_owner_sessions, CTC_REFORM_WITH_REMOVED_PARAMETER) is None + assert remaining_of(run, SavedRecordKind.SAVED_REFORM).missing_parameters == 1 assert run.closing_check.passed def test_the_second_mode_keeps_the_parameters_that_still_exist( runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows ) -> None: - partly_missing = _save( + partly_missing = save_row( v2_owner_sessions, UserPolicy, user_id=stored_rows.first_user, legacy_policy_id=CTC_REFORM_WITH_REMOVED_PARAMETER, ) - wholly_missing = _save( + wholly_missing = save_row( v2_owner_sessions, UserPolicy, user_id=stored_rows.first_user, legacy_policy_id=ONLY_REMOVED_PARAMETER, ) - service = _service( + service = migration_service( runtime_sessions, v1_sessions, - _simulation_service(v2_owner_sessions, stored_rows), + simulation_service_for(v2_owner_sessions, stored_rows), ) - run = _migrate(service, stored_rows, drop_missing_parameters=True) + run = migrate(service, stored_rows, drop_missing_parameters=True) - migrated = _result(run, partly_missing) + migrated = result_of(run, partly_missing) assert migrated.outcome is RowOutcome.MIGRATED assert migrated.dropped_parameters == (REMOVED_PARAMETER,) assert migrated.api_v2_id is not None - assert _policy_values(v2_owner_sessions, migrated.api_v2_id) == {(EITC_RATE, 0.4)} - row = _row(v2_owner_sessions, UserPolicy, partly_missing) + assert policy_values(v2_owner_sessions, migrated.api_v2_id) == {(EITC_RATE, 0.4)} + row = stored_row(v2_owner_sessions, UserPolicy, partly_missing) assert row.policy_id == migrated.api_v2_id # The kept policy isn't the API v1 policy's copy, so the API v1 ID gets no mapping. - assert _mapping(v2_owner_sessions, CTC_REFORM_WITH_REMOVED_PARAMETER) is None - left = _result(run, wholly_missing) + assert policy_mapping(v2_owner_sessions, CTC_REFORM_WITH_REMOVED_PARAMETER) is None + left = result_of(run, wholly_missing) assert left.outcome is RowOutcome.EVERY_PARAMETER_MISSING assert left.missing_parameters == (REMOVED_PARAMETER,) - assert _row(v2_owner_sessions, UserPolicy, wholly_missing).policy_id is None - assert _remaining(run, SavedRecordKind.SAVED_REFORM).every_parameter_missing == 1 + assert stored_row(v2_owner_sessions, UserPolicy, wholly_missing).policy_id is None + assert remaining_of(run, SavedRecordKind.SAVED_REFORM).every_parameter_missing == 1 assert run.closing_check.passed @@ -676,20 +248,20 @@ def test_the_second_mode_keeps_the_parameters_that_still_exist( def test_a_saved_household_is_pointed_at_its_v1_household_s_copy( runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows ) -> None: - saved = _save( + saved = save_row( v2_owner_sessions, UserHouseholdAssociation, user_id=stored_rows.first_user, legacy_household_id=V1_HOUSEHOLD, name="My household", ) - service = _service( + service = migration_service( runtime_sessions, v1_sessions, - _simulation_service(v2_owner_sessions, stored_rows), + simulation_service_for(v2_owner_sessions, stored_rows), ) - run = _migrate(service, stored_rows) + run = migrate(service, stored_rows) with v2_owner_sessions() as session: household_id = session.scalar( @@ -698,34 +270,35 @@ def test_a_saved_household_is_pointed_at_its_v1_household_s_copy( ) ) assert household_id is not None - row = _row(v2_owner_sessions, UserHouseholdAssociation, saved) + row = stored_row(v2_owner_sessions, UserHouseholdAssociation, saved) assert (row.household_id, row.legacy_household_id) == (household_id, V1_HOUSEHOLD) - assert _result(run, saved).api_v2_id == household_id + assert result_of(run, saved).api_v2_id == household_id assert run.closing_check.passed def test_a_saved_simulation_is_listed_and_not_migrated( runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows ) -> None: - saved = _save( + saved = save_row( v2_owner_sessions, UserSimulationAssociation, user_id=stored_rows.first_user, legacy_simulation_id=SAVED_SIMULATION, ) - service = _service( + service = migration_service( runtime_sessions, v1_sessions, - _simulation_service(v2_owner_sessions, stored_rows), + simulation_service_for(v2_owner_sessions, stored_rows), ) - run = _migrate(service, stored_rows) + run = migrate(service, stored_rows) - assert _result(run, saved).outcome is RowOutcome.NOT_MIGRATED + assert result_of(run, saved).outcome is RowOutcome.NOT_MIGRATED assert ( - _row(v2_owner_sessions, UserSimulationAssociation, saved).simulation_id is None + stored_row(v2_owner_sessions, UserSimulationAssociation, saved).simulation_id + is None ) - assert _remaining(run, SavedRecordKind.SAVED_SIMULATION).not_migrated == 1 + assert remaining_of(run, SavedRecordKind.SAVED_SIMULATION).not_migrated == 1 assert run.closing_check.passed @@ -735,26 +308,26 @@ def test_a_saved_simulation_is_listed_and_not_migrated( def test_identical_v1_reports_share_one_report_with_each_side_split( runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows ) -> None: - first = _save( + first = save_row( v2_owner_sessions, UserReportAssociation, user_id=stored_rows.first_user, legacy_report_id=ECONOMY_REPORT, name="CTC report", ) - second = _save( + second = save_row( v2_owner_sessions, UserReportAssociation, user_id=stored_rows.second_user, legacy_report_id=ECONOMY_REPORT, name="Same report, another user", ) - simulation_service = _simulation_service(v2_owner_sessions, stored_rows) - service = _service(runtime_sessions, v1_sessions, simulation_service) + simulation_service = simulation_service_for(v2_owner_sessions, stored_rows) + service = migration_service(runtime_sessions, v1_sessions, simulation_service) - run = _migrate(service, stored_rows) + run = migrate(service, stored_rows) - mapping = _mapping(v2_owner_sessions, CTC_REFORM_WITH_ELASTICITY) + mapping = policy_mapping(v2_owner_sessions, CTC_REFORM_WITH_ELASTICITY) assert mapping is not None assert simulation_service.definitions == [ ApiV2ReportDefinition( @@ -772,53 +345,53 @@ def test_identical_v1_reports_share_one_report_with_each_side_split( ] (report_id,) = simulation_service.reports.values() for row_id, name in ((first, "CTC report"), (second, "Same report, another user")): - row = _row(v2_owner_sessions, UserReportAssociation, row_id) + row = stored_row(v2_owner_sessions, UserReportAssociation, row_id) assert (row.report_id, row.legacy_report_id, row.name) == ( report_id, ECONOMY_REPORT, name, ) - assert _result(run, row_id).api_v2_id == report_id + assert result_of(run, row_id).api_v2_id == report_id assert run.closing_check.passed def test_a_saved_budget_window_becomes_a_budget_window_report( runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows ) -> None: - saved = _save( + saved = save_row( v2_owner_sessions, UserReportAssociation, user_id=stored_rows.first_user, legacy_report_id=ECONOMY_REPORT, budget_window_years=10, ) - simulation_service = _simulation_service(v2_owner_sessions, stored_rows) - service = _service(runtime_sessions, v1_sessions, simulation_service) + simulation_service = simulation_service_for(v2_owner_sessions, stored_rows) + service = migration_service(runtime_sessions, v1_sessions, simulation_service) - run = _migrate(service, stored_rows) + run = migrate(service, stored_rows) (definition,) = simulation_service.definitions assert definition.kind is ApiV2ReportKind.BUDGET_WINDOW assert (definition.year, definition.budget_window_size) == (2026, 10) - row = _row(v2_owner_sessions, UserReportAssociation, saved) + row = stored_row(v2_owner_sessions, UserReportAssociation, saved) assert row.report_id == simulation_service.reports[definition] assert row.budget_window_years == 10 - assert _result(run, saved).outcome is RowOutcome.MIGRATED + assert result_of(run, saved).outcome is RowOutcome.MIGRATED def test_a_household_report_names_the_household_s_copy( runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows ) -> None: - saved = _save( + saved = save_row( v2_owner_sessions, UserReportAssociation, user_id=stored_rows.first_user, legacy_report_id=HOUSEHOLD_REPORT, ) - simulation_service = _simulation_service(v2_owner_sessions, stored_rows) - service = _service(runtime_sessions, v1_sessions, simulation_service) + simulation_service = simulation_service_for(v2_owner_sessions, stored_rows) + service = migration_service(runtime_sessions, v1_sessions, simulation_service) - run = _migrate(service, stored_rows) + run = migrate(service, stored_rows) household_mapping_id = None with v2_owner_sessions() as session: @@ -827,7 +400,7 @@ def test_a_household_report_names_the_household_s_copy( col(LegacyHouseholdMapping.legacy_household_id) == V1_HOUSEHOLD ) ) - reform_mapping = _mapping(v2_owner_sessions, CTC_REFORM) + reform_mapping = policy_mapping(v2_owner_sessions, CTC_REFORM) assert reform_mapping is not None assert simulation_service.definitions == [ ApiV2ReportDefinition( @@ -841,54 +414,60 @@ def test_a_household_report_names_the_household_s_copy( household_id=household_mapping_id, ) ] - assert _result(run, saved).outcome is RowOutcome.MIGRATED - assert _row(v2_owner_sessions, UserReportAssociation, saved).report_id is not None + assert result_of(run, saved).outcome is RowOutcome.MIGRATED + assert ( + stored_row(v2_owner_sessions, UserReportAssociation, saved).report_id + is not None + ) def test_reports_that_cant_migrate_are_left_with_a_reason( runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows ) -> None: - missing_parameter = _save( + missing_parameter = save_row( v2_owner_sessions, UserReportAssociation, user_id=stored_rows.first_user, legacy_report_id=MISSING_PARAMETER_REPORT, ) - unknown_region = _save( + unknown_region = save_row( v2_owner_sessions, UserReportAssociation, user_id=stored_rows.first_user, legacy_report_id=UNKNOWN_REGION_REPORT, ) - refused = _save( + refused = save_row( v2_owner_sessions, UserReportAssociation, user_id=stored_rows.first_user, legacy_report_id=HOUSEHOLD_REPORT, ) - no_v1_report = _save( + no_v1_report = save_row( v2_owner_sessions, UserReportAssociation, user_id=stored_rows.first_user, legacy_report_id=940_399, ) - simulation_service = _simulation_service(v2_owner_sessions, stored_rows) + simulation_service = simulation_service_for(v2_owner_sessions, stored_rows) simulation_service.refused.add(ApiV2ReportKind.HOUSEHOLD) - service = _service(runtime_sessions, v1_sessions, simulation_service) + service = migration_service(runtime_sessions, v1_sessions, simulation_service) - run = _migrate(service, stored_rows) + run = migrate(service, stored_rows) - skipped = _result(run, missing_parameter) + skipped = result_of(run, missing_parameter) assert skipped.outcome is RowOutcome.MISSING_PARAMETERS assert skipped.missing_parameters == (REMOVED_PARAMETER,) - assert _result(run, unknown_region).failure_reason is FailureReason.UNKNOWN_REGION - assert _result(run, refused).failure_reason is FailureReason.REPORT_REFUSED + assert result_of(run, unknown_region).failure_reason is FailureReason.UNKNOWN_REGION + assert result_of(run, refused).failure_reason is FailureReason.REPORT_REFUSED assert ( - _result(run, no_v1_report).failure_reason is FailureReason.V1_RECORD_NOT_FOUND + result_of(run, no_v1_report).failure_reason is FailureReason.V1_RECORD_NOT_FOUND ) for row_id in (missing_parameter, unknown_region, refused, no_v1_report): - assert _row(v2_owner_sessions, UserReportAssociation, row_id).report_id is None - remaining = _remaining(run, SavedRecordKind.SAVED_REPORT) + assert ( + stored_row(v2_owner_sessions, UserReportAssociation, row_id).report_id + is None + ) + remaining = remaining_of(run, SavedRecordKind.SAVED_REPORT) assert (remaining.missing_parameters, remaining.failed) == (1, 3) assert not run.closing_check.passed # Only the household report reached the simulation service. @@ -900,26 +479,11 @@ def test_reports_that_cant_migrate_are_left_with_a_reason( # Dry runs and running again. -def _row_counts(owner_sessions: sessionmaker[Session]) -> dict[str, int]: - with owner_sessions() as session: - return { - model.__name__: session.scalar(select(func.count()).select_from(model)) - for model in ( - Policy, - Dynamic, - Household, - LegacyPolicyMapping, - LegacyHouseholdMapping, - UserDynamic, - ) - } - - def test_a_dry_run_writes_nothing_and_predicts_the_real_run( runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows ) -> None: saved_rows = [ - _save( + save_row( v2_owner_sessions, UserPolicy, user_id=stored_rows.first_user, @@ -928,7 +492,7 @@ def test_a_dry_run_writes_nothing_and_predicts_the_real_run( for legacy_policy_id in (CTC_REFORM_WITH_ELASTICITY, ONLY_REMOVED_PARAMETER) ] saved_rows.append( - _save( + save_row( v2_owner_sessions, UserReportAssociation, user_id=stored_rows.first_user, @@ -936,26 +500,26 @@ def test_a_dry_run_writes_nothing_and_predicts_the_real_run( ) ) saved_rows.append( - _save( + save_row( v2_owner_sessions, UserHouseholdAssociation, user_id=stored_rows.first_user, legacy_household_id=V1_HOUSEHOLD, ) ) - simulation_service = _simulation_service(v2_owner_sessions, stored_rows) - service = _service(runtime_sessions, v1_sessions, simulation_service) - read_only_service = _service( - _read_only(runtime_sessions), v1_sessions, simulation_service + simulation_service = simulation_service_for(v2_owner_sessions, stored_rows) + service = migration_service(runtime_sessions, v1_sessions, simulation_service) + read_only_service = migration_service( + read_only_sessions(runtime_sessions), v1_sessions, simulation_service ) - before = _row_counts(v2_owner_sessions) + before = row_counts(v2_owner_sessions) - dry_run = _migrate(read_only_service, stored_rows, apply=False) + dry_run = migrate(read_only_service, stored_rows, apply=False) - assert _row_counts(v2_owner_sessions) == before + assert row_counts(v2_owner_sessions) == before assert simulation_service.definitions == [] - assert _row(v2_owner_sessions, UserPolicy, saved_rows[0]).policy_id is None - real_run = _migrate(service, stored_rows) + assert stored_row(v2_owner_sessions, UserPolicy, saved_rows[0]).policy_id is None + real_run = migrate(service, stored_rows) assert [ (result.row_id, result.outcome, result.missing_parameters) for result in dry_run.results @@ -969,23 +533,23 @@ def test_a_dry_run_writes_nothing_and_predicts_the_real_run( def test_a_second_run_finds_nothing_left_to_migrate( runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows ) -> None: - _save( + save_row( v2_owner_sessions, UserPolicy, user_id=stored_rows.first_user, legacy_policy_id=CTC_REFORM, ) - _save( + save_row( v2_owner_sessions, UserReportAssociation, user_id=stored_rows.first_user, legacy_report_id=ECONOMY_REPORT, ) - simulation_service = _simulation_service(v2_owner_sessions, stored_rows) - service = _service(runtime_sessions, v1_sessions, simulation_service) - _migrate(service, stored_rows) + simulation_service = simulation_service_for(v2_owner_sessions, stored_rows) + service = migration_service(runtime_sessions, v1_sessions, simulation_service) + migrate(service, stored_rows) - second = _migrate(service, stored_rows) + second = migrate(service, stored_rows) assert second.results == () assert second.closing_check.passed @@ -996,44 +560,44 @@ def test_the_limit_leaves_rows_the_closing_check_counts( runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows ) -> None: for legacy_policy_id in (CTC_REFORM, CTC_REFORM_WITH_ELASTICITY): - _save( + save_row( v2_owner_sessions, UserPolicy, user_id=stored_rows.first_user, legacy_policy_id=legacy_policy_id, ) - service = _service( + service = migration_service( runtime_sessions, v1_sessions, - _simulation_service(v2_owner_sessions, stored_rows), + simulation_service_for(v2_owner_sessions, stored_rows), ) - run = _migrate(service, stored_rows, limit=1) + run = migrate(service, stored_rows, limit=1) assert [result.outcome for result in run.results] == [RowOutcome.MIGRATED] - assert _remaining(run, SavedRecordKind.SAVED_REFORM).not_attempted == 1 + assert remaining_of(run, SavedRecordKind.SAVED_REFORM).not_attempted == 1 assert not run.closing_check.passed def test_a_run_of_some_kinds_leaves_the_others_alone( runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows ) -> None: - saved_reform = _save( + saved_reform = save_row( v2_owner_sessions, UserPolicy, user_id=stored_rows.first_user, legacy_policy_id=CTC_REFORM, ) - saved_report = _save( + saved_report = save_row( v2_owner_sessions, UserReportAssociation, user_id=stored_rows.first_user, legacy_report_id=ECONOMY_REPORT, ) - simulation_service = _simulation_service(v2_owner_sessions, stored_rows) - service = _service(runtime_sessions, v1_sessions, simulation_service) + simulation_service = simulation_service_for(v2_owner_sessions, stored_rows) + service = migration_service(runtime_sessions, v1_sessions, simulation_service) - run = _migrate( + run = migrate( service, stored_rows, kinds=(SavedRecordKind.SAVED_REFORM, SavedRecordKind.SAVED_HOUSEHOLD), @@ -1041,7 +605,8 @@ def test_a_run_of_some_kinds_leaves_the_others_alone( assert [result.row_id for result in run.results] == [saved_reform] assert ( - _row(v2_owner_sessions, UserReportAssociation, saved_report).report_id is None + stored_row(v2_owner_sessions, UserReportAssociation, saved_report).report_id + is None ) assert simulation_service.definitions == [] assert [item.kind for item in run.closing_check.remaining] == [ @@ -1051,38 +616,6 @@ def test_a_run_of_some_kinds_leaves_the_others_alone( assert run.closing_check.passed -# The sample comparison of migrated reports' results with API v1's. - -RUN_VERSIONS = {"country_package_version": "2.2.2", "policyengine_version": "6.20.0"} - - -def _store_v1_result( - v1_sessions: sessionmaker[OrmSession], - report_id: int, - *, - budgetary_impact: float, - country_package_version: str, -) -> None: - """Give an API v1 report output a stored result from a run on a package version.""" - run_id = str(uuid4()) - with v1_sessions.begin() as session: - session.add( - V1ReportOutputRun( - id=run_id, - report_output_id=report_id, - run_sequence=1, - status="complete", - trigger_type="initial", - country_package_version=country_package_version, - ) - ) - report = session.get(V1ReportOutput, report_id) - assert report is not None - report.output = {"budget": {"budgetary_impact": budgetary_impact}} - report.status = "complete" - report.latest_successful_run_id = run_id - - def test_the_sample_compares_a_migrated_report_s_run_with_v1_s_result( runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows ) -> None: @@ -1110,7 +643,7 @@ def test_the_sample_compares_a_migrated_report_s_run_with_v1_s_result( (MISSING_PARAMETER_REPORT, never_run.report_id), (UNKNOWN_REGION_REPORT, failed.report_id), ): - _save( + save_row( v2_owner_sessions, UserReportAssociation, user_id=stored_rows.first_user, @@ -1118,20 +651,20 @@ def test_the_sample_compares_a_migrated_report_s_run_with_v1_s_result( report_id=report_id, ) # A saved report holding only its API v2 report wasn't migrated. - _save( + save_row( v2_owner_sessions, UserReportAssociation, user_id=stored_rows.second_user, report_id=calculated.report_id, ) - _store_v1_result( + store_v1_result( v1_sessions, ECONOMY_REPORT, budgetary_impact=-10.0e9, country_package_version="1.420.0", ) - simulation_service = _simulation_service(v2_owner_sessions, stored_rows) - service = _service(runtime_sessions, v1_sessions, simulation_service) + simulation_service = simulation_service_for(v2_owner_sessions, stored_rows) + service = migration_service(runtime_sessions, v1_sessions, simulation_service) comparison = service.compare_sample( size=5, @@ -1171,17 +704,17 @@ def test_the_sample_takes_at_most_its_size( RunSettings(versions=RUN_VERSIONS), result=us_economy_result(), ) - _save( + save_row( v2_owner_sessions, UserReportAssociation, user_id=stored_rows.first_user, legacy_report_id=legacy_report_id, report_id=report.report_id, ) - service = _service( + service = migration_service( runtime_sessions, v1_sessions, - _simulation_service(v2_owner_sessions, stored_rows), + simulation_service_for(v2_owner_sessions, stored_rows), ) comparison = service.compare_sample( @@ -1192,268 +725,3 @@ def test_the_sample_takes_at_most_its_size( # API v1 stored no result for this report. assert item.api_v1_budgetary_impact is None assert item.relative_difference is None - - -# Review round 1. - - -def test_a_saved_dynamic_that_cant_take_the_description_fails_its_row_alone( - runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows -) -> None: - # A saved dynamic's description takes at most 10,000 characters, while a - # saved reform's is unbounded. - too_long = _save( - v2_owner_sessions, - UserPolicy, - user_id=stored_rows.first_user, - legacy_policy_id=CTC_REFORM_WITH_ELASTICITY, - description="x" * 10_001, - ) - later = _save( - v2_owner_sessions, - UserPolicy, - user_id=stored_rows.second_user, - legacy_policy_id=CTC_REFORM, - ) - service = _service( - runtime_sessions, - v1_sessions, - _simulation_service(v2_owner_sessions, stored_rows), - ) - - dry_run = _migrate(service, stored_rows, apply=False) - run = _migrate(service, stored_rows) - - for checked in (dry_run, run): - result = _result(checked, too_long) - assert (result.outcome, result.failure_reason) == ( - RowOutcome.FAILED, - FailureReason.SAVED_DYNAMIC_NOT_VALID, - ) - assert _result(run, later).outcome is RowOutcome.MIGRATED - assert _row(v2_owner_sessions, UserPolicy, too_long).policy_id is None - with v2_owner_sessions() as session: - assert ( - session.scalar( - select(func.count()) - .select_from(UserDynamic) - .where(col(UserDynamic.user_id) == stored_rows.first_user) - ) - == 0 - ) - - -def test_a_refused_report_is_asked_for_once_for_all_its_saved_reports( - runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows -) -> None: - saved_rows = [ - _save( - v2_owner_sessions, - UserReportAssociation, - user_id=user_id, - legacy_report_id=HOUSEHOLD_REPORT, - ) - for user_id in (stored_rows.first_user, stored_rows.second_user) - ] - simulation_service = _simulation_service(v2_owner_sessions, stored_rows) - simulation_service.refused.add(ApiV2ReportKind.HOUSEHOLD) - service = _service(runtime_sessions, v1_sessions, simulation_service) - - run = _migrate(service, stored_rows) - - assert len(simulation_service.definitions) == 1 - for row_id in saved_rows: - assert _result(run, row_id).failure_reason is FailureReason.REPORT_REFUSED - assert _row(v2_owner_sessions, UserReportAssociation, row_id).report_id is None - - -def test_an_unexpected_error_fails_its_row_and_the_run_goes_on( - runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows -) -> None: - broken = _save( - v2_owner_sessions, - UserReportAssociation, - user_id=stored_rows.first_user, - legacy_report_id=HOUSEHOLD_REPORT, - ) - later = _save( - v2_owner_sessions, - UserReportAssociation, - user_id=stored_rows.first_user, - legacy_report_id=ECONOMY_REPORT, - ) - simulation_service = _simulation_service(v2_owner_sessions, stored_rows) - simulation_service.broken.add(ApiV2ReportKind.HOUSEHOLD) - service = _service(runtime_sessions, v1_sessions, simulation_service) - - run = _migrate(service, stored_rows) - - failed = _result(run, broken) - assert (failed.outcome, failed.failure_reason) == ( - RowOutcome.FAILED, - FailureReason.UNEXPECTED_ERROR, - ) - assert failed.failure_detail is not None - assert "RuntimeError" in failed.failure_detail - assert _result(run, later).outcome is RowOutcome.MIGRATED - assert not run.closing_check.passed - - -def test_the_second_mode_drops_missing_parameters_from_both_sides_of_a_report( - runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows -) -> None: - reduced = _save( - v2_owner_sessions, - UserReportAssociation, - user_id=stored_rows.first_user, - legacy_report_id=MISSING_PARAMETER_REPORT, - ) - every_parameter_missing = _save( - v2_owner_sessions, - UserReportAssociation, - user_id=stored_rows.first_user, - legacy_report_id=EVERY_PARAMETER_MISSING_REPORT, - ) - baseline_missing = _save( - v2_owner_sessions, - UserReportAssociation, - user_id=stored_rows.first_user, - legacy_report_id=BASELINE_MISSING_REPORT, - ) - simulation_service = _simulation_service(v2_owner_sessions, stored_rows) - service = _service(runtime_sessions, v1_sessions, simulation_service) - - run = _migrate(service, stored_rows, drop_missing_parameters=True) - - migrated = _result(run, reduced) - assert (migrated.outcome, migrated.dropped_parameters) == ( - RowOutcome.MIGRATED, - (REMOVED_PARAMETER,), - ) - left = _result(run, every_parameter_missing) - # Both sides' missing parameters are listed. - assert (left.outcome, left.missing_parameters) == ( - RowOutcome.EVERY_PARAMETER_MISSING, - (OTHER_REMOVED_PARAMETER, REMOVED_PARAMETER), - ) - assert ( - _row( - v2_owner_sessions, UserReportAssociation, every_parameter_missing - ).report_id - is None - ) - baseline_result = _result(run, baseline_missing) - assert (baseline_result.outcome, baseline_result.dropped_parameters) == ( - RowOutcome.MIGRATED, - (REMOVED_PARAMETER,), - ) - reduced_definition, baseline_definition = simulation_service.definitions - assert reduced_definition.baseline == PolicySide(policy_id=None, dynamic_id=None) - assert reduced_definition.reform is not None - assert reduced_definition.reform.policy_id is not None - assert _policy_values(v2_owner_sessions, reduced_definition.reform.policy_id) == { - (EITC_RATE, 0.4) - } - # The kept part isn't a copy of the API v1 policy, so it gets no mapping. - assert _mapping(v2_owner_sessions, CTC_REFORM_WITH_REMOVED_PARAMETER) is None - ctc_mapping = _mapping(v2_owner_sessions, CTC_REFORM) - assert ctc_mapping is not None - assert baseline_definition.baseline == PolicySide(policy_id=None, dynamic_id=None) - assert baseline_definition.reform == PolicySide( - policy_id=ctc_mapping.policy_id, dynamic_id=None - ) - - -def test_a_saved_report_changed_while_its_report_is_found_is_left_alone( - runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows -) -> None: - saved = _save( - v2_owner_sessions, - UserReportAssociation, - user_id=stored_rows.first_user, - legacy_report_id=ECONOMY_REPORT, - ) - simulation_service = _simulation_service(v2_owner_sessions, stored_rows) - - def delete_the_saved_report() -> None: - with v2_owner_sessions.begin() as session: - session.execute( - delete(UserReportAssociation).where( - col(UserReportAssociation.id) == saved - ) - ) - - simulation_service.while_answering = delete_the_saved_report - service = _service(runtime_sessions, v1_sessions, simulation_service) - - run = _migrate(service, stored_rows) - - result = _result(run, saved) - assert (result.outcome, result.failure_reason) == ( - RowOutcome.FAILED, - FailureReason.ROW_CHANGED, - ) - - -def test_saved_reforms_of_one_api_v1_policy_share_its_copy( - runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows -) -> None: - saved_rows = [ - _save( - v2_owner_sessions, - UserPolicy, - user_id=user_id, - legacy_policy_id=CTC_REFORM, - ) - for user_id in (stored_rows.first_user, stored_rows.second_user) - ] - service = _service( - runtime_sessions, - v1_sessions, - _simulation_service(v2_owner_sessions, stored_rows), - ) - - _migrate(service, stored_rows) - - mapping = _mapping(v2_owner_sessions, CTC_REFORM) - assert mapping is not None - assert { - _row(v2_owner_sessions, UserPolicy, row_id).policy_id for row_id in saved_rows - } == {mapping.policy_id} - - -def test_a_policy_mapped_from_another_source_fails_in_the_dry_run_too( - runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows -) -> None: - assert stored_rows.report_catalog is not None - with v2_owner_sessions.begin() as session: - add_row( - session, - LegacyPolicyMapping, - id=uuid4(), - country_id="us", - legacy_policy_id=CTC_REFORM, - policy_id=stored_rows.report_catalog.policy_id, - source_policy_hash="another-source-hash", - ) - saved = _save( - v2_owner_sessions, - UserPolicy, - user_id=stored_rows.first_user, - legacy_policy_id=CTC_REFORM, - ) - service = _service( - runtime_sessions, - v1_sessions, - _simulation_service(v2_owner_sessions, stored_rows), - ) - - dry_run = _migrate(service, stored_rows, apply=False) - run = _migrate(service, stored_rows) - - for checked in (dry_run, run): - result = _result(checked, saved) - assert (result.outcome, result.failure_reason) == ( - RowOutcome.FAILED, - FailureReason.POLICY_NOT_COPYABLE, - ) diff --git a/tests/integration/test_v2_saved_record_migration_failures.py b/tests/integration/test_v2_saved_record_migration_failures.py new file mode 100644 index 000000000..2bec8dbf6 --- /dev/null +++ b/tests/integration/test_v2_saved_record_migration_failures.py @@ -0,0 +1,499 @@ +"""How the one-time saved-record migration fails, and its second mode (D4 · 1). + +Rows that can't migrate fail alone and the run goes on; the second mode on +saved reports; and dry runs that predict real runs. The rows, the stand-in for +the simulation service and the helpers are in ``saved_record_migration_support``. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING +from uuid import uuid4 + +import pytest +from sqlalchemy import delete, func, select +from sqlmodel import col + +from policyengine_api.data.v2.models import ( + LegacyPolicyMapping, + UserDynamic, + UserHouseholdAssociation, + UserPolicy, + UserReportAssociation, +) +from policyengine_api.services.v2.saved_record_migration.database_session import ( + SavedRecordMigrationDatabaseSession, + V1RecordDatabaseSession, +) +from policyengine_api.services.v2.saved_record_migration.services import ( + V2SavedRecordMigrationService, +) +from policyengine_api.services.v2.saved_record_migration.types import ( + ApiV2ReportKind, + FailureReason, + MigrationRun, + PolicySide, + RowOutcome, +) +from tests.integration.saved_record_migration_support import ( + BASELINE_MISSING_REPORT, + CTC_REFORM, + CTC_REFORM_WITH_ELASTICITY, + CTC_REFORM_WITH_REMOVED_PARAMETER, + ECONOMY_REPORT, + EITC_RATE, + EVERY_PARAMETER_MISSING_REPORT, + HOUSEHOLD_REPORT, + MISSING_PARAMETER_REPORT, + OTHER_REMOVED_PARAMETER, + REMOVED_PARAMETER, + RUNNING_VERSION, + V1_HOUSEHOLD, + ApiV2Rows, + migrate, + migration_service, + policy_mapping, + policy_values, + read_only_sessions, + result_of, + runtime_role_sessions, + save_row, + simulation_service_for, + stored_row, + stored_rows_in, +) +from tests.integration.simulation_rows import add_row + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + + from sqlalchemy.orm import Session as OrmSession + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + from tests.integration.conftest import ManagedV2Roles + + +@pytest.fixture +def runtime_sessions( + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], + managed_v2_roles: ManagedV2Roles, +) -> sessionmaker[Session]: + return runtime_role_sessions(v2_sessions_as_role, managed_v2_roles) + + +@pytest.fixture +def stored_rows( + v1_sessions: sessionmaker[OrmSession], + v2_owner_sessions: sessionmaker[Session], +) -> Iterator[ApiV2Rows]: + yield from stored_rows_in(v1_sessions, v2_owner_sessions) + + +# Review round 1. + + +def test_a_saved_dynamic_that_cant_take_the_description_fails_its_row_alone( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + # A saved dynamic's description takes at most 10,000 characters, while a + # saved reform's is unbounded. + too_long = save_row( + v2_owner_sessions, + UserPolicy, + user_id=stored_rows.first_user, + legacy_policy_id=CTC_REFORM_WITH_ELASTICITY, + description="x" * 10_001, + ) + later = save_row( + v2_owner_sessions, + UserPolicy, + user_id=stored_rows.second_user, + legacy_policy_id=CTC_REFORM, + ) + service = migration_service( + runtime_sessions, + v1_sessions, + simulation_service_for(v2_owner_sessions, stored_rows), + ) + + dry_run = migrate(service, stored_rows, apply=False) + run = migrate(service, stored_rows) + + for checked in (dry_run, run): + result = result_of(checked, too_long) + assert (result.outcome, result.failure_reason) == ( + RowOutcome.FAILED, + FailureReason.SAVED_DYNAMIC_NOT_VALID, + ) + assert result_of(run, later).outcome is RowOutcome.MIGRATED + assert stored_row(v2_owner_sessions, UserPolicy, too_long).policy_id is None + with v2_owner_sessions() as session: + assert ( + session.scalar( + select(func.count()) + .select_from(UserDynamic) + .where(col(UserDynamic.user_id) == stored_rows.first_user) + ) + == 0 + ) + + +def test_a_refused_report_is_asked_for_once_for_all_its_saved_reports( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + saved_rows = [ + save_row( + v2_owner_sessions, + UserReportAssociation, + user_id=user_id, + legacy_report_id=HOUSEHOLD_REPORT, + ) + for user_id in (stored_rows.first_user, stored_rows.second_user) + ] + simulation_service = simulation_service_for(v2_owner_sessions, stored_rows) + simulation_service.refused.add(ApiV2ReportKind.HOUSEHOLD) + service = migration_service(runtime_sessions, v1_sessions, simulation_service) + + run = migrate(service, stored_rows) + + assert len(simulation_service.definitions) == 1 + for row_id in saved_rows: + assert result_of(run, row_id).failure_reason is FailureReason.REPORT_REFUSED + assert ( + stored_row(v2_owner_sessions, UserReportAssociation, row_id).report_id + is None + ) + + +def test_an_unexpected_error_fails_its_row_and_the_run_goes_on( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + broken = save_row( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=HOUSEHOLD_REPORT, + ) + later = save_row( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=ECONOMY_REPORT, + ) + simulation_service = simulation_service_for(v2_owner_sessions, stored_rows) + simulation_service.broken.add(ApiV2ReportKind.HOUSEHOLD) + service = migration_service(runtime_sessions, v1_sessions, simulation_service) + + run = migrate(service, stored_rows) + + failed = result_of(run, broken) + assert (failed.outcome, failed.failure_reason) == ( + RowOutcome.FAILED, + FailureReason.UNEXPECTED_ERROR, + ) + # Only the error's type and first line are kept, so no row's contents + # reach the output. + assert failed.failure_detail == ( + "RuntimeError: the stand-in simulation service broke" + ) + assert result_of(run, later).outcome is RowOutcome.MIGRATED + assert not run.closing_check.passed + + +def test_the_second_mode_drops_missing_parameters_from_both_sides_of_a_report( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + reduced = save_row( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=MISSING_PARAMETER_REPORT, + ) + every_parameter_missing = save_row( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=EVERY_PARAMETER_MISSING_REPORT, + ) + baseline_missing = save_row( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=BASELINE_MISSING_REPORT, + ) + simulation_service = simulation_service_for(v2_owner_sessions, stored_rows) + service = migration_service(runtime_sessions, v1_sessions, simulation_service) + + run = migrate(service, stored_rows, drop_missing_parameters=True) + + migrated = result_of(run, reduced) + assert (migrated.outcome, migrated.dropped_parameters) == ( + RowOutcome.MIGRATED, + (REMOVED_PARAMETER,), + ) + left = result_of(run, every_parameter_missing) + # Both sides' missing parameters are listed. + assert (left.outcome, left.missing_parameters) == ( + RowOutcome.EVERY_PARAMETER_MISSING, + (OTHER_REMOVED_PARAMETER, REMOVED_PARAMETER), + ) + assert ( + stored_row( + v2_owner_sessions, UserReportAssociation, every_parameter_missing + ).report_id + is None + ) + baseline_result = result_of(run, baseline_missing) + assert (baseline_result.outcome, baseline_result.dropped_parameters) == ( + RowOutcome.MIGRATED, + (REMOVED_PARAMETER,), + ) + reduced_definition, baseline_definition = simulation_service.definitions + assert reduced_definition.baseline == PolicySide(policy_id=None, dynamic_id=None) + assert reduced_definition.reform is not None + assert reduced_definition.reform.policy_id is not None + assert policy_values(v2_owner_sessions, reduced_definition.reform.policy_id) == { + (EITC_RATE, 0.4) + } + # The kept part isn't a copy of the API v1 policy, so it gets no mapping. + assert policy_mapping(v2_owner_sessions, CTC_REFORM_WITH_REMOVED_PARAMETER) is None + ctc_mapping = policy_mapping(v2_owner_sessions, CTC_REFORM) + assert ctc_mapping is not None + assert baseline_definition.baseline == PolicySide(policy_id=None, dynamic_id=None) + assert baseline_definition.reform == PolicySide( + policy_id=ctc_mapping.policy_id, dynamic_id=None + ) + + +def test_a_saved_report_changed_while_its_report_is_found_is_left_alone( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + saved = save_row( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=ECONOMY_REPORT, + ) + simulation_service = simulation_service_for(v2_owner_sessions, stored_rows) + + def delete_the_saved_report() -> None: + with v2_owner_sessions.begin() as session: + session.execute( + delete(UserReportAssociation).where( + col(UserReportAssociation.id) == saved + ) + ) + + simulation_service.while_answering = delete_the_saved_report + service = migration_service(runtime_sessions, v1_sessions, simulation_service) + + run = migrate(service, stored_rows) + + result = result_of(run, saved) + assert (result.outcome, result.failure_reason) == ( + RowOutcome.FAILED, + FailureReason.ROW_CHANGED, + ) + + +def test_saved_reforms_of_one_api_v1_policy_share_its_copy( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + saved_rows = [ + save_row( + v2_owner_sessions, + UserPolicy, + user_id=user_id, + legacy_policy_id=CTC_REFORM, + ) + for user_id in (stored_rows.first_user, stored_rows.second_user) + ] + service = migration_service( + runtime_sessions, + v1_sessions, + simulation_service_for(v2_owner_sessions, stored_rows), + ) + + migrate(service, stored_rows) + + mapping = policy_mapping(v2_owner_sessions, CTC_REFORM) + assert mapping is not None + assert { + stored_row(v2_owner_sessions, UserPolicy, row_id).policy_id + for row_id in saved_rows + } == {mapping.policy_id} + + +def test_a_policy_mapped_from_another_source_fails_in_the_dry_run_too( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + assert stored_rows.report_catalog is not None + with v2_owner_sessions.begin() as session: + add_row( + session, + LegacyPolicyMapping, + id=uuid4(), + country_id="us", + legacy_policy_id=CTC_REFORM, + policy_id=stored_rows.report_catalog.policy_id, + source_policy_hash="another-source-hash", + ) + saved = save_row( + v2_owner_sessions, + UserPolicy, + user_id=stored_rows.first_user, + legacy_policy_id=CTC_REFORM, + ) + service = migration_service( + runtime_sessions, + v1_sessions, + simulation_service_for(v2_owner_sessions, stored_rows), + ) + + dry_run = migrate(service, stored_rows, apply=False) + run = migrate(service, stored_rows) + + for checked in (dry_run, run): + result = result_of(checked, saved) + assert (result.outcome, result.failure_reason) == ( + RowOutcome.FAILED, + FailureReason.POLICY_NOT_COPYABLE, + ) + + +# Review round 2. + + +def test_a_run_without_the_simulation_service_writes_nothing_for_a_report( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + saved = save_row( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=ECONOMY_REPORT, + ) + service = V2SavedRecordMigrationService( + SavedRecordMigrationDatabaseSession(runtime_sessions), + V1RecordDatabaseSession(v1_sessions), + running_policyengine_version=RUNNING_VERSION, + ) + + run = migrate(service, stored_rows) + + assert result_of(run, saved).failure_reason is ( + FailureReason.SIMULATION_SERVICE_UNAVAILABLE + ) + # Nothing was copied for a report the run couldn't ask for. + assert policy_mapping(v2_owner_sessions, CTC_REFORM_WITH_ELASTICITY) is None + + +def test_an_unexpected_error_in_a_saved_household_fails_its_row_alone( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows, monkeypatch +) -> None: + from policyengine_api.services.v2.households import services as households + + def broken_copy(*_arguments: object) -> None: + message = "the household copy broke" + raise RuntimeError(message) + + monkeypatch.setattr(households, "mirror_legacy_household_in_session", broken_copy) + saved_reform = save_row( + v2_owner_sessions, + UserPolicy, + user_id=stored_rows.first_user, + legacy_policy_id=CTC_REFORM, + ) + saved_household = save_row( + v2_owner_sessions, + UserHouseholdAssociation, + user_id=stored_rows.first_user, + legacy_household_id=V1_HOUSEHOLD, + ) + service = migration_service( + runtime_sessions, + v1_sessions, + simulation_service_for(v2_owner_sessions, stored_rows), + ) + + run = migrate(service, stored_rows) + + failed = result_of(run, saved_household) + assert (failed.failure_reason, failed.failure_detail) == ( + FailureReason.UNEXPECTED_ERROR, + "RuntimeError: the household copy broke", + ) + assert result_of(run, saved_reform).outcome is RowOutcome.MIGRATED + + +def test_an_unexpected_report_error_is_met_once_for_all_its_saved_reports( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + saved_rows = [ + save_row( + v2_owner_sessions, + UserReportAssociation, + user_id=user_id, + legacy_report_id=HOUSEHOLD_REPORT, + ) + for user_id in (stored_rows.first_user, stored_rows.second_user) + ] + simulation_service = simulation_service_for(v2_owner_sessions, stored_rows) + simulation_service.broken.add(ApiV2ReportKind.HOUSEHOLD) + service = migration_service(runtime_sessions, v1_sessions, simulation_service) + + run = migrate(service, stored_rows) + + assert len(simulation_service.definitions) == 1 + for row_id in saved_rows: + assert result_of(run, row_id).failure_reason is FailureReason.UNEXPECTED_ERROR + + +def test_a_read_only_dry_run_of_the_second_mode_predicts_the_real_run( + runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows +) -> None: + for legacy_report_id, budget_window_years in ( + (HOUSEHOLD_REPORT, None), + (ECONOMY_REPORT, 10), + (MISSING_PARAMETER_REPORT, None), + (EVERY_PARAMETER_MISSING_REPORT, None), + ): + save_row( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=legacy_report_id, + budget_window_years=budget_window_years, + ) + save_row( + v2_owner_sessions, + UserPolicy, + user_id=stored_rows.first_user, + legacy_policy_id=CTC_REFORM_WITH_REMOVED_PARAMETER, + ) + simulation_service = simulation_service_for(v2_owner_sessions, stored_rows) + service = migration_service(runtime_sessions, v1_sessions, simulation_service) + read_only_service = migration_service( + read_only_sessions(runtime_sessions), v1_sessions, simulation_service + ) + + dry_run = migrate( + read_only_service, stored_rows, apply=False, drop_missing_parameters=True + ) + real_run = migrate(service, stored_rows, drop_missing_parameters=True) + + def outcomes(run: MigrationRun) -> list[tuple]: + return [ + ( + result.row_id, + result.outcome, + result.missing_parameters, + result.dropped_parameters, + result.notes, + ) + for result in run.results + ] + + assert outcomes(dry_run) == outcomes(real_run) + assert dry_run.closing_check == real_run.closing_check diff --git a/tests/unit/test_v2_integration_workflow.py b/tests/unit/test_v2_integration_workflow.py index 77f4265b3..d63fe6826 100644 --- a/tests/unit/test_v2_integration_workflow.py +++ b/tests/unit/test_v2_integration_workflow.py @@ -123,12 +123,13 @@ def test_the_job_runs_the_saved_record_migration_tests() -> None: role grants. """ commands = _step_commands(_runtime_job()) - - (command,) = [ - command - for command in commands - if "tests/integration/test_v2_saved_record_migration.py" in command - ] - assert commands.index(command) > commands.index( + grants_verified = commands.index( "uv run --frozen --extra dev python scripts/reconcile_v2_privileges.py verify" ) + + for test_file in ( + "tests/integration/test_v2_saved_record_migration.py", + "tests/integration/test_v2_saved_record_migration_failures.py", + ): + (command,) = [command for command in commands if test_file in command] + assert commands.index(command) > grants_verified From 5bd634551f8a4b8f94b4abdcc7f76d99e7546caa Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:20:32 +0400 Subject: [PATCH 12/22] Fix review round 2's quality findings in the saved-record migration MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A run without a client for the simulation service fails each saved report as simulation_service_unavailable before it reads or writes anything for it. - One helper turns an error into a failed row: a refusal keeps its reason and message, any other error only its type and first line, so a database error's statement and parameters never reach the output. - The copy plan says why missing parameters are found before an existing copy is looked up (A1 · 6). - The cross-database workflow also runs the failures' tests; the step reads only the job's existing database URLs. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/v2-integration-check.yml | 2 +- .../saved_record_migration/copies/services.py | 7 +++ .../v2/saved_record_migration/services.py | 48 +++++++++++-------- 3 files changed, 35 insertions(+), 22 deletions(-) diff --git a/.github/workflows/v2-integration-check.yml b/.github/workflows/v2-integration-check.yml index 3f7134482..12d1a7950 100644 --- a/.github/workflows/v2-integration-check.yml +++ b/.github/workflows/v2-integration-check.yml @@ -80,7 +80,7 @@ jobs: - 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 the one-time migration of saved records' API v1 references - run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_saved_record_migration.py + run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_saved_record_migration.py tests/integration/test_v2_saved_record_migration_failures.py - name: Test comparison-run persistence, the simulation API's roles, shared reports and runs, privilege reconciliation as the managed roles, the v2 migration target checks as roles that don't own the database, and the tests' database sessions run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_stage12_comparison_persistence.py tests/integration/test_v2_simulation_role_privileges.py tests/integration/test_v2_shared_report_rows.py tests/integration/test_v2_privilege_reconciliation.py tests/integration/test_v2_migration_target_persistent.py tests/integration/test_database_sessions.py - name: Test v2 household persistence, immediate v1 copying, household calculation reads and household reports diff --git a/policyengine_api/services/v2/saved_record_migration/copies/services.py b/policyengine_api/services/v2/saved_record_migration/copies/services.py index fb26d10a9..1f5cc56a7 100644 --- a/policyengine_api/services/v2/saved_record_migration/copies/services.py +++ b/policyengine_api/services/v2/saved_record_migration/copies/services.py @@ -128,6 +128,13 @@ def plan_policy_in_session( A whole API v1 policy without a copy is translated, so an error the copy would raise is found before anything is written. In the second mode, what is kept of a policy with missing parameters is translated too. + + Missing parameters are found before an existing copy is looked up, on + purpose: a copy bound to an older catalog sets the parameters the running + catalog lacks too, which API v1's ``missing_parameters`` check reports + for it. So A1 · 6 leaves such a policy's rows, as it leaves a policy + without a copy, and the second mode gives them a policy of what still + exists, which saved reforms the copy already served don't share. """ try: selected = read_policy_catalog( diff --git a/policyengine_api/services/v2/saved_record_migration/services.py b/policyengine_api/services/v2/saved_record_migration/services.py index 560c97eba..2b19e1cda 100644 --- a/policyengine_api/services/v2/saved_record_migration/services.py +++ b/policyengine_api/services/v2/saved_record_migration/services.py @@ -157,13 +157,32 @@ def _result( # noqa: PLR0913 # the record and outcome, then each optional fiel ) -def _unexpected(record: PendingSavedRecord, error: Exception) -> SavedRecordResult: - """Return the result of a row an unexpected error failed; it keeps its reference.""" +_NO_CLIENT = "this run has no client for the simulation service" +# The most an unexpected error's first line is kept to. +_ERROR_DETAIL_LENGTH = 300 + + +def _failed(record: PendingSavedRecord, error: Exception) -> SavedRecordResult: + """Return the result of a row ``error`` failed; the row keeps its reference. + + A refusal gives its reason and message. Any other error is + ``unexpected_error`` with its type and its message's first line only: a + database error's later lines hold the statement and its parameters, such + as a household's contents, which the output mustn't carry. + """ + if isinstance(error, SavedRecordMigrationRefusal): + return _result( + record, + RowOutcome.FAILED, + failure_reason=error.reason, + failure_detail=str(error), + ) + first_line = next(iter(str(error).splitlines()), "") return _result( record, RowOutcome.FAILED, failure_reason=FailureReason.UNEXPECTED_ERROR, - failure_detail=f"{type(error).__name__}: {error}", + failure_detail=f"{type(error).__name__}: {first_line[:_ERROR_DETAIL_LENGTH]}", ) @@ -369,15 +388,8 @@ def _migrate_record( if record.kind is SavedRecordKind.SAVED_REPORT: return self._migrate_saved_report(record, options, reports_this_run) return _result(record, RowOutcome.NOT_MIGRATED) - except SavedRecordMigrationRefusal as refusal: - return _result( - record, - RowOutcome.FAILED, - failure_reason=refusal.reason, - failure_detail=str(refusal), - ) except Exception as error: # noqa: BLE001 # recorded on its row, so the run still prints every row's result - return _unexpected(record, error) + return _failed(record, error) def _session(self, options: MigrationOptions) -> AbstractContextManager[Session]: """Open a transaction that commits for a run, or a read for a dry run.""" @@ -561,8 +573,7 @@ def _v1_report( def _report_id(self, definition: ApiV2ReportDefinition) -> UUID: """Ask the simulation service to find or create the report.""" if self._report_submitter is None: - msg = "migrating saved reports needs the simulation service" - raise RuntimeError(msg) + raise _refusal(FailureReason.SIMULATION_SERVICE_UNAVAILABLE, _NO_CLIENT) try: return self._report_submitter.find_or_create_report(definition) except ReportSubmissionRefusedError as error: @@ -609,15 +620,8 @@ def _migrate_saved_report( if report is None: try: report = self._report_of(record, options, window) - except SavedRecordMigrationRefusal as refusal: - report = _result( - record, - RowOutcome.FAILED, - failure_reason=refusal.reason, - failure_detail=str(refusal), - ) except Exception as error: # noqa: BLE001 # recorded for every saved report of it, so the run goes on - report = _unexpected(record, error) + report = _failed(record, error) reports_this_run[report_key] = report if ( options.apply @@ -642,6 +646,8 @@ def _report_of( report_side_in_session, ) + if options.apply and self._report_submitter is None: + raise _refusal(FailureReason.SIMULATION_SERVICE_UNAVAILABLE, _NO_CLIENT) definition, snapshots, household = self._v1_report(record) region_code = ( require_catalog_region_code( From 16066db9e1256aa0e4f93ad493ee2281dbfa1577 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:54:43 +0400 Subject: [PATCH 13/22] Fix the three guard tests the saved-record migration failed in CI - The ORM-only check refused the integration tests reading a session factory's engine (sessions.kw['bind']) to make read-only sessions. tests/fixtures/database_sessions gains v2_read_only_role_sessions, which builds read-only sessions for a role as v2_role_sessions builds them, and the dry-run tests take a read-only runtime fixture from it. - The runtime SQL boundary check matched "database.transaction(" in the service. Its session attributes are now _database_session and _v1_database_session, as other services name theirs. - The integration workflow keeps its seven coverage steps: the two saved-record migration modules join the step that tests saved records. The step reads only the job's existing database URLs. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/v2-integration-check.yml | 6 ++--- .../v2/saved_record_migration/services.py | 24 +++++++++++-------- tests/fixtures/database_sessions.py | 21 ++++++++++++++++ .../saved_record_migration_support.py | 11 --------- .../test_v2_saved_record_migration.py | 21 +++++++++++++--- ...test_v2_saved_record_migration_failures.py | 21 +++++++++++++--- 6 files changed, 73 insertions(+), 31 deletions(-) diff --git a/.github/workflows/v2-integration-check.yml b/.github/workflows/v2-integration-check.yml index 12d1a7950..2e06739ef 100644 --- a/.github/workflows/v2-integration-check.yml +++ b/.github/workflows/v2-integration-check.yml @@ -77,10 +77,8 @@ jobs: 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_publication_dynamic_parameters.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_dynamic_parameter_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 and dynamic 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_v2_dynamic_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 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 the one-time migration of saved records' API v1 references - run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_saved_record_migration.py tests/integration/test_v2_saved_record_migration_failures.py + - name: Test signed-in identity provisioning, user associations, saved detailed-save records, user types and the one-time migration of saved records + 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 tests/integration/test_v2_saved_record_migration.py tests/integration/test_v2_saved_record_migration_failures.py - name: Test comparison-run persistence, the simulation API's roles, shared reports and runs, privilege reconciliation as the managed roles, the v2 migration target checks as roles that don't own the database, and the tests' database sessions run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_stage12_comparison_persistence.py tests/integration/test_v2_simulation_role_privileges.py tests/integration/test_v2_shared_report_rows.py tests/integration/test_v2_privilege_reconciliation.py tests/integration/test_v2_migration_target_persistent.py tests/integration/test_database_sessions.py - name: Test v2 household persistence, immediate v1 copying, household calculation reads and household reports diff --git a/policyengine_api/services/v2/saved_record_migration/services.py b/policyengine_api/services/v2/saved_record_migration/services.py index 2b19e1cda..4a8f9c8a7 100644 --- a/policyengine_api/services/v2/saved_record_migration/services.py +++ b/policyengine_api/services/v2/saved_record_migration/services.py @@ -234,8 +234,8 @@ def __init__( run doesn't need one. Copies bind to the catalog of ``running_policyengine_version``, the running .py version's. """ - self._database = database - self._v1_database = v1_database + self._database_session = database + self._v1_database_session = v1_database self._report_submitter = report_submitter self._running_policyengine_version = running_policyengine_version self._region_references = region_references @@ -274,7 +274,7 @@ def compare_sample( It writes nothing and starts no run. ``user_ids`` keeps it to those owners' saved reports. """ - with self._database.read() as session: + with self._database_session.read() as session: runs = read_migrated_economy_report_runs( session, country_ids=country_ids, user_ids=user_ids, limit=size ) @@ -284,7 +284,7 @@ def compare_sample( } comparisons = [] for run in runs: - with self._v1_database.read() as session: + with self._v1_database_session.read() as session: v1_result = read_v1_report_result( session, country_id=run.country_id, report_id=run.legacy_report_id ) @@ -343,7 +343,7 @@ def _pending( countries = options.country_ids users = options.user_ids pending: list[PendingSavedRecord] = [] - with self._database.read() as session: + with self._database_session.read() as session: if SavedRecordKind.SAVED_REFORM in options.kinds: pending.extend( pending_saved_reform(row) @@ -393,7 +393,11 @@ def _migrate_record( def _session(self, options: MigrationOptions) -> AbstractContextManager[Session]: """Open a transaction that commits for a run, or a read for a dry run.""" - return self._database.transaction() if options.apply else self._database.read() + return ( + self._database_session.transaction() + if options.apply + else self._database_session.read() + ) # Saved reforms. @@ -467,7 +471,7 @@ def _migrate_saved_reform( # Policies. def _v1_policy(self, country_id: str, policy_id: int) -> LegacyPolicySnapshot: - with self._v1_database.read() as session: + with self._v1_database_session.read() as session: try: snapshot = read_v1_policy_snapshot( session, country_id=country_id, policy_id=policy_id @@ -485,7 +489,7 @@ def _v1_policy(self, country_id: str, policy_id: int) -> LegacyPolicySnapshot: def _v1_household( self, country_id: str, household_id: int ) -> LegacyHouseholdSnapshot: - with self._v1_database.read() as session: + with self._v1_database_session.read() as session: try: snapshot = read_v1_household_snapshot( session, country_id=country_id, household_id=household_id @@ -533,7 +537,7 @@ def _v1_report( LegacyHouseholdSnapshot | None, ]: """Read the API v1 report's definition, its policies and its household.""" - with self._v1_database.read() as session: + with self._v1_database_session.read() as session: report = read_v1_report( session, country_id=record.country_id, report_id=record.legacy_id ) @@ -591,7 +595,7 @@ def _country_regions(self, country_id: str) -> tuple[RegionReference, ...]: return self._references_by_country[country_id] def _point_saved_report(self, record: PendingSavedRecord, report_id: UUID) -> None: - with self._database.transaction() as session: + with self._database_session.transaction() as session: if not set_saved_report_report( session, row_id=record.row_id, diff --git a/tests/fixtures/database_sessions.py b/tests/fixtures/database_sessions.py index 9a91f44b7..5b0827bab 100644 --- a/tests/fixtures/database_sessions.py +++ b/tests/fixtures/database_sessions.py @@ -136,6 +136,27 @@ def v2_role_sessions(database_url: str, role: str) -> Iterator[sessionmaker[Sess engine.dispose() +@contextmanager +def v2_read_only_role_sessions( + database_url: str, role: str +) -> Iterator[sessionmaker[Session]]: + """Yield ``v2_role_sessions``' factories with every transaction READ ONLY. + + PostgreSQL refuses any write in them, as it does in the sessions a + command opens with ``unpooled_v2_read_only_sessions``. + """ + engine = create_engine( + database_url, + poolclass=NullPool, + connect_args={"options": f"-c role={_plain_role_name(role)}"}, + execution_options={"postgresql_readonly": True}, + ) + try: + yield build_v2_session_factory(engine) + finally: + engine.dispose() + + @contextmanager def v1_sessions(database_url: str) -> Iterator[sessionmaker[OrmSession]]: """Yield API v1's Session factories for the disposable MySQL database.""" diff --git a/tests/integration/saved_record_migration_support.py b/tests/integration/saved_record_migration_support.py index ad5b26527..2aded730b 100644 --- a/tests/integration/saved_record_migration_support.py +++ b/tests/integration/saved_record_migration_support.py @@ -23,7 +23,6 @@ from policyengine_api.data.v1_models import ReportOutput as V1ReportOutput from policyengine_api.data.v1_models import ReportOutputRun as V1ReportOutputRun from policyengine_api.data.v1_models import Simulation as V1Simulation -from policyengine_api.data.v2.database import build_v2_session_factory from policyengine_api.data.v2.models import ( Dynamic, DynamicParameter, @@ -439,16 +438,6 @@ def migration_service( ) -def read_only_sessions(sessions: sessionmaker[Session]) -> sessionmaker[Session]: - """Return the same role's sessions with every transaction READ ONLY. - - The command opens a dry run's sessions this way, so PostgreSQL refuses - any write it tried. - """ - engine = sessions.kw["bind"] - return build_v2_session_factory(engine.execution_options(postgresql_readonly=True)) - - def simulation_service_for( owner_sessions: sessionmaker[Session], rows: ApiV2Rows ) -> RecordingSimulationService: diff --git a/tests/integration/test_v2_saved_record_migration.py b/tests/integration/test_v2_saved_record_migration.py index 51fc320de..239f0ccd0 100644 --- a/tests/integration/test_v2_saved_record_migration.py +++ b/tests/integration/test_v2_saved_record_migration.py @@ -29,6 +29,7 @@ RowOutcome, SavedRecordKind, ) +from tests.fixtures.database_sessions import v2_read_only_role_sessions from tests.fixtures.economy_results import us_economy_result from tests.integration.saved_record_migration_support import ( CTC_AMOUNT, @@ -52,7 +53,6 @@ migration_service, policy_mapping, policy_values, - read_only_sessions, remaining_of, result_of, row_counts, @@ -95,6 +95,17 @@ def stored_rows( yield from stored_rows_in(v1_sessions, v2_owner_sessions) +@pytest.fixture +def read_only_runtime_sessions( + disposable_v2_database_url: str, managed_v2_roles: ManagedV2Roles +) -> Iterator[sessionmaker[Session]]: + """Yield the runtime role's sessions, every transaction READ ONLY.""" + with v2_read_only_role_sessions( + disposable_v2_database_url, managed_v2_roles.runtime + ) as sessions: + yield sessions + + # Saved reforms. @@ -480,7 +491,11 @@ def test_reports_that_cant_migrate_are_left_with_a_reason( def test_a_dry_run_writes_nothing_and_predicts_the_real_run( - runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows + runtime_sessions, + v1_sessions, + v2_owner_sessions, + stored_rows, + read_only_runtime_sessions, ) -> None: saved_rows = [ save_row( @@ -510,7 +525,7 @@ def test_a_dry_run_writes_nothing_and_predicts_the_real_run( simulation_service = simulation_service_for(v2_owner_sessions, stored_rows) service = migration_service(runtime_sessions, v1_sessions, simulation_service) read_only_service = migration_service( - read_only_sessions(runtime_sessions), v1_sessions, simulation_service + read_only_runtime_sessions, v1_sessions, simulation_service ) before = row_counts(v2_owner_sessions) diff --git a/tests/integration/test_v2_saved_record_migration_failures.py b/tests/integration/test_v2_saved_record_migration_failures.py index 2bec8dbf6..c13518e10 100644 --- a/tests/integration/test_v2_saved_record_migration_failures.py +++ b/tests/integration/test_v2_saved_record_migration_failures.py @@ -35,6 +35,7 @@ PolicySide, RowOutcome, ) +from tests.fixtures.database_sessions import v2_read_only_role_sessions from tests.integration.saved_record_migration_support import ( BASELINE_MISSING_REPORT, CTC_REFORM, @@ -54,7 +55,6 @@ migration_service, policy_mapping, policy_values, - read_only_sessions, result_of, runtime_role_sessions, save_row, @@ -90,6 +90,17 @@ def stored_rows( yield from stored_rows_in(v1_sessions, v2_owner_sessions) +@pytest.fixture +def read_only_runtime_sessions( + disposable_v2_database_url: str, managed_v2_roles: ManagedV2Roles +) -> Iterator[sessionmaker[Session]]: + """Yield the runtime role's sessions, every transaction READ ONLY.""" + with v2_read_only_role_sessions( + disposable_v2_database_url, managed_v2_roles.runtime + ) as sessions: + yield sessions + + # Review round 1. @@ -451,7 +462,11 @@ def test_an_unexpected_report_error_is_met_once_for_all_its_saved_reports( def test_a_read_only_dry_run_of_the_second_mode_predicts_the_real_run( - runtime_sessions, v1_sessions, v2_owner_sessions, stored_rows + runtime_sessions, + v1_sessions, + v2_owner_sessions, + stored_rows, + read_only_runtime_sessions, ) -> None: for legacy_report_id, budget_window_years in ( (HOUSEHOLD_REPORT, None), @@ -475,7 +490,7 @@ def test_a_read_only_dry_run_of_the_second_mode_predicts_the_real_run( simulation_service = simulation_service_for(v2_owner_sessions, stored_rows) service = migration_service(runtime_sessions, v1_sessions, simulation_service) read_only_service = migration_service( - read_only_sessions(runtime_sessions), v1_sessions, simulation_service + read_only_runtime_sessions, v1_sessions, simulation_service ) dry_run = migrate( From 86e93e85107af36a10ee0bd597f2d38d3c97b3a1 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:58:15 +0400 Subject: [PATCH 14/22] Add a failing test for read-only role sessions v2_role_sessions takes read_only, for sessions that act as a role with every transaction READ ONLY, as a dry run's are. Co-Authored-By: Claude Opus 5.5 --- tests/integration/test_database_sessions.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/integration/test_database_sessions.py b/tests/integration/test_database_sessions.py index c4b41f3cb..ad50b3809 100644 --- a/tests/integration/test_database_sessions.py +++ b/tests/integration/test_database_sessions.py @@ -40,6 +40,7 @@ query_plan, schema_inspector, truncate, + v2_role_sessions, ) from tests.integration.simulation_rows import add_row, insert_public_api_rows @@ -270,6 +271,26 @@ def test_unpooled_v2_read_only_sessions_refuse_writes( assert countries +def test_read_only_role_sessions_act_as_their_role_and_refuse_writes( + disposable_v2_database_url: str, + managed_v2_roles: ManagedV2Roles, +) -> None: + runtime_role = managed_v2_roles.runtime + with ( + v2_role_sessions( + disposable_v2_database_url, runtime_role, read_only=True + ) as sessions, + sessions() as session, + ): + acting_as = _current_user(session) + countries = session.scalars(select(col(Country.id))).all() + with pytest.raises(DBAPIError, match="read-only transaction"): + add_row(session, TaxBenefitModel, name=f"read-only-{uuid4().hex[:12]}") + + assert acting_as == runtime_role + assert countries + + def test_v1_sessions_reach_the_disposable_mysql_database( v1_sessions: sessionmaker[Session], disposable_v1_database_url: str ) -> None: From 25812c65228fa60fab4e80849337edc79b3346d0 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:59:16 +0400 Subject: [PATCH 15/22] Fold read-only role sessions into v2_role_sessions The review of the CI fix found no bug; its quality findings: - v2_role_sessions takes read_only instead of a near-copy of it, and the Alembic skill's table of session factories says so. - The saved-record migration tests' read-only runtime fixture shares its body through saved_record_migration_support. - V2SavedRecordMigrationService's parameters are named as its attributes: database_session and v1_database_session. Co-Authored-By: Claude Opus 5.5 --- docs/engineering/skills/alembic-migrations.md | 2 +- .../v2/saved_record_migration/services.py | 10 +++---- tests/fixtures/database_sessions.py | 30 +++++-------------- .../saved_record_migration_support.py | 12 ++++++++ .../test_v2_saved_record_migration.py | 10 +++---- ...test_v2_saved_record_migration_failures.py | 10 +++---- 6 files changed, 33 insertions(+), 41 deletions(-) diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 9ee2c2906..7d1da2f72 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -273,7 +273,7 @@ integration fixtures built on it (`tests/integration/conftest.py`): | Function or fixture | What it gives or does | | --- | --- | | `v2_owner_sessions(url)`; fixture `v2_owner_sessions` | Session factories of the disposable v2 PostgreSQL database's owner, its superuser. | -| `v2_role_sessions(url, role)`; fixture `v2_sessions_as_role(role)` | Session factories whose every connection starts as `role` (PostgreSQL's `role` startup option), so every statement is checked against its privileges. | +| `v2_role_sessions(url, role, *, read_only=False)`; fixture `v2_sessions_as_role(role)` | Session factories whose every connection starts as `role` (PostgreSQL's `role` startup option), so every statement is checked against its privileges. With `read_only`, every transaction is READ ONLY, as in a command's `unpooled_v2_read_only_sessions`. | | `v1_sessions(url)`; fixture `v1_sessions` | API v1's Session factories of the disposable MySQL database. | | `sqlite_v2_sessions(foreign_keys=False)` | Session factories of a new in-memory SQLite copy of the v2 schema, whose savepoints behave as on PostgreSQL (Python 3.12's sqlite3 `autocommit=False`); with `foreign_keys`, SQLite enforces the foreign keys. | | `sqlite_v1_sessions(json_serializer=None)` | API v1's Session factories of a new in-memory SQLite copy of its schema, with SQLite numbering policies. | diff --git a/policyengine_api/services/v2/saved_record_migration/services.py b/policyengine_api/services/v2/saved_record_migration/services.py index 4a8f9c8a7..0e3636b91 100644 --- a/policyengine_api/services/v2/saved_record_migration/services.py +++ b/policyengine_api/services/v2/saved_record_migration/services.py @@ -219,8 +219,8 @@ class V2SavedRecordMigrationService: def __init__( self, - database: SavedRecordMigrationDatabaseSession, - v1_database: V1RecordDatabaseSession, + database_session: SavedRecordMigrationDatabaseSession, + v1_database_session: V1RecordDatabaseSession, *, report_submitter: ReportSubmitter | None = None, running_policyengine_version: str = POLICYENGINE_VERSION, @@ -228,14 +228,14 @@ def __init__( load_region_references ), ) -> None: - """Read and write through ``database`` and read API v1 through ``v1_database``. + """Use ``database_session`` for API v2 and ``v1_database_session`` for API v1. ``report_submitter`` asks the simulation service for reports; a dry run doesn't need one. Copies bind to the catalog of ``running_policyengine_version``, the running .py version's. """ - self._database_session = database - self._v1_database_session = v1_database + self._database_session = database_session + self._v1_database_session = v1_database_session self._report_submitter = report_submitter self._running_policyengine_version = running_policyengine_version self._region_references = region_references diff --git a/tests/fixtures/database_sessions.py b/tests/fixtures/database_sessions.py index 5b0827bab..c30234663 100644 --- a/tests/fixtures/database_sessions.py +++ b/tests/fixtures/database_sessions.py @@ -115,7 +115,9 @@ def single_connection_v2_sessions( @contextmanager -def v2_role_sessions(database_url: str, role: str) -> Iterator[sessionmaker[Session]]: +def v2_role_sessions( + database_url: str, role: str, *, read_only: bool = False +) -> Iterator[sessionmaker[Session]]: """Yield Session factories whose every connection acts as ``role``. Each connection starts with ``role`` as its role (PostgreSQL's ``role`` @@ -123,33 +125,15 @@ def v2_role_sessions(database_url: str, role: str) -> Iterator[sessionmaker[Sess privileges, as in staging and production. ``act_as_owner`` would still switch a transaction to the user the connection logged in as, the database's owner, so a test acting as a role uses these factories, or - ``act_as`` on the owner's. - """ - engine = create_engine( - database_url, - poolclass=NullPool, - connect_args={"options": f"-c role={_plain_role_name(role)}"}, - ) - try: - yield build_v2_session_factory(engine) - finally: - engine.dispose() - - -@contextmanager -def v2_read_only_role_sessions( - database_url: str, role: str -) -> Iterator[sessionmaker[Session]]: - """Yield ``v2_role_sessions``' factories with every transaction READ ONLY. - - PostgreSQL refuses any write in them, as it does in the sessions a - command opens with ``unpooled_v2_read_only_sessions``. + ``act_as`` on the owner's. With ``read_only``, every transaction is READ + ONLY, as in the sessions a command opens with + ``unpooled_v2_read_only_sessions``, so PostgreSQL refuses any write. """ engine = create_engine( database_url, poolclass=NullPool, connect_args={"options": f"-c role={_plain_role_name(role)}"}, - execution_options={"postgresql_readonly": True}, + execution_options={"postgresql_readonly": True} if read_only else {}, ) try: yield build_v2_session_factory(engine) diff --git a/tests/integration/saved_record_migration_support.py b/tests/integration/saved_record_migration_support.py index 2aded730b..94594579a 100644 --- a/tests/integration/saved_record_migration_support.py +++ b/tests/integration/saved_record_migration_support.py @@ -59,6 +59,7 @@ from policyengine_api.services.v2.saved_record_migration.validators import ( ReportSubmissionRefusedError, ) +from tests.fixtures.database_sessions import v2_role_sessions from tests.integration.simulation_rows import add_row from tests.integration.stored_report_rows import ( CatalogRows, @@ -289,6 +290,17 @@ def runtime_role_sessions( return v2_sessions_as_role(managed_v2_roles.runtime) +def read_only_runtime_role_sessions( + database_url: str, roles: ManagedV2Roles +) -> Iterator[sessionmaker[Session]]: + """Yield the runtime role's sessions with every transaction READ ONLY. + + A dry run's sessions are so, and PostgreSQL refuses any write in them. + """ + with v2_role_sessions(database_url, roles.runtime, read_only=True) as sessions: + yield sessions + + def stored_rows_in( v1_sessions: sessionmaker[OrmSession], v2_owner_sessions: sessionmaker[Session], diff --git a/tests/integration/test_v2_saved_record_migration.py b/tests/integration/test_v2_saved_record_migration.py index 239f0ccd0..37b701848 100644 --- a/tests/integration/test_v2_saved_record_migration.py +++ b/tests/integration/test_v2_saved_record_migration.py @@ -29,7 +29,6 @@ RowOutcome, SavedRecordKind, ) -from tests.fixtures.database_sessions import v2_read_only_role_sessions from tests.fixtures.economy_results import us_economy_result from tests.integration.saved_record_migration_support import ( CTC_AMOUNT, @@ -53,6 +52,7 @@ migration_service, policy_mapping, policy_values, + read_only_runtime_role_sessions, remaining_of, result_of, row_counts, @@ -99,11 +99,9 @@ def stored_rows( def read_only_runtime_sessions( disposable_v2_database_url: str, managed_v2_roles: ManagedV2Roles ) -> Iterator[sessionmaker[Session]]: - """Yield the runtime role's sessions, every transaction READ ONLY.""" - with v2_read_only_role_sessions( - disposable_v2_database_url, managed_v2_roles.runtime - ) as sessions: - yield sessions + yield from read_only_runtime_role_sessions( + disposable_v2_database_url, managed_v2_roles + ) # Saved reforms. diff --git a/tests/integration/test_v2_saved_record_migration_failures.py b/tests/integration/test_v2_saved_record_migration_failures.py index c13518e10..9511493fe 100644 --- a/tests/integration/test_v2_saved_record_migration_failures.py +++ b/tests/integration/test_v2_saved_record_migration_failures.py @@ -35,7 +35,6 @@ PolicySide, RowOutcome, ) -from tests.fixtures.database_sessions import v2_read_only_role_sessions from tests.integration.saved_record_migration_support import ( BASELINE_MISSING_REPORT, CTC_REFORM, @@ -55,6 +54,7 @@ migration_service, policy_mapping, policy_values, + read_only_runtime_role_sessions, result_of, runtime_role_sessions, save_row, @@ -94,11 +94,9 @@ def stored_rows( def read_only_runtime_sessions( disposable_v2_database_url: str, managed_v2_roles: ManagedV2Roles ) -> Iterator[sessionmaker[Session]]: - """Yield the runtime role's sessions, every transaction READ ONLY.""" - with v2_read_only_role_sessions( - disposable_v2_database_url, managed_v2_roles.runtime - ) as sessions: - yield sessions + yield from read_only_runtime_role_sessions( + disposable_v2_database_url, managed_v2_roles + ) # Review round 1. From c94595c6e17dbe63819044a7f6f55f47ff0e54aa Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 05:21:51 +0400 Subject: [PATCH 16/22] Add failing tests for sending migrated reports to the simulation service MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The migration command (D4 · 1) asks the simulation service to find or create each saved report's API v2 report through POST /reports/without-run (D4 · 0), which starts no run. These tests cover the request body for each kind of report, how each answer is read, and the command building the simulation service's client only for a run that migrates saved reports. Co-Authored-By: Claude Opus 5.5 --- .../test_simulation_reports_without_runs.py | 423 ++++++++++++++++++ .../unit/test_migrate_saved_records_script.py | 120 ++++- 2 files changed, 541 insertions(+), 2 deletions(-) create mode 100644 tests/unit/libs/test_simulation_reports_without_runs.py diff --git a/tests/unit/libs/test_simulation_reports_without_runs.py b/tests/unit/libs/test_simulation_reports_without_runs.py new file mode 100644 index 000000000..bde3e9f74 --- /dev/null +++ b/tests/unit/libs/test_simulation_reports_without_runs.py @@ -0,0 +1,423 @@ +"""Find or create the migration's reports through the simulation service, with no run. + +The one-time saved-record migration (D4 · 1) sends each saved report's API v2 +definition to the simulation service's ``POST /reports/without-run`` (D4 · 0) +and keeps the report ID it answers. +""" + +from __future__ import annotations + +import dataclasses +import json +from typing import Any +from uuid import UUID + +import httpx +import pytest +from policyengine_api.libs.simulation_reports_without_runs import ( + REPORTS_WITHOUT_RUN_PATH, + SimulationServiceReportSubmitter, +) +from policyengine_api_simulation_client.api.default import create_report_without_run +from policyengine_api_simulation_client.models import ( + BudgetWindowReportRequest, + EconomyReportRequest, + HouseholdReportRequest, +) + +from policyengine_api.services.v2.saved_record_migration.types import ( + ApiV2ReportDefinition, + ApiV2ReportKind, + PolicySide, +) +from policyengine_api.services.v2.saved_record_migration.validators import ( + ReportSubmissionRefusedError, + ReportSubmissionUnavailableError, +) +from policyengine_api.services.v2.simulation_service.types import ( + SimulationServiceUnavailableError, +) + +SIMULATION_URL = "https://simulation.example.test" +ENVIRONMENT_VARIABLES = ( + "GATEWAY_AUTH_ISSUER", + "GATEWAY_AUTH_AUDIENCE", + "GATEWAY_AUTH_CLIENT_ID", + "GATEWAY_AUTH_CLIENT_SECRET", + "GATEWAY_AUTH_CLIENT_SECRET_RESOURCE", + "GATEWAY_AUTH_REQUIRED", + "SIM_ENTRYPOINT", + "OLD_SIMULATION_GATEWAY_URL", + "SIMULATION_ENTRYPOINT_URL", +) +REPORT_ID = UUID("00000000-0000-0000-0000-00000000d421") +POLICY_ID = UUID("00000000-0000-0000-0000-00000000d422") +DYNAMIC_ID = UUID("00000000-0000-0000-0000-00000000d423") +HOUSEHOLD_ID = UUID("00000000-0000-0000-0000-00000000d424") +BASELINE_SIMULATION_ID = "00000000-0000-0000-0000-00000000d425" +REFORM_SIMULATION_ID = "00000000-0000-0000-0000-00000000d426" +# What the simulation service answers once it has found or created a report. +REPORT_FOUND_OR_CREATED = { + "report_id": str(REPORT_ID), + "report_type": "economy", + "baseline_simulation_id": BASELINE_SIMULATION_ID, + "reform_simulation_id": REFORM_SIMULATION_ID, +} +CURRENT_LAW = PolicySide(policy_id=None, dynamic_id=None) +REFORM = PolicySide(policy_id=POLICY_ID, dynamic_id=DYNAMIC_ID) +ECONOMY_REPORT = ApiV2ReportDefinition( + country_id="us", + kind=ApiV2ReportKind.ECONOMY, + baseline=CURRENT_LAW, + reform=REFORM, + year=2025, + region_code="state/ca", + budget_window_size=None, + household_id=None, +) +BUDGET_WINDOW = dataclasses.replace( + ECONOMY_REPORT, + kind=ApiV2ReportKind.BUDGET_WINDOW, + region_code="us", + budget_window_size=10, +) +HOUSEHOLD_REPORT = ApiV2ReportDefinition( + country_id="uk", + kind=ApiV2ReportKind.HOUSEHOLD, + baseline=CURRENT_LAW, + reform=None, + year=None, + region_code=None, + budget_window_size=None, + household_id=HOUSEHOLD_ID, +) + + +@pytest.fixture(autouse=True) +def configured_simulation_service(monkeypatch): + """Name the Cloud Run simulation service; set no gateway credentials.""" + for name in ENVIRONMENT_VARIABLES: + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("SIMULATION_ENTRYPOINT_URL", f"{SIMULATION_URL}/") + monkeypatch.setenv("SIM_ENTRYPOINT", "old_gateway_direct") + monkeypatch.setenv("OLD_SIMULATION_GATEWAY_URL", "https://old.example.test") + + +class ScriptedService: + """The simulation service, answering every request with one scripted answer.""" + + def __init__( + self, status_code: int = 201, body: object = REPORT_FOUND_OR_CREATED + ) -> None: + self.status_code = status_code + self.body = body + self.requests: list[httpx.Request] = [] + + def answer(self, request: httpx.Request) -> httpx.Response: + self.requests.append(request) + if isinstance(self.body, bytes): + return httpx.Response(self.status_code, content=self.body) + return httpx.Response(self.status_code, json=self.body) + + def submit(self, definition: ApiV2ReportDefinition) -> UUID: + submitter = SimulationServiceReportSubmitter.from_environment( + transport=httpx.MockTransport(self.answer) + ) + return submitter.find_or_create_report(definition) + + def sent_body(self) -> dict[str, Any]: + (request,) = self.requests + return json.loads(request.content) + + +def _submitter_raising( + error_type: type[httpx.TransportError], +) -> SimulationServiceReportSubmitter: + def fail(request: httpx.Request) -> httpx.Response: + msg = "the transport failed" + raise error_type(msg, request=request) + + return SimulationServiceReportSubmitter.from_environment( + transport=httpx.MockTransport(fail) + ) + + +def test_an_economy_report_is_found_or_created_by_its_definition_without_a_run() -> ( + None +): + service = ScriptedService() + + report_id = service.submit(ECONOMY_REPORT) + + assert report_id == REPORT_ID + (request,) = service.requests + assert request.method == "POST" + assert str(request.url) == f"{SIMULATION_URL}/reports/without-run" + assert REPORTS_WITHOUT_RUN_PATH == "/reports/without-run" + assert service.sent_body() == { + "country": "us", + "report_type": "economy", + "year": 2025, + "region_code": "state/ca", + "baseline": {"policy_id": None, "dynamic_id": None}, + "reform": {"policy_id": str(POLICY_ID), "dynamic_id": str(DYNAMIC_ID)}, + "include_cliffs": False, + } + + +def test_a_budget_window_sends_its_size_and_no_cliff_impacts() -> None: + service = ScriptedService() + + service.submit(BUDGET_WINDOW) + + assert service.sent_body() == { + "country": "us", + "report_type": "budget_window", + "year": 2025, + "region_code": "us", + "baseline": {"policy_id": None, "dynamic_id": None}, + "reform": {"policy_id": str(POLICY_ID), "dynamic_id": str(DYNAMIC_ID)}, + "budget_window_size": 10, + } + + +def test_a_household_report_of_the_baseline_alone_names_its_household() -> None: + service = ScriptedService() + + service.submit(HOUSEHOLD_REPORT) + + assert service.sent_body() == { + "country": "uk", + "report_type": "household", + "household_id": str(HOUSEHOLD_ID), + "baseline": {"policy_id": None}, + "reform": None, + } + + +def test_a_household_side_names_its_dynamic_only_when_it_has_one() -> None: + service = ScriptedService() + + service.submit( + dataclasses.replace( + HOUSEHOLD_REPORT, + baseline=PolicySide(policy_id=None, dynamic_id=DYNAMIC_ID), + reform=PolicySide(policy_id=POLICY_ID, dynamic_id=None), + ) + ) + + body = service.sent_body() + assert body["baseline"] == {"policy_id": None, "dynamic_id": str(DYNAMIC_ID)} + assert body["reform"] == {"policy_id": str(POLICY_ID)} + + +@pytest.mark.parametrize( + ("definition", "generated_model"), + [ + (ECONOMY_REPORT, EconomyReportRequest), + (BUDGET_WINDOW, BudgetWindowReportRequest), + (HOUSEHOLD_REPORT, HouseholdReportRequest), + ], +) +def test_each_report_is_the_request_the_generated_operation_builds( + definition: ApiV2ReportDefinition, + generated_model: type[ + EconomyReportRequest | BudgetWindowReportRequest | HouseholdReportRequest + ], +) -> None: + service = ScriptedService() + + service.submit(definition) + + (request,) = service.requests + generated = create_report_without_run._get_kwargs( + body=generated_model.from_dict(service.sent_body()) + ) + assert (request.method, request.url.path) == ( + generated["method"].upper(), + generated["url"], + ) + assert service.sent_body() == generated["json"] + assert request.headers["content-type"] == generated["headers"]["Content-Type"] + + +@pytest.mark.parametrize("status_code", [201, 202]) +def test_a_report_found_or_created_is_read_from_either_created_status( + status_code: int, +) -> None: + assert ScriptedService(status_code).submit(ECONOMY_REPORT) == REPORT_ID + + +def test_an_economy_report_without_a_reform_is_not_sent() -> None: + service = ScriptedService() + + with pytest.raises(ValueError, match="names a reform"): + service.submit(dataclasses.replace(ECONOMY_REPORT, reform=None)) + + assert service.requests == [] + + +def test_a_definition_the_report_inputs_refuse_is_refused_unsent() -> None: + service = ScriptedService() + + with pytest.raises(ReportSubmissionRefusedError) as refused: + service.submit(dataclasses.replace(ECONOMY_REPORT, year=1800)) + + assert refused.value.code == "invalid_report_definition" + assert "year" in str(refused.value) + assert service.requests == [] + + +@pytest.mark.parametrize( + "body", + [ + b"not json", + {"report_id": "not-a-uuid"}, + {"report_type": "economy"}, + ], +) +def test_a_created_answer_that_cannot_be_read_can_be_sent_again(body: object) -> None: + with pytest.raises(ReportSubmissionUnavailableError) as unavailable: + ScriptedService(201, body).submit(ECONOMY_REPORT) + + assert str(unavailable.value) == ( + "its answer naming the report can't be read (201); running the command " + "again finds the report by its definition" + ) + + +def test_a_refusal_names_the_services_code_and_reason() -> None: + service = ScriptedService( + 400, + {"detail": "Region state/zz is not in the catalog", "code": "unknown_region"}, + ) + + with pytest.raises(ReportSubmissionRefusedError) as refused: + service.submit(ECONOMY_REPORT) + + assert refused.value.code == "unknown_region" + assert str(refused.value) == "Region state/zz is not in the catalog" + + +def test_a_refusal_of_request_fields_names_each_field_and_its_status() -> None: + service = ScriptedService( + 422, + { + "detail": [ + {"loc": ["body", "year"], "msg": "Input should be at most 2200"}, + {"loc": ["body", "region_code"], "msg": "Field required"}, + ] + }, + ) + + with pytest.raises(ReportSubmissionRefusedError) as refused: + service.submit(ECONOMY_REPORT) + + assert refused.value.code == "422" + assert str(refused.value) == ( + "year: Input should be at most 2200; region_code: Field required" + ) + + +@pytest.mark.parametrize( + "body", + [ + b"Bad request", + {"detail": "Bad request", "code": "Traceback (most recent call last)"}, + ], +) +def test_a_refusal_names_only_a_code_that_is_a_fixed_identifier(body: object) -> None: + with pytest.raises(ReportSubmissionRefusedError) as refused: + ScriptedService(400, body).submit(ECONOMY_REPORT) + + assert refused.value.code == "400" + assert "Traceback" not in str(refused.value) + + +def test_a_refusal_whose_reason_cannot_be_read_says_so() -> None: + with pytest.raises(ReportSubmissionRefusedError) as refused: + ScriptedService(422, b"not json").submit(ECONOMY_REPORT) + + assert str(refused.value) == "the simulation service gave no readable reason" + + +@pytest.mark.parametrize( + ("status_code", "body", "status_text"), + [ + ( + 503, + { + "detail": "manifest at gs://bucket/secret", + "code": "manifest_unavailable", + }, + "503 manifest_unavailable", + ), + (503, b"Service Unavailable", "503"), + ( + 500, + {"detail": "KeyError: 'x'", "code": "internal_error"}, + "500 internal_error", + ), + (502, b"Bad Gateway", "502"), + (504, b"Gateway Timeout", "504"), + (403, b"Forbidden", "403"), + (404, {"detail": "Not Found"}, "404"), + (429, b"Too Many Requests", "429"), + ], +) +def test_any_other_answer_can_be_sent_again_and_names_no_reason( + status_code: int, body: object, status_text: str +) -> None: + with pytest.raises(ReportSubmissionUnavailableError) as unavailable: + ScriptedService(status_code, body).submit(ECONOMY_REPORT) + + assert str(unavailable.value) == ( + f"it answered {status_text}; running the command again finds or creates " + "the report by its definition" + ) + + +@pytest.mark.parametrize( + "error_type", [httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout] +) +def test_a_connection_never_made_can_be_sent_again( + error_type: type[httpx.TransportError], +) -> None: + with pytest.raises(ReportSubmissionUnavailableError, match="could not be reached"): + _submitter_raising(error_type).find_or_create_report(ECONOMY_REPORT) + + +@pytest.mark.parametrize( + "error_type", [httpx.ReadTimeout, httpx.ReadError, httpx.RemoteProtocolError] +) +def test_an_answer_lost_after_sending_can_be_sent_again( + error_type: type[httpx.TransportError], +) -> None: + with pytest.raises(ReportSubmissionUnavailableError) as lost: + _submitter_raising(error_type).find_or_create_report(ECONOMY_REPORT) + + assert str(lost.value) == ( + "The simulation service may have received the request, but its answer " + f"was lost ({error_type.__name__}). Running the command again finds the " + "report it created by its definition." + ) + + +def test_without_the_simulation_service_configured_no_submitter_is_built( + monkeypatch, +) -> None: + monkeypatch.delenv("SIMULATION_ENTRYPOINT_URL") + + with pytest.raises(SimulationServiceUnavailableError, match="not configured"): + SimulationServiceReportSubmitter.from_environment() + + +def test_closing_the_submitter_closes_its_http_client() -> None: + submitter = SimulationServiceReportSubmitter.from_environment( + transport=httpx.MockTransport(ScriptedService().answer) + ) + + submitter.close() + + with pytest.raises(RuntimeError, match="closed"): + submitter.find_or_create_report(ECONOMY_REPORT) diff --git a/tests/unit/test_migrate_saved_records_script.py b/tests/unit/test_migrate_saved_records_script.py index 4a4402638..2ca1828fa 100644 --- a/tests/unit/test_migrate_saved_records_script.py +++ b/tests/unit/test_migrate_saved_records_script.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +import os import subprocess import sys from contextlib import contextmanager @@ -23,6 +24,9 @@ SavedRecordKind, SavedRecordResult, ) +from policyengine_api.services.v2.simulation_service.types import ( + SimulationServiceUnavailableError, +) from scripts import migrate_saved_records_to_api_v2 as command if TYPE_CHECKING: @@ -31,6 +35,21 @@ FIRST_USER = UUID("00000000-0000-0000-0000-00000000d411") SECOND_USER = UUID("00000000-0000-0000-0000-00000000d412") SAVED_ROW = UUID("00000000-0000-0000-0000-00000000d413") +# The settings API v1's simulation client reads, which a test's new process +# gets only as the test sets them. +SIMULATION_SETTINGS = frozenset( + { + "GATEWAY_AUTH_ISSUER", + "GATEWAY_AUTH_AUDIENCE", + "GATEWAY_AUTH_CLIENT_ID", + "GATEWAY_AUTH_CLIENT_SECRET", + "GATEWAY_AUTH_CLIENT_SECRET_RESOURCE", + "GATEWAY_AUTH_REQUIRED", + "SIM_ENTRYPOINT", + "OLD_SIMULATION_GATEWAY_URL", + "SIMULATION_ENTRYPOINT_URL", + } +) class FakeMigrator: @@ -69,15 +88,23 @@ def migrate(self, options: MigrationOptions) -> MigrationRun: class RecordingFactory: - """Build ``migrator``, recording whether each build was for a dry run.""" + """Build ``migrator``, recording whether each build was for a dry run. + + ``report_submissions`` records whether each build was asked for the + simulation service's report client. + """ def __init__(self, migrator: FakeMigrator) -> None: self.migrator = migrator self.dry_runs: list[bool] = [] + self.report_submissions: list[bool] = [] @contextmanager - def __call__(self, *, dry_run: bool) -> Iterator[FakeMigrator]: + def __call__( + self, *, dry_run: bool, submits_reports: bool + ) -> Iterator[FakeMigrator]: self.dry_runs.append(dry_run) + self.report_submissions.append(submits_reports) yield self.migrator @@ -223,6 +250,95 @@ def test_a_sample_comparison_takes_no_migration_flag(arguments) -> None: assert factory.dry_runs == [] +@pytest.mark.parametrize( + ("arguments", "submits_reports"), + [ + ([], True), + (["--kind", "saved_report"], True), + (["--kind", "saved_reform", "--kind", "saved_household"], False), + (["--dry-run"], False), + (["--compare-sample", "5"], False), + ], +) +def test_only_a_run_that_migrates_saved_reports_builds_the_report_client( + arguments: list[str], + submits_reports: bool, # noqa: FBT001 # pytest passes parameters positionally +) -> None: + factory = RecordingFactory(FakeMigrator()) + + _run(arguments, factory) + + assert factory.report_submissions == [submits_reports] + + +def test_a_run_without_the_simulation_service_stops_before_connecting( + monkeypatch, +) -> None: + monkeypatch.delenv("SIMULATION_ENTRYPOINT_URL", raising=False) + monkeypatch.delenv("V2_RUNTIME_DATABASE_URL", raising=False) + monkeypatch.delenv("POLICYENGINE_DB_READONLY_PASSWORD", raising=False) + monkeypatch.setenv("SIM_ENTRYPOINT", "old_gateway_direct") + monkeypatch.setenv("OLD_SIMULATION_GATEWAY_URL", "https://old.example.test") + + building = command._migrator_from_environment(dry_run=False, submits_reports=True) + + with pytest.raises(SimulationServiceUnavailableError, match="not configured"): + building.__enter__() + + +def _run_in_a_new_process(code: str, **environment: str) -> subprocess.CompletedProcess: + inherited = { + name: value + for name, value in os.environ.items() + if name not in SIMULATION_SETTINGS + } + return subprocess.run( + [sys.executable, "-c", code], + cwd=REPO, + capture_output=True, + text=True, + check=False, + env={**inherited, **environment}, + ) + + +def test_the_report_clients_log_records_leave_the_document_alone_on_stdout() -> None: + """Loading API v1's simulation client builds its logging runtime. + + That runtime writes log records to the standard output it finds when it + is built, where the command prints its JSON document. + """ + result = _run_in_a_new_process( + "import logging\n" + "from scripts import migrate_saved_records_to_api_v2 as command\n" + "command._report_submitter_from_environment().close()\n" + "logging.getLogger('migration').warning('a record after loading')\n" + "print('the document')\n", + SIM_ENTRYPOINT="cloud_run_simulation_entrypoint", + SIMULATION_ENTRYPOINT_URL="https://simulation.example.test", + ) + + assert result.returncode == 0, result.stderr + assert result.stdout == "the document\n" + assert "a record after loading" in result.stderr + + +def test_the_report_client_without_its_entrypoint_settings_names_them() -> None: + result = _run_in_a_new_process( + "from scripts import migrate_saved_records_to_api_v2 as command\n" + "try:\n" + " command._report_submitter_from_environment()\n" + "except command.MissingSettingError as error:\n" + " print(error)\n", + SIM_ENTRYPOINT="old_gateway_direct", + SIMULATION_ENTRYPOINT_URL="https://simulation.example.test", + ) + + assert result.returncode == 0, result.stderr + assert "SIM_ENTRYPOINT=cloud_run_simulation_entrypoint" in result.stdout + assert "OLD_SIMULATION_GATEWAY_URL is required" in result.stdout + + def test_v1_is_read_as_the_read_only_role_through_the_proxy() -> None: url = command.v1_read_only_database_url( {"POLICYENGINE_DB_READONLY_PASSWORD": "reader-secret"} From 05932500c08f6970e84161e3f79412536adf0710 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 05:24:51 +0400 Subject: [PATCH 17/22] Send migrated reports to the simulation service without starting a run MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SimulationServiceReportSubmitter sends each saved report's API v2 definition to POST /reports/without-run (D4 · 0), with the body API v1's POST /v2/reports builds for the same report, and returns the report the service found or created. A 400 or 422 is a refusal with the service's code and reason; any other answer leaves the row for the next run, which finds the same report by its definition. The command builds the client only for a run that migrates saved reports, before it connects to either database, and loads it with standard output sent to standard error, so the log records of the runtime it builds stay off the JSON document. Co-Authored-By: Claude Opus 5.5 --- changelog.d/saved-record-migration.added.md | 2 +- .../libs/simulation_reports_without_runs.py | 260 ++++++++++++++++++ .../libs/simulation_service_operations.py | 22 +- pyproject.toml | 1 + scripts/migrate_saved_records_to_api_v2.py | 86 ++++-- .../test_simulation_reports_without_runs.py | 8 +- .../unit/test_migrate_saved_records_script.py | 17 +- 7 files changed, 365 insertions(+), 31 deletions(-) create mode 100644 policyengine_api/libs/simulation_reports_without_runs.py diff --git a/changelog.d/saved-record-migration.added.md b/changelog.d/saved-record-migration.added.md index 7bcb27418..e1e302b2c 100644 --- a/changelog.d/saved-record-migration.added.md +++ b/changelog.d/saved-record-migration.added.md @@ -1 +1 @@ -Add API v1's one-time command that gives saved reforms, saved households and saved reports holding only an API v1 reference their API v2 records, splitting each API v1 policy's model assumptions into a dynamic, with a dry run, a mode that drops parameters the running catalog lacks, and a closing check. +Add API v1's one-time command that gives saved reforms, saved households and saved reports holding only an API v1 reference their API v2 records, splitting each API v1 policy's model assumptions into a dynamic, with a dry run, a mode that drops parameters the running catalog lacks, and a closing check. Each saved report's report is found or created through the simulation service's `POST /reports/without-run`, which starts no run. diff --git a/policyengine_api/libs/simulation_reports_without_runs.py b/policyengine_api/libs/simulation_reports_without_runs.py new file mode 100644 index 000000000..60093bb27 --- /dev/null +++ b/policyengine_api/libs/simulation_reports_without_runs.py @@ -0,0 +1,260 @@ +"""Find or create the saved-record migration's reports, starting no run (D4 · 1). + +The one-time saved-record migration gives each saved report that holds only +an API v1 report output the API v2 report the simulation service finds or +creates for that output's definition. ``SimulationServiceReportSubmitter`` +sends the definition to the service's ``POST /reports/without-run`` +(D4 · 0). The route looks the report up by the key ``POST /reports`` uses, +and creates the report and its simulations when none matches, but starts no +run: app v3 starts a report's first run through +``POST /v2/reports/{report_id}/runs`` when someone opens it. + +The request body is the one API v1's ``POST /v2/reports`` sends the service +for the same report, built from the same creation inputs by +``policyengine_api.libs.simulation_reports``. An economy report asks for no +cliff impacts, which this route refuses. + +The route finds a report it created by its definition, so sending the same +definition again creates nothing more. Every answer but a found or created +report and a refusal therefore raises ReportSubmissionUnavailableError, which +leaves the saved report on its API v1 reference for the command's next run to +send again: the service unreachable, unavailable or failing, a proxy's answer +in its place, an answer lost after the request was sent, or a created answer +that can't be read. Such an error names the status, and the service's code +when that is a fixed identifier, never the service's reason, which may be an +exception's text. A 400 or 422 raises ReportSubmissionRefusedError with that +code, or the status without one, and the service's reason. A definition the +creation inputs refuse is refused before anything is sent. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any +from uuid import UUID + +from pydantic import ValidationError + +from policyengine_api.libs.simulation_service_answers import ( + CREATED_STATUSES, + REFUSAL_STATUSES, + AnswerModel, + Refusal, + SimulationAnswer, + fixed_identifier_code, + parsed_body, + refusal_reason, + send_to_simulation_service, + simulation_service_http_client, + status_and_code, +) +from policyengine_api.libs.simulation_service_operations import ( + post_report_without_run, +) +from policyengine_api.services.v2.saved_record_migration.types import ( + ApiV2ReportKind, +) +from policyengine_api.services.v2.saved_record_migration.validators import ( + ReportSubmissionRefusedError, + ReportSubmissionUnavailableError, +) +from policyengine_api.services.v2.simulation_service.types import ( + BudgetWindowReportCreationInput, + EconomyReportCreationInput, + HouseholdPolicyChoice, + HouseholdReportCreationInput, + PolicyChoice, + SimulationServiceAnswerUnreadableError, + SimulationServiceUnavailableError, +) + +if TYPE_CHECKING: + import httpx + + from policyengine_api.services.v2.saved_record_migration.types import ( + ApiV2ReportDefinition, + PolicySide, + ) + +# The route's path, which tests check requests against. The generated +# operation holds its own copy, which it sends the request to. +REPORTS_WITHOUT_RUN_PATH = "/reports/without-run" +# The code of a definition the creation inputs refuse before it is sent. +INVALID_REPORT_DEFINITION = "invalid_report_definition" +# What to do after an answer lost once the request may have arrived. +SEND_AGAIN = "Running the command again finds the report it created by its definition." +NO_READABLE_REASON = "the simulation service gave no readable reason" + + +class _ReportWithoutRun(AnswerModel): + """The found or created report's answer, of which only its ID is read.""" + + report_id: UUID + + +def _policy_choice(side: PolicySide) -> PolicyChoice: + return PolicyChoice(policy_id=side.policy_id, dynamic_id=side.dynamic_id) + + +def _household_policy_choice(side: PolicySide) -> HouseholdPolicyChoice: + return HouseholdPolicyChoice(policy_id=side.policy_id, dynamic_id=side.dynamic_id) + + +def _invalid_fields(error: ValidationError) -> str: + """Return each field the creation input refuses and why, on one line.""" + return "; ".join( + f"{'.'.join(str(part) for part in detail['loc'])}: {detail['msg']}" + for detail in error.errors() + ) + + +def _household_report_input( + definition: ApiV2ReportDefinition, +) -> HouseholdReportCreationInput: + return HouseholdReportCreationInput( + country_id=definition.country_id, + kind="household", + household_id=definition.household_id, + baseline=_household_policy_choice(definition.baseline), + reform=( + None + if definition.reform is None + else _household_policy_choice(definition.reform) + ), + ) + + +def _report_sides( + definition: ApiV2ReportDefinition, +) -> tuple[PolicyChoice, PolicyChoice]: + """Return an economy report's or budget window's baseline and reform. + + Raise ValueError when it has no reform, which the migration never builds. + """ + if definition.reform is None: + msg = f"an {definition.kind.value} report names a reform" + raise ValueError(msg) + return _policy_choice(definition.baseline), _policy_choice(definition.reform) + + +def report_without_run_request(definition: ApiV2ReportDefinition) -> dict[str, Any]: + """Return the request body for the definition, as ``POST /v2/reports`` builds it. + + Raise ValueError for an economy report or budget window without a + reform, which the migration never builds, and + ReportSubmissionRefusedError when the creation inputs refuse the + definition, such as a year outside the years the service stores. + """ + # simulation_reports holds API v1's report routes' process-wide client, + # so it is imported only when a report is sent. + from policyengine_api.libs.simulation_reports import ( + budget_window_request, + household_report_request, + report_request, + ) + + try: + if definition.kind is ApiV2ReportKind.HOUSEHOLD: + return household_report_request(_household_report_input(definition)) + baseline, reform = _report_sides(definition) + if definition.kind is ApiV2ReportKind.BUDGET_WINDOW: + return budget_window_request( + BudgetWindowReportCreationInput( + country_id=definition.country_id, + kind="budget_window", + year=definition.year, + region_code=definition.region_code, + baseline=baseline, + reform=reform, + budget_window_size=definition.budget_window_size, + ) + ) + return report_request( + EconomyReportCreationInput( + country_id=definition.country_id, + kind="economy", + year=definition.year, + region_code=definition.region_code, + baseline=baseline, + reform=reform, + ) + ) + except ValidationError as error: + msg = f"the report's definition isn't valid: {_invalid_fields(error)}" + raise ReportSubmissionRefusedError(INVALID_REPORT_DEFINITION, msg) from error + + +def _refusal_text(answer: SimulationAnswer) -> str: + try: + return refusal_reason(Refusal.model_validate_json(answer.content)) + except ValidationError: + return NO_READABLE_REASON + + +def _found_or_created_report_id(answer: SimulationAnswer) -> UUID: + """Return the ID the answer names, or raise for any other answer.""" + if answer.status_code in CREATED_STATUSES: + try: + return _ReportWithoutRun.model_validate_json(answer.content).report_id + except ValidationError as error: + msg = ( + f"its answer naming the report can't be read ({answer.status_code}); " + "running the command again finds the report by its definition" + ) + raise ReportSubmissionUnavailableError(msg) from error + code = fixed_identifier_code(parsed_body(answer)) + if answer.status_code in REFUSAL_STATUSES: + raise ReportSubmissionRefusedError( + code or str(answer.status_code), _refusal_text(answer) + ) + msg = ( + f"it answered {status_and_code(answer.status_code, code)}; running the " + "command again finds or creates the report by its definition" + ) + raise ReportSubmissionUnavailableError(msg) + + +class SimulationServiceReportSubmitter: + """Finds or creates the migration's reports through the simulation service.""" + + def __init__(self, http_client: httpx.Client) -> None: + """Send requests on ``http_client``, which names the service's base URL.""" + self._http_client = http_client + + @classmethod + def from_environment( + cls, *, transport: httpx.BaseTransport | None = None + ) -> SimulationServiceReportSubmitter: + """Build the submitter on the configured Cloud Run simulation service. + + Raise SimulationServiceUnavailableError when + ``SIMULATION_ENTRYPOINT_URL`` is missing or invalid, or the gateway + credentials (``GATEWAY_AUTH_*``) are partly set, or required but + unset. ``transport`` replaces the simulation transport, for tests. + """ + return cls(simulation_service_http_client(transport=transport)) + + def close(self) -> None: + """Close the HTTP client; the submitter sends nothing afterwards.""" + self._http_client.close() + + def find_or_create_report(self, definition: ApiV2ReportDefinition) -> UUID: + """Return the ID of the report the service found or created; start no run. + + Raise ReportSubmissionRefusedError when the definition is refused, + and ReportSubmissionUnavailableError for any other answer but a + found or created report. + """ + body = report_without_run_request(definition) + try: + answer = send_to_simulation_service( + post_report_without_run, + self._http_client, + body, + submit_again_sentence=SEND_AGAIN, + ) + except ( + SimulationServiceUnavailableError, + SimulationServiceAnswerUnreadableError, + ) as error: + raise ReportSubmissionUnavailableError(str(error)) from error + return _found_or_created_report_id(answer) diff --git a/policyengine_api/libs/simulation_service_operations.py b/policyengine_api/libs/simulation_service_operations.py index be987c179..cb559997e 100644 --- a/policyengine_api/libs/simulation_service_operations.py +++ b/policyengine_api/libs/simulation_service_operations.py @@ -61,6 +61,9 @@ from policyengine_api_simulation_client.api.default.create_report import ( _get_kwargs as report_request_arguments, ) +from policyengine_api_simulation_client.api.default.create_report_without_run import ( + _get_kwargs as report_without_run_request_arguments, +) from policyengine_api_simulation_client.api.default.create_simulation import ( _get_kwargs as simulation_request_arguments, ) @@ -86,8 +89,8 @@ import httpx -# The generated model of each kind of report sent to POST /reports, by the -# body's report_type. +# The generated model of each kind of report sent to POST /reports and +# POST /reports/without-run, by the body's report_type. REPORT_REQUEST_MODELS: dict[ str, type[EconomyReportRequest | BudgetWindowReportRequest | HouseholdReportRequest], @@ -182,6 +185,21 @@ def post_report(http_client: httpx.Client, body: dict[str, Any]) -> SimulationAn ) +def post_report_without_run( + http_client: httpx.Client, body: dict[str, Any] +) -> SimulationAnswer: + """Find or create a report, starting no run (``POST /reports/without-run``). + + The body is the one ``post_report`` sends for the same report, and its + ``report_type`` selects its generated model. Raise what + ``send_request_with_body`` raises. + """ + request = REPORT_REQUEST_MODELS[body["report_type"]].from_dict(body) + return send_request_with_body( + http_client, report_without_run_request_arguments(body=request), body + ) + + def post_report_rerun( http_client: httpx.Client, report_id: UUID, body: dict[str, Any] ) -> SimulationAnswer: diff --git a/pyproject.toml b/pyproject.toml index 17710d86e..d2ff17d5e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -410,6 +410,7 @@ banned-module-level-imports = [ "policyengine_api.libs.postmark_email", "policyengine_api.libs.simulation_household_calculations", "policyengine_api.libs.simulation_reports", + "policyengine_api.libs.simulation_reports_without_runs", "policyengine_api.services.v2.countries.database_session", "policyengine_api.services.v2.countries.services", "policyengine_api.services.v2.dynamics.database_session", diff --git a/scripts/migrate_saved_records_to_api_v2.py b/scripts/migrate_saved_records_to_api_v2.py index da408b1fc..5764bd76d 100755 --- a/scripts/migrate_saved_records_to_api_v2.py +++ b/scripts/migrate_saved_records_to_api_v2.py @@ -49,16 +49,24 @@ and ``V2_SUPABASE_ENVIRONMENT``; a dry run's transactions are read only; - API v1's database read only, as ``policyengine_schema_reader`` through the Cloud SQL Auth Proxy on 127.0.0.1 (``POLICYENGINE_DB_READONLY_PASSWORD``, - and ``POLICYENGINE_DB_PROXY_PORT``, 3307 without it). + and ``POLICYENGINE_DB_PROXY_PORT``, 3307 without it); +- for a run that migrates saved reports, the Cloud Run simulation service at + ``SIMULATION_ENTRYPOINT_URL`` with the gateway credentials + (``GATEWAY_AUTH_*``). API v1's simulation client also reads the v1 + economy routes' setting when loaded, so set + ``SIM_ENTRYPOINT=cloud_run_simulation_entrypoint`` too. Each saved report's + report is found or created through ``POST /reports/without-run``, which + starts no run: app v3 starts a report's first run when it is opened. + A dry run calls no other service. """ from __future__ import annotations import argparse +import contextlib import json import os import sys -from contextlib import contextmanager from typing import TYPE_CHECKING, Protocol from uuid import UUID @@ -79,6 +87,9 @@ from collections.abc import Callable, Iterator, Mapping, Sequence from contextlib import AbstractContextManager + from policyengine_api.libs.simulation_reports_without_runs import ( + SimulationServiceReportSubmitter, + ) from policyengine_api.services.v2.saved_record_migration.types import ( MigrationRun, SampleComparison, @@ -129,9 +140,42 @@ def v1_read_only_database_url(environ: Mapping[str, str]) -> URL: ) -@contextmanager -def _migrator_from_environment(*, dry_run: bool) -> Iterator[SavedRecordMigrator]: - """Build the migration service on the deployed API v1's connections.""" +def _report_submitter_from_environment() -> SimulationServiceReportSubmitter: + """Build the simulation service's report client from the deployed settings. + + Loading API v1's simulation client builds API v1's logging runtime, which + writes log records to the standard output it finds when it is built. It + is loaded with standard output sent to standard error, so the command's + JSON document is alone on standard output. Raise MissingSettingError when + loading it refuses the v1 economy routes' entrypoint settings, and + SimulationServiceUnavailableError when the simulation service isn't + configured. + """ + try: + with contextlib.redirect_stdout(sys.stderr): + from policyengine_api.libs.simulation_reports_without_runs import ( + SimulationServiceReportSubmitter, + ) + except ValueError as error: + msg = ( + "API v1's simulation client can't be loaded; set " + "SIM_ENTRYPOINT=cloud_run_simulation_entrypoint with " + f"SIMULATION_ENTRYPOINT_URL: {error}" + ) + raise MissingSettingError(msg) from error + return SimulationServiceReportSubmitter.from_environment() + + +@contextlib.contextmanager +def _migrator_from_environment( + *, dry_run: bool, submits_reports: bool +) -> Iterator[SavedRecordMigrator]: + """Build the migration service on the deployed API v1's connections. + + A run that ``submits_reports`` builds the simulation service's report + client first, so missing settings stop it before it connects to either + database. + """ # These modules are imported only when the command runs, as they read the # database settings or need the connections. from policyengine_api.data.v2.database import ( @@ -146,18 +190,25 @@ def _migrator_from_environment(*, dry_run: bool) -> Iterator[SavedRecordMigrator V2SavedRecordMigrationService, ) - v2_url = load_v2_runtime_database_settings().connection.url - v1_url = v1_read_only_database_url(os.environ) - open_v2_sessions = ( - unpooled_v2_read_only_sessions if dry_run else unpooled_v2_sessions - ) - with ( - open_v2_sessions(v2_url) as v2_sessions, - unpooled_v1_sessions(v1_url) as v1_sessions, - ): + with contextlib.ExitStack() as resources: + report_submitter = ( + resources.enter_context( + contextlib.closing(_report_submitter_from_environment()) + ) + if submits_reports + else None + ) + v2_url = load_v2_runtime_database_settings().connection.url + v1_url = v1_read_only_database_url(os.environ) + open_v2_sessions = ( + unpooled_v2_read_only_sessions if dry_run else unpooled_v2_sessions + ) + v2_sessions = resources.enter_context(open_v2_sessions(v2_url)) + v1_sessions = resources.enter_context(unpooled_v1_sessions(v1_url)) yield V2SavedRecordMigrationService( SavedRecordMigrationDatabaseSession(v2_sessions), V1RecordDatabaseSession(v1_sessions), + report_submitter=report_submitter, ) @@ -290,14 +341,17 @@ def main( or arguments.kinds is not None ): parser.error("--compare-sample takes only --country") - with migrator_factory(dry_run=True) as migrator: + with migrator_factory(dry_run=True, submits_reports=False) as migrator: comparison = migrator.compare_sample( size=arguments.compare_sample, country_ids=countries ) print(json.dumps(sample_comparison_document(comparison), indent=2)) return 0 options = _options(arguments) - with migrator_factory(dry_run=arguments.dry_run) as migrator: + submits_reports = options.apply and SavedRecordKind.SAVED_REPORT in options.kinds + with migrator_factory( + dry_run=arguments.dry_run, submits_reports=submits_reports + ) as migrator: run = migrator.migrate(options) print(json.dumps(migration_document(run), indent=2)) return 0 if run.closing_check.passed else 1 diff --git a/tests/unit/libs/test_simulation_reports_without_runs.py b/tests/unit/libs/test_simulation_reports_without_runs.py index bde3e9f74..ffb04472a 100644 --- a/tests/unit/libs/test_simulation_reports_without_runs.py +++ b/tests/unit/libs/test_simulation_reports_without_runs.py @@ -14,10 +14,6 @@ import httpx import pytest -from policyengine_api.libs.simulation_reports_without_runs import ( - REPORTS_WITHOUT_RUN_PATH, - SimulationServiceReportSubmitter, -) from policyengine_api_simulation_client.api.default import create_report_without_run from policyengine_api_simulation_client.models import ( BudgetWindowReportRequest, @@ -25,6 +21,10 @@ HouseholdReportRequest, ) +from policyengine_api.libs.simulation_reports_without_runs import ( + REPORTS_WITHOUT_RUN_PATH, + SimulationServiceReportSubmitter, +) from policyengine_api.services.v2.saved_record_migration.types import ( ApiV2ReportDefinition, ApiV2ReportKind, diff --git a/tests/unit/test_migrate_saved_records_script.py b/tests/unit/test_migrate_saved_records_script.py index 2ca1828fa..eb1b6ff33 100644 --- a/tests/unit/test_migrate_saved_records_script.py +++ b/tests/unit/test_migrate_saved_records_script.py @@ -68,14 +68,15 @@ def compare_sample( def migrate(self, options: MigrationOptions) -> MigrationRun: self.options.append(options) - results = ( - SavedRecordResult( - kind=SavedRecordKind.SAVED_REFORM, - row_id=SAVED_ROW, - country_id="us", - legacy_id=12, - outcome=RowOutcome.MIGRATED, - ), + migrated_reform = SavedRecordResult( + kind=SavedRecordKind.SAVED_REFORM, + row_id=SAVED_ROW, + country_id="us", + legacy_id=12, + outcome=RowOutcome.MIGRATED, + ) + results = tuple( + result for result in (migrated_reform,) if result.kind in options.kinds ) remaining = {kind: set() for kind in SavedRecordKind} remaining[SavedRecordKind.SAVED_HOUSEHOLD] = self.remaining From 586fb67c8a0ca48f9f9156ad7be4a50ed261e163 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 05:37:10 +0400 Subject: [PATCH 18/22] Add failing tests for review round 3's findings on the report client - An economy report or budget window without a reform says it has none. - A refusal of the whole definition names the definition, not an empty field. - The command checks the v1 economy routes' entrypoint settings before loading API v1's simulation client, and names missing gateway credentials as a missing setting. - The report client is closed after both databases, also when a setting is missing or the run fails. Co-Authored-By: Claude Opus 5.5 --- .../test_simulation_reports_without_runs.py | 23 ++- .../unit/test_migrate_saved_records_script.py | 152 +++++++++++++++++- 2 files changed, 168 insertions(+), 7 deletions(-) diff --git a/tests/unit/libs/test_simulation_reports_without_runs.py b/tests/unit/libs/test_simulation_reports_without_runs.py index ffb04472a..2b32cfb83 100644 --- a/tests/unit/libs/test_simulation_reports_without_runs.py +++ b/tests/unit/libs/test_simulation_reports_without_runs.py @@ -248,11 +248,14 @@ def test_a_report_found_or_created_is_read_from_either_created_status( assert ScriptedService(status_code).submit(ECONOMY_REPORT) == REPORT_ID -def test_an_economy_report_without_a_reform_is_not_sent() -> None: +@pytest.mark.parametrize("definition", [ECONOMY_REPORT, BUDGET_WINDOW]) +def test_an_economy_report_or_budget_window_without_a_reform_is_not_sent( + definition: ApiV2ReportDefinition, +) -> None: service = ScriptedService() - with pytest.raises(ValueError, match="names a reform"): - service.submit(dataclasses.replace(ECONOMY_REPORT, reform=None)) + with pytest.raises(ValueError, match=f"the {definition.kind.value} report has no"): + service.submit(dataclasses.replace(definition, reform=None)) assert service.requests == [] @@ -268,6 +271,20 @@ def test_a_definition_the_report_inputs_refuse_is_refused_unsent() -> None: assert service.requests == [] +def test_a_refusal_of_the_whole_definition_names_the_definition() -> None: + service = ScriptedService() + + with pytest.raises(ReportSubmissionRefusedError) as refused: + service.submit(dataclasses.replace(BUDGET_WINDOW, year=2195)) + + assert refused.value.code == "invalid_report_definition" + assert str(refused.value) == ( + "the report's definition isn't valid: definition: Value error, a budget " + "window must end in 2200 or earlier" + ) + assert service.requests == [] + + @pytest.mark.parametrize( "body", [ diff --git a/tests/unit/test_migrate_saved_records_script.py b/tests/unit/test_migrate_saved_records_script.py index eb1b6ff33..1bb7c472f 100644 --- a/tests/unit/test_migrate_saved_records_script.py +++ b/tests/unit/test_migrate_saved_records_script.py @@ -7,6 +7,7 @@ import subprocess import sys from contextlib import contextmanager +from types import SimpleNamespace from typing import TYPE_CHECKING from uuid import UUID @@ -31,6 +32,7 @@ if TYPE_CHECKING: from collections.abc import Iterator + from contextlib import AbstractContextManager FIRST_USER = UUID("00000000-0000-0000-0000-00000000d411") SECOND_USER = UUID("00000000-0000-0000-0000-00000000d412") @@ -324,20 +326,162 @@ def test_the_report_clients_log_records_leave_the_document_alone_on_stdout() -> assert "a record after loading" in result.stderr -def test_the_report_client_without_its_entrypoint_settings_names_them() -> None: +@pytest.mark.parametrize( + "selected_entrypoint", [{}, {"SIM_ENTRYPOINT": "old_gateway_direct"}] +) +def test_the_report_client_without_its_entrypoint_settings_is_not_loaded( + selected_entrypoint: dict[str, str], +) -> None: + with pytest.raises(command.MissingSettingError) as missing: + command.check_simulation_client_settings( + { + "SIMULATION_ENTRYPOINT_URL": "https://simulation.example.test", + **selected_entrypoint, + } + ) + + assert "SIM_ENTRYPOINT=cloud_run_simulation_entrypoint" in str(missing.value) + assert "OLD_SIMULATION_GATEWAY_URL" in str(missing.value) + + +@pytest.mark.parametrize( + "settings", + [ + { + "SIM_ENTRYPOINT": "cloud_run_simulation_entrypoint", + "SIMULATION_ENTRYPOINT_URL": "https://simulation.example.test", + }, + { + "SIM_ENTRYPOINT": "old_gateway_direct", + "OLD_SIMULATION_GATEWAY_URL": "https://old.example.test", + }, + ], +) +def test_the_report_client_with_its_entrypoint_settings_may_be_loaded( + settings: dict[str, str], +) -> None: + assert command.check_simulation_client_settings(settings) is None + + +def test_the_report_client_without_required_gateway_credentials_names_them() -> None: result = _run_in_a_new_process( "from scripts import migrate_saved_records_to_api_v2 as command\n" "try:\n" " command._report_submitter_from_environment()\n" "except command.MissingSettingError as error:\n" " print(error)\n", - SIM_ENTRYPOINT="old_gateway_direct", + SIM_ENTRYPOINT="cloud_run_simulation_entrypoint", SIMULATION_ENTRYPOINT_URL="https://simulation.example.test", + GATEWAY_AUTH_REQUIRED="1", ) assert result.returncode == 0, result.stderr - assert "SIM_ENTRYPOINT=cloud_run_simulation_entrypoint" in result.stdout - assert "OLD_SIMULATION_GATEWAY_URL is required" in result.stdout + assert result.stdout.startswith( + "API v1's simulation client can't be loaded without its gateway credentials" + ) + + +class RecordedResources: + """Record when the report client and each database's sessions open and close.""" + + def __init__(self) -> None: + self.events: list[str] = [] + + def report_submitter(self) -> RecordedResources: + self.events.append("report client built") + return self + + def close(self) -> None: + self.events.append("report client closed") + + @contextmanager + def sessions(self, database: str) -> Iterator[str]: + self.events.append(f"{database} opened") + try: + yield f"{database} sessions" + finally: + self.events.append(f"{database} closed") + + +@pytest.fixture +def recorded_resources(monkeypatch) -> RecordedResources: + """Replace the report client and both databases' sessions with recorders.""" + # The command imports it only when it runs. + import policyengine_api.data.v2.database as v2_database + + resources = RecordedResources() + monkeypatch.setattr( + command, "_report_submitter_from_environment", resources.report_submitter + ) + monkeypatch.setattr( + command, + "load_v2_runtime_database_settings", + lambda: SimpleNamespace(connection=SimpleNamespace(url="v2-url")), + ) + monkeypatch.setenv("POLICYENGINE_DB_READONLY_PASSWORD", "reader-secret") + monkeypatch.setattr( + v2_database, "unpooled_v2_sessions", lambda url: resources.sessions("API v2") + ) + monkeypatch.setattr( + command, "unpooled_v1_sessions", lambda url: resources.sessions("API v1") + ) + return resources + + +def test_a_run_closes_the_report_client_after_both_databases( + recorded_resources: RecordedResources, +) -> None: + with command._migrator_from_environment( + dry_run=False, submits_reports=True + ) as migrator: + assert migrator._report_submitter is recorded_resources + + assert recorded_resources.events == [ + "report client built", + "API v2 opened", + "API v1 opened", + "API v1 closed", + "API v2 closed", + "report client closed", + ] + + +def test_a_run_that_cannot_read_its_settings_closes_the_report_client( + recorded_resources: RecordedResources, monkeypatch +) -> None: + monkeypatch.delenv("POLICYENGINE_DB_READONLY_PASSWORD") + + with ( + pytest.raises(command.MissingSettingError), + command._migrator_from_environment(dry_run=False, submits_reports=True), + ): + pass + + assert recorded_resources.events == [ + "report client built", + "report client closed", + ] + + +def _fail_while_running(building: AbstractContextManager[object]) -> None: + with building: + msg = "the run failed" + raise RuntimeError(msg) + + +def test_a_run_that_fails_closes_both_databases_and_the_report_client( + recorded_resources: RecordedResources, +) -> None: + with pytest.raises(RuntimeError, match="the run failed"): + _fail_while_running( + command._migrator_from_environment(dry_run=False, submits_reports=True) + ) + + assert recorded_resources.events[-3:] == [ + "API v1 closed", + "API v2 closed", + "report client closed", + ] def test_v1_is_read_as_the_read_only_role_through_the_proxy() -> None: From ef0f38e029ecfd8223653785b07cfadf0a41eaa1 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 05:38:20 +0400 Subject: [PATCH 19/22] Fix review round 3's findings on the report client - The submitter validates each report's creation input from a mapping, so its types check, and says a report without a reform has none. - A refusal of the whole definition names the definition. - The command checks the v1 economy routes' entrypoint settings before loading API v1's simulation client, rather than catching every ValueError the load raises, and names missing gateway credentials as a missing setting. Its docs ask for GATEWAY_AUTH_REQUIRED=1, as deployed. - Docstrings name the new route's request test and no longer say no route finds what a submission created. Co-Authored-By: Claude Opus 5.5 --- .../libs/simulation_reports_without_runs.py | 96 +++++++++---------- .../libs/simulation_service_answers.py | 6 +- .../libs/simulation_service_operations.py | 4 +- scripts/migrate_saved_records_to_api_v2.py | 57 +++++++++-- 4 files changed, 101 insertions(+), 62 deletions(-) diff --git a/policyengine_api/libs/simulation_reports_without_runs.py b/policyengine_api/libs/simulation_reports_without_runs.py index 60093bb27..99396e858 100644 --- a/policyengine_api/libs/simulation_reports_without_runs.py +++ b/policyengine_api/libs/simulation_reports_without_runs.py @@ -60,9 +60,7 @@ from policyengine_api.services.v2.simulation_service.types import ( BudgetWindowReportCreationInput, EconomyReportCreationInput, - HouseholdPolicyChoice, HouseholdReportCreationInput, - PolicyChoice, SimulationServiceAnswerUnreadableError, SimulationServiceUnavailableError, ) @@ -91,47 +89,35 @@ class _ReportWithoutRun(AnswerModel): report_id: UUID -def _policy_choice(side: PolicySide) -> PolicyChoice: - return PolicyChoice(policy_id=side.policy_id, dynamic_id=side.dynamic_id) - - -def _household_policy_choice(side: PolicySide) -> HouseholdPolicyChoice: - return HouseholdPolicyChoice(policy_id=side.policy_id, dynamic_id=side.dynamic_id) +def _policy_choice(side: PolicySide) -> dict[str, UUID | None]: + return {"policy_id": side.policy_id, "dynamic_id": side.dynamic_id} def _invalid_fields(error: ValidationError) -> str: - """Return each field the creation input refuses and why, on one line.""" + """Return each field the creation input refuses and why, on one line. + + A refusal of the whole definition, such as a budget window ending after + the last year stored, names the definition. + """ return "; ".join( - f"{'.'.join(str(part) for part in detail['loc'])}: {detail['msg']}" + f"{'.'.join(str(part) for part in detail['loc']) or 'definition'}: " + f"{detail['msg']}" for detail in error.errors() ) -def _household_report_input( - definition: ApiV2ReportDefinition, -) -> HouseholdReportCreationInput: - return HouseholdReportCreationInput( - country_id=definition.country_id, - kind="household", - household_id=definition.household_id, - baseline=_household_policy_choice(definition.baseline), - reform=( - None - if definition.reform is None - else _household_policy_choice(definition.reform) - ), - ) - - def _report_sides( definition: ApiV2ReportDefinition, -) -> tuple[PolicyChoice, PolicyChoice]: +) -> tuple[dict[str, UUID | None], dict[str, UUID | None]]: """Return an economy report's or budget window's baseline and reform. Raise ValueError when it has no reform, which the migration never builds. """ if definition.reform is None: - msg = f"an {definition.kind.value} report names a reform" + msg = ( + f"the {definition.kind.value} report has no reform; the migration " + "gives every economy report and budget window one" + ) raise ValueError(msg) return _policy_choice(definition.baseline), _policy_choice(definition.reform) @@ -139,13 +125,13 @@ def _report_sides( def report_without_run_request(definition: ApiV2ReportDefinition) -> dict[str, Any]: """Return the request body for the definition, as ``POST /v2/reports`` builds it. - Raise ValueError for an economy report or budget window without a - reform, which the migration never builds, and + The definition is checked as API v1's report creation inputs check a + report a caller sends. Raise ValueError for an economy report or budget + window without a reform, which the migration never builds, and ReportSubmissionRefusedError when the creation inputs refuse the definition, such as a year outside the years the service stores. """ - # simulation_reports holds API v1's report routes' process-wide client, - # so it is imported only when a report is sent. + # The project bans importing simulation_reports at module level. from policyengine_api.libs.simulation_reports import ( budget_window_request, household_report_request, @@ -154,28 +140,42 @@ def report_without_run_request(definition: ApiV2ReportDefinition) -> dict[str, A try: if definition.kind is ApiV2ReportKind.HOUSEHOLD: - return household_report_request(_household_report_input(definition)) + return household_report_request( + HouseholdReportCreationInput.model_validate( + { + "country_id": definition.country_id, + "kind": "household", + "household_id": definition.household_id, + "baseline": _policy_choice(definition.baseline), + "reform": ( + None + if definition.reform is None + else _policy_choice(definition.reform) + ), + } + ) + ) baseline, reform = _report_sides(definition) + sides_and_place = { + "country_id": definition.country_id, + "year": definition.year, + "region_code": definition.region_code, + "baseline": baseline, + "reform": reform, + } if definition.kind is ApiV2ReportKind.BUDGET_WINDOW: return budget_window_request( - BudgetWindowReportCreationInput( - country_id=definition.country_id, - kind="budget_window", - year=definition.year, - region_code=definition.region_code, - baseline=baseline, - reform=reform, - budget_window_size=definition.budget_window_size, + BudgetWindowReportCreationInput.model_validate( + { + **sides_and_place, + "kind": "budget_window", + "budget_window_size": definition.budget_window_size, + } ) ) return report_request( - EconomyReportCreationInput( - country_id=definition.country_id, - kind="economy", - year=definition.year, - region_code=definition.region_code, - baseline=baseline, - reform=reform, + EconomyReportCreationInput.model_validate( + {**sides_and_place, "kind": "economy"} ) ) except ValidationError as error: diff --git a/policyengine_api/libs/simulation_service_answers.py b/policyengine_api/libs/simulation_service_answers.py index 7721576bc..83b9ed8e3 100644 --- a/policyengine_api/libs/simulation_service_answers.py +++ b/policyengine_api/libs/simulation_service_answers.py @@ -167,9 +167,9 @@ def simulation_service_http_client( def submit_again(submission: str, second: str) -> str: """Ask the caller to submit the ``submission`` again, which may create a second. - No route finds what a submission created by what it was submitted with, - so the caller cannot check whether the first request created a - ``second``. + The routes whose clients use it don't find what a submission created by + what it was submitted with, so the caller cannot check whether the first + request created a ``second``. """ return ( f"Submit the {submission} again; if the first request went through, " diff --git a/policyengine_api/libs/simulation_service_operations.py b/policyengine_api/libs/simulation_service_operations.py index cb559997e..03c7cdec6 100644 --- a/policyengine_api/libs/simulation_service_operations.py +++ b/policyengine_api/libs/simulation_service_operations.py @@ -37,7 +37,9 @@ ``tests/unit/libs/test_simulation_generated_client.py`` checks that each request is the one API v1 builds by hand and the one the generated operation -builds; run those tests when moving the pin. +builds, and ``tests/unit/libs/test_simulation_reports_without_runs.py`` does +the same for ``POST /reports/without-run``; run those tests when moving the +pin. To call another of the simulation service's routes, add a function here that builds the request with that route's generated operation and request model, diff --git a/scripts/migrate_saved_records_to_api_v2.py b/scripts/migrate_saved_records_to_api_v2.py index 5764bd76d..2d28205b6 100755 --- a/scripts/migrate_saved_records_to_api_v2.py +++ b/scripts/migrate_saved_records_to_api_v2.py @@ -52,8 +52,12 @@ and ``POLICYENGINE_DB_PROXY_PORT``, 3307 without it); - for a run that migrates saved reports, the Cloud Run simulation service at ``SIMULATION_ENTRYPOINT_URL`` with the gateway credentials - (``GATEWAY_AUTH_*``). API v1's simulation client also reads the v1 - economy routes' setting when loaded, so set + (``GATEWAY_AUTH_ISSUER``, ``GATEWAY_AUTH_AUDIENCE``, + ``GATEWAY_AUTH_CLIENT_ID`` and ``GATEWAY_AUTH_CLIENT_SECRET_RESOURCE``). + Set ``GATEWAY_AUTH_REQUIRED=1``, as the deployed API v1 does, so missing + credentials stop the run before it connects, rather than failing every + saved report. API v1's simulation client also reads the v1 economy + routes' setting when loaded, so set ``SIM_ENTRYPOINT=cloud_run_simulation_entrypoint`` too. Each saved report's report is found or created through ``POST /reports/without-run``, which starts no run: app v3 starts a report's first run when it is opened. @@ -74,6 +78,7 @@ from policyengine_api.data.v1_sessions import unpooled_v1_sessions from policyengine_api.data.v2.settings import load_v2_runtime_database_settings +from policyengine_api.libs.gateway_auth import GatewayAuthError from policyengine_api.services.v2.saved_record_migration.transformations import ( migration_document, sample_comparison_document, @@ -101,6 +106,14 @@ V1_PROXY_HOST = "127.0.0.1" V1_PROXY_PORT = "POLICYENGINE_DB_PROXY_PORT" DEFAULT_V1_PROXY_PORT = 3307 +# The v1 economy routes' entrypoint setting, and the URL setting each of its +# values needs; unset, it selects the old gateway. +SIM_ENTRYPOINT = "SIM_ENTRYPOINT" +ENTRYPOINT_URL_SETTINGS = { + "old_gateway_direct": "OLD_SIMULATION_GATEWAY_URL", + "cloud_run_simulation_entrypoint": "SIMULATION_ENTRYPOINT_URL", +} +DEFAULT_SIM_ENTRYPOINT = "old_gateway_direct" class MissingSettingError(RuntimeError): @@ -140,27 +153,51 @@ def v1_read_only_database_url(environ: Mapping[str, str]) -> URL: ) +def check_simulation_client_settings(environ: Mapping[str, str]) -> None: + """Refuse settings with which API v1's simulation client can't be loaded. + + Loading it builds the v1 economy routes' client, which needs the URL + ``SIM_ENTRYPOINT`` selects: ``OLD_SIMULATION_GATEWAY_URL`` when it is + unset or ``old_gateway_direct``. The command sends reports to + ``SIMULATION_ENTRYPOINT_URL`` either way, so it asks for + ``SIM_ENTRYPOINT=cloud_run_simulation_entrypoint``. Raise + MissingSettingError when the selected URL is unset; an entrypoint it + doesn't know, or a URL it can't take, is left for the client to refuse. + """ + selected = environ.get(SIM_ENTRYPOINT) or DEFAULT_SIM_ENTRYPOINT + url_setting = ENTRYPOINT_URL_SETTINGS.get(selected) + if url_setting is not None and not environ.get(url_setting, "").strip(): + msg = ( + f"API v1's simulation client needs {url_setting} when " + f"{SIM_ENTRYPOINT} selects {selected!r}; set " + f"{SIM_ENTRYPOINT}=cloud_run_simulation_entrypoint with " + "SIMULATION_ENTRYPOINT_URL, or OLD_SIMULATION_GATEWAY_URL" + ) + raise MissingSettingError(msg) + + def _report_submitter_from_environment() -> SimulationServiceReportSubmitter: """Build the simulation service's report client from the deployed settings. Loading API v1's simulation client builds API v1's logging runtime, which writes log records to the standard output it finds when it is built. It is loaded with standard output sent to standard error, so the command's - JSON document is alone on standard output. Raise MissingSettingError when - loading it refuses the v1 economy routes' entrypoint settings, and - SimulationServiceUnavailableError when the simulation service isn't - configured. + JSON document is alone on standard output. Raise MissingSettingError + when the v1 economy routes' entrypoint settings + (``check_simulation_client_settings``) or required gateway credentials + are missing, and SimulationServiceUnavailableError when + ``SIMULATION_ENTRYPOINT_URL`` is missing or invalid. """ + check_simulation_client_settings(os.environ) try: with contextlib.redirect_stdout(sys.stderr): from policyengine_api.libs.simulation_reports_without_runs import ( SimulationServiceReportSubmitter, ) - except ValueError as error: + except GatewayAuthError as error: msg = ( - "API v1's simulation client can't be loaded; set " - "SIM_ENTRYPOINT=cloud_run_simulation_entrypoint with " - f"SIMULATION_ENTRYPOINT_URL: {error}" + "API v1's simulation client can't be loaded without its gateway " + f"credentials: {error}" ) raise MissingSettingError(msg) from error return SimulationServiceReportSubmitter.from_environment() From cdd70d572141b3e7e8bb6800c04affb7b220e168 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:16:05 +0400 Subject: [PATCH 20/22] Add a failing test: API v1 loads without the run-free report create The pinned policyengine-api-simulation-client lacks create_report_without_run until the release published after PolicyEngine/policyengine-sim-api#1167 deploys, and API v1 fails to load its simulation modules without it, which fails every test shard. Co-Authored-By: Claude Opus 5.5 --- ...ation_client_without_report_without_run.py | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 tests/unit/libs/test_simulation_client_without_report_without_run.py diff --git a/tests/unit/libs/test_simulation_client_without_report_without_run.py b/tests/unit/libs/test_simulation_client_without_report_without_run.py new file mode 100644 index 000000000..09942088e --- /dev/null +++ b/tests/unit/libs/test_simulation_client_without_report_without_run.py @@ -0,0 +1,71 @@ +"""API v1 loads with a simulation client release that lacks the run-free report create. + +``policyengine-api-simulation-client`` gains ``create_report_without_run`` +only in the release published after the simulation service's +``POST /reports/without-run`` (PolicyEngine/policyengine-sim-api#1167) +deploys. Until API v1 pins that release, API v1's simulation modules must +load without it. +""" + +from __future__ import annotations + +import os +import subprocess +import sys + +from policyengine_api.constants import REPO + +# The generated operation the pinned release may lack. +REPORT_WITHOUT_RUN_OPERATION = ( + "policyengine_api_simulation_client.api.default.create_report_without_run" +) +# Settings API v1's simulation client reads when loaded, which the new +# process gets only as this test sets them. +SIMULATION_SETTINGS = ( + "GATEWAY_AUTH_ISSUER", + "GATEWAY_AUTH_AUDIENCE", + "GATEWAY_AUTH_CLIENT_ID", + "GATEWAY_AUTH_CLIENT_SECRET", + "GATEWAY_AUTH_CLIENT_SECRET_RESOURCE", + "GATEWAY_AUTH_REQUIRED", + "SIM_ENTRYPOINT", + "OLD_SIMULATION_GATEWAY_URL", + "SIMULATION_ENTRYPOINT_URL", +) + + +def test_api_v1_simulation_modules_load_without_the_run_free_report_create() -> None: + import_check = ( + "import sys\n" + "class RefuseReportWithoutRun:\n" + " def find_spec(self, name, path=None, target=None):\n" + f" if name == {REPORT_WITHOUT_RUN_OPERATION!r}:\n" + " raise ModuleNotFoundError(name)\n" + " return None\n" + "sys.meta_path.insert(0, RefuseReportWithoutRun())\n" + "import policyengine_api.libs.simulation_service_operations\n" + "import policyengine_api.libs.simulation_reports\n" + "import policyengine_api.libs.simulation_reports_without_runs\n" + "print('loaded')\n" + ) + environment = { + name: value + for name, value in os.environ.items() + if name not in SIMULATION_SETTINGS + } + + result = subprocess.run( + [sys.executable, "-c", import_check], + cwd=REPO, + capture_output=True, + text=True, + check=False, + env={ + **environment, + "SIM_ENTRYPOINT": "cloud_run_simulation_entrypoint", + "SIMULATION_ENTRYPOINT_URL": "https://simulation.example.test", + }, + ) + + assert result.returncode == 0, result.stderr + assert result.stdout == "loaded\n" From 9c978c723d8c479dc031be39b2055a02a12f4d66 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:17:34 +0400 Subject: [PATCH 21/22] Revert "Add a failing test: API v1 loads without the run-free report create" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit cdd70d572. D4 · 0 is deployed and its client release 0.20261201.454 has create_report_without_run, so the pin is raised to it instead of loading the operation only when a report is sent. Co-Authored-By: Claude Opus 5.5 --- ...ation_client_without_report_without_run.py | 71 ------------------- 1 file changed, 71 deletions(-) delete mode 100644 tests/unit/libs/test_simulation_client_without_report_without_run.py diff --git a/tests/unit/libs/test_simulation_client_without_report_without_run.py b/tests/unit/libs/test_simulation_client_without_report_without_run.py deleted file mode 100644 index 09942088e..000000000 --- a/tests/unit/libs/test_simulation_client_without_report_without_run.py +++ /dev/null @@ -1,71 +0,0 @@ -"""API v1 loads with a simulation client release that lacks the run-free report create. - -``policyengine-api-simulation-client`` gains ``create_report_without_run`` -only in the release published after the simulation service's -``POST /reports/without-run`` (PolicyEngine/policyengine-sim-api#1167) -deploys. Until API v1 pins that release, API v1's simulation modules must -load without it. -""" - -from __future__ import annotations - -import os -import subprocess -import sys - -from policyengine_api.constants import REPO - -# The generated operation the pinned release may lack. -REPORT_WITHOUT_RUN_OPERATION = ( - "policyengine_api_simulation_client.api.default.create_report_without_run" -) -# Settings API v1's simulation client reads when loaded, which the new -# process gets only as this test sets them. -SIMULATION_SETTINGS = ( - "GATEWAY_AUTH_ISSUER", - "GATEWAY_AUTH_AUDIENCE", - "GATEWAY_AUTH_CLIENT_ID", - "GATEWAY_AUTH_CLIENT_SECRET", - "GATEWAY_AUTH_CLIENT_SECRET_RESOURCE", - "GATEWAY_AUTH_REQUIRED", - "SIM_ENTRYPOINT", - "OLD_SIMULATION_GATEWAY_URL", - "SIMULATION_ENTRYPOINT_URL", -) - - -def test_api_v1_simulation_modules_load_without_the_run_free_report_create() -> None: - import_check = ( - "import sys\n" - "class RefuseReportWithoutRun:\n" - " def find_spec(self, name, path=None, target=None):\n" - f" if name == {REPORT_WITHOUT_RUN_OPERATION!r}:\n" - " raise ModuleNotFoundError(name)\n" - " return None\n" - "sys.meta_path.insert(0, RefuseReportWithoutRun())\n" - "import policyengine_api.libs.simulation_service_operations\n" - "import policyengine_api.libs.simulation_reports\n" - "import policyengine_api.libs.simulation_reports_without_runs\n" - "print('loaded')\n" - ) - environment = { - name: value - for name, value in os.environ.items() - if name not in SIMULATION_SETTINGS - } - - result = subprocess.run( - [sys.executable, "-c", import_check], - cwd=REPO, - capture_output=True, - text=True, - check=False, - env={ - **environment, - "SIM_ENTRYPOINT": "cloud_run_simulation_entrypoint", - "SIMULATION_ENTRYPOINT_URL": "https://simulation.example.test", - }, - ) - - assert result.returncode == 0, result.stderr - assert result.stdout == "loaded\n" From d33259f69267de6870f2e789c2f3f6e0bbe24641 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:18:18 +0400 Subject: [PATCH 22/22] Pin the simulation client release with the run-free report create policyengine-api-simulation-client 0.20261201.454 is the first release published after PolicyEngine/policyengine-sim-api#1167 deployed; it has create_report_without_run, which the migration command's report submitter calls. Co-Authored-By: Claude Opus 5.5 --- pyproject.toml | 2 +- uv.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index d2ff17d5e..c82e89cf0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -57,7 +57,7 @@ dependencies = [ # a release whose request models hold every field those requests send; # moving it is its own change, tested by # tests/unit/libs/test_simulation_generated_client.py. - "policyengine-api-simulation-client==0.20261127.430", + "policyengine-api-simulation-client==0.20261201.454", "pydantic", "pymysql", "python-dotenv", diff --git a/uv.lock b/uv.lock index 97e0b8a9d..14ed565f9 100644 --- a/uv.lock +++ b/uv.lock @@ -3074,7 +3074,7 @@ requires-dist = [ { name = "openai" }, { name = "packaging", specifier = ">=24,<27" }, { name = "policyengine", extras = ["models"], specifier = "==6.20.0" }, - { name = "policyengine-api-simulation-client", specifier = "==0.20261127.430" }, + { name = "policyengine-api-simulation-client", specifier = "==0.20261201.454" }, { name = "policyengine-observability", extras = ["flask", "google", "httpx", "otlp-grpc"], specifier = ">=3.0.3,<4" }, { name = "psycopg", extras = ["binary"], specifier = ">=3.3,<4" }, { name = "pydantic" }, @@ -3103,15 +3103,15 @@ telemetry-error-issues = [{ name = "google-cloud-bigquery", specifier = ">=3.30, [[package]] name = "policyengine-api-simulation-client" -version = "0.20261127.430" +version = "0.20261201.454" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "attrs" }, { name = "httpx" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/ee/5b/23ee4708a81ca8cb80da3f299d66530f2c9b014dbef7298b017394e5ef2a/policyengine_api_simulation_client-0.20261127.430.tar.gz", hash = "sha256:fd65475e32eeb3eec9478565df42a524c2fa0a5d66945e5ce8f45f67846d5da4", size = 73000, upload-time = "2026-11-27T16:28:23.425Z" } +sdist = { url = "https://files.pythonhosted.org/packages/44/e1/240821339fdca27a7db09f4e11467107ab5c4b77caa2a3f0cd96a68c6578/policyengine_api_simulation_client-0.20261201.454.tar.gz", hash = "sha256:9663c209fb2a1af41c4d7c0168a161a84ee71cf5484232c1f6d1edf8b374c266", size = 77171, upload-time = "2026-12-01T16:42:38.631Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/2e/c4/bf8755ea496cf6dd774c944952baf9e14e41355ea70beb20dfcaa5fff095/policyengine_api_simulation_client-0.20261127.430-py3-none-any.whl", hash = "sha256:bfa200907750af00adee1c310cec7b851c1a2a0d3d5a3c717d33f65ccd17b444", size = 161942, upload-time = "2026-11-27T16:28:22.018Z" }, + { url = "https://files.pythonhosted.org/packages/74/7f/1920dc8272813d8d4001666e3c7185818a4e0cd29407c81e24c27dc9ae83/policyengine_api_simulation_client-0.20261201.454-py3-none-any.whl", hash = "sha256:7b201b7df45e1967bcec4e8eddd26409b4e83b5e8bde22f443b8c2cae2576f98", size = 173233, upload-time = "2026-12-01T16:42:37.101Z" }, ] [[package]]