diff --git a/.github/workflows/v2-integration-check.yml b/.github/workflows/v2-integration-check.yml index c8e313090..9b6562132 100644 --- a/.github/workflows/v2-integration-check.yml +++ b/.github/workflows/v2-integration-check.yml @@ -77,8 +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, user types and published reports - 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_published_reports.py + - name: Test signed-in identity provisioning, user associations, saved detailed-save records, user types, published reports 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_published_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/changelog.d/saved-record-migration.added.md b/changelog.d/saved-record-migration.added.md new file mode 100644 index 000000000..e1e302b2c --- /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 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/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 375f48d97..2b46b4bcf 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/libs/simulation_reports_without_runs.py b/policyengine_api/libs/simulation_reports_without_runs.py new file mode 100644 index 000000000..99396e858 --- /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, + HouseholdReportCreationInput, + 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) -> 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. + + 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']) or 'definition'}: " + f"{detail['msg']}" + for detail in error.errors() + ) + + +def _report_sides( + definition: ApiV2ReportDefinition, +) -> 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"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) + + +def report_without_run_request(definition: ApiV2ReportDefinition) -> dict[str, Any]: + """Return the request body for the definition, as ``POST /v2/reports`` builds it. + + 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. + """ + # The project bans importing simulation_reports at module level. + 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( + 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.model_validate( + { + **sides_and_place, + "kind": "budget_window", + "budget_window_size": definition.budget_window_size, + } + ) + ) + return report_request( + EconomyReportCreationInput.model_validate( + {**sides_and_place, "kind": "economy"} + ) + ) + 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_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 188c47022..f50f69591 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, @@ -61,6 +63,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, ) @@ -87,8 +92,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], @@ -191,6 +196,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/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..079f6a722 --- /dev/null +++ b/policyengine_api/services/v2/saved_record_migration/__init__.py @@ -0,0 +1 @@ +"""The one-time migration of saved records' API 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..1f5cc56a7 --- /dev/null +++ b/policyengine_api/services/v2/saved_record_migration/copies/services.py @@ -0,0 +1,344 @@ +"""The policy and household copies the one-time saved-record migration makes. + +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 + +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 ( + LEGACY_HOUSEHOLD_FINGERPRINT_VERSION, + legacy_household_fingerprint, + translate_legacy_household, +) +from policyengine_api.services.v2.households.validators import ( + HouseholdCreationIntegrityError, + HouseholdValidationError, + LegacyHouseholdMappingIntegrityError, + LegacyHouseholdTranslationError, + verify_legacy_household_mapping, +) +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, + 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, +) +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"API 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 API v1 policy migrates, writing nothing. + + 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( + 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 + ) + 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=(), + 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 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, + ) + 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 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 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: + 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 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. + """ + 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"API 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, + ) + 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/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..9b7e472d9 --- /dev/null +++ b/policyengine_api/services/v2/saved_record_migration/database_connectors/reads.py @@ -0,0 +1,229 @@ +"""Reads of saved records holding only an API v1 reference, for the migration. + +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). +""" + +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 ( + 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 + 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 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), + ) + 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 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), + ) + 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 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), + ) + 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 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), + ) + 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) + ) + + +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 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. + """ + 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 new file mode 100644 index 000000000..ded1cb6a5 --- /dev/null +++ b/policyengine_api/services/v2/saved_record_migration/database_connectors/reads_v1_records.py @@ -0,0 +1,164 @@ +"""Reads of the API v1 records saved records name, through the API v1 mapped models. + +The migration only reads API 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, + 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, +) + +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 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. + """ + 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 API 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 API v1 report output's defining fields, or None without one.""" + 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 API 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 + } + + +def read_v1_report_result( + session: Session, *, country_id: str, report_id: int +) -> V1ReportResult | None: + """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 API 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/database_connectors/updates.py b/policyengine_api/services/v2/saved_record_migration/database_connectors/updates.py new file mode 100644 index 000000000..68bad5f3f --- /dev/null +++ b/policyengine_api/services/v2/saved_record_migration/database_connectors/updates.py @@ -0,0 +1,79 @@ +"""Updates that give saved records their API v2 reference. + +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. +""" + +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 API 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..29ddd7162 --- /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 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. +""" + +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 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.""" + 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 API v1 transactions that are always rolled back and closed.""" + + def __init__(self, session_factory: sessionmaker[OrmSession]) -> None: + """Use ``session_factory``, the API v1 database's, to open every session.""" + self._session_factory = session_factory + + @contextmanager + def read(self) -> Iterator[OrmSession]: + """Yield an API 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..0e3636b91 --- /dev/null +++ b/policyengine_api/services/v2/saved_record_migration/services.py @@ -0,0 +1,743 @@ +"""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 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 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 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 an API v1 ID +mapping, and a row whose every parameter is missing is still left. A row +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 API v1 reference. Running again picks up what is left. +""" + +from __future__ import annotations + +from dataclasses import replace +from typing import TYPE_CHECKING +from uuid import UUID + +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_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, + 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_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 + set_saved_household_household, + set_saved_reform_policy, + set_saved_report_report, +) +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, + pending_saved_report, + pending_saved_simulation, + relative_difference, +) +from policyengine_api.services.v2.saved_record_migration.types import ( + FailureReason, + MigrationRun, + ReportComparison, + RowOutcome, + SampleComparison, + SavedRecordKind, + SavedRecordResult, + V1ReportKind, +) +from policyengine_api.services.v2.saved_record_migration.validators import ( + ReportSubmissionRefusedError, + 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 + budget_impact, +) +from policyengine_api.services.v2.stored_reports.economy_results.types import ( + EconomyResultUnreadableError, +) + +if TYPE_CHECKING: + from collections.abc import Callable + from contextlib import AbstractContextManager + + 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 ( + ApiV2ReportDefinition, + MigratedReportRun, + MigrationOptions, + PendingSavedRecord, + PolicyMigrationPlan, + ReportSubmitter, + V1ReportDefinition, + ) + + +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, + *, + api_v2_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, + api_v2_id=api_v2_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, + ) + + +_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__}: {first_line[:_ERROR_DETAIL_LENGTH]}", + ) + + +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=missing_parameters, + ) + return None + + +class V2SavedRecordMigrationService: + """Migrate saved records' API v1 references, one saved record at a time.""" + + def __init__( + self, + database_session: SavedRecordMigrationDatabaseSession, + v1_database_session: V1RecordDatabaseSession, + *, + report_submitter: ReportSubmitter | None = None, + running_policyengine_version: str = POLICYENGINE_VERSION, + region_references: Callable[[str], tuple[RegionReference, ...]] = ( + load_region_references + ), + ) -> None: + """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_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 + 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 options.kinds + } + 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 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 API 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. + """ + with self._database_session.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_session.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 api_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, + api_v1_budgetary_impact=v1_value, + api_v1_country_package_version=( + None if v1_result is None else v1_result.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 "API 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]: + """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_session.read() as session: + 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, + 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 Exception as error: # noqa: BLE001 # recorded on its row, so the run still prints every row's result + 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.""" + return ( + self._database_session.transaction() + if options.apply + else self._database_session.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 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, + RowOutcome.MIGRATED, + api_v2_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 API 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, saved_dynamic_input(record, stored.dynamic_id) + ).id + ) + return _result( + record, + RowOutcome.MIGRATED, + api_v2_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_session.read() as session: + try: + snapshot = read_v1_policy_snapshot( + session, country_id=country_id, policy_id=policy_id + ) + except ValidationError as 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"API 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_session.read() as session: + try: + snapshot = read_v1_household_snapshot( + session, country_id=country_id, household_id=household_id + ) + except ValidationError as 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"API 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 API v1 household" + raise _refusal(FailureReason.ROW_CHANGED, msg) + return _result(record, RowOutcome.MIGRATED, api_v2_id=household_id) + + # Saved reports. + + def _v1_report( + self, record: PendingSavedRecord + ) -> tuple[ + V1ReportDefinition, + dict[int, LegacyPolicySnapshot], + LegacyHouseholdSnapshot | None, + ]: + """Read the API v1 report's definition, its policies and its household.""" + with self._v1_database_session.read() as session: + report = read_v1_report( + session, country_id=record.country_id, report_id=record.legacy_id + ) + if report is None: + 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: + 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"API 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: ApiV2ReportDefinition) -> UUID: + """Ask the simulation service to find or create the report.""" + if self._report_submitter is None: + raise _refusal(FailureReason.SIMULATION_SERVICE_UNAVAILABLE, _NO_CLIENT) + 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_session.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 API 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: + """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 Exception as error: # noqa: BLE001 # recorded for every saved report of it, so the run goes on + report = _failed(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, + ) + + 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( + 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 API v1 report's {definition.year}", + ) + if household is not None and household_year != definition.year + else () + ) + report_id = ( + self._report_id( + api_v2_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, + ) + ) + if options.apply + else None + ) + return _result( + record, + RowOutcome.MIGRATED, + 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 new file mode 100644 index 000000000..baa1d4457 --- /dev/null +++ b/policyengine_api/services/v2/saved_record_migration/transformations.py @@ -0,0 +1,354 @@ +"""Conversions the one-time saved-record migration makes (D4 · 1). + +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 + +import json +from collections import Counter +from typing import TYPE_CHECKING + +from policyengine_api.services.v2.saved_record_migration.types import ( + ApiV2ReportDefinition, + ApiV2ReportKind, + ClosingCheck, + 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, + SampleComparison, + 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 API 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 API v1 policy.""" + if row.legacy_policy_id is None: + msg = "a pending saved reform holds an API 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 API v1 report output.""" + if row.legacy_report_id is None: + msg = "a pending saved report holds an API 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 API v1 household.""" + if row.legacy_household_id is None: + msg = "a pending saved household holds an API 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 API v1 simulation.""" + if row.legacy_simulation_id is None: + msg = "a pending saved simulation holds an API 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 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 + ``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 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, + *, + baseline: PolicySide, + reform: PolicySide | None, + region_code: str | None, + household_id: UUID | None, + budget_window_years: int | None, +) -> ApiV2ReportDefinition: + """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 ApiV2ReportDefinition( + country_id=definition.country_id, + kind=ApiV2ReportKind.HOUSEHOLD, + baseline=baseline, + reform=reform, + year=None, + region_code=None, + budget_window_size=None, + household_id=household_id, + ) + window = budget_window_size(budget_window_years) + return ApiV2ReportDefinition( + country_id=definition.country_id, + 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=window, + household_id=None, + ) + + +def closing_check( + remaining: Mapping[SavedRecordKind, Collection[UUID]], + results: Sequence[SavedRecordResult], +) -> ClosingCheck: + """Count the rows still holding only an API v1 reference by what the run did. + + ``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)) + 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, + "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), + "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 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 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 + return { + "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 + 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 + }, + }, + "sample_comparison": ( + "not run: run the command with --compare-sample N for it" + ), + } + + +def api_v1_budgetary_impact(output: object) -> float | None: + """Return the budgetary impact an API v1 economy report output stored, if any. + + 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): + 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, api_v2_value: float | None +) -> float | None: + """Return the API v2 value's difference from API v1's, as a fraction of API v1's. + + None without both values, or when API v1's is zero. + """ + if v1_value is None or api_v2_value is None or v1_value == 0: + return None + return (api_v2_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), + "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, + } + 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 new file mode 100644 index 000000000..17b1c0887 --- /dev/null +++ b/policyengine_api/services/v2/saved_record_migration/types.py @@ -0,0 +1,366 @@ +"""Types of the one-time migration of saved records' API v1 references (D4 · 1). + +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 + +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 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)). + ``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 API 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" + SAVED_DYNAMIC_NOT_VALID = "saved_dynamic_not_valid" + UNEXPECTED_ERROR = "unexpected_error" + + +class V1ReportKind(StrEnum): + """Whether an API v1 report simulates a region's population or one household.""" + + ECONOMY = "economy" + HOUSEHOLD = "household" + + +class ApiV2ReportKind(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, and ``kinds`` to those kinds of saved record. The closing + check covers the same countries, owners and kinds. + """ + + apply: bool + drop_missing_parameters: bool = False + country_ids: tuple[str, ...] = ("uk", "us") + limit: int | None = None + user_ids: tuple[UUID, ...] | None = None + kinds: tuple[SavedRecordKind, ...] = tuple(SavedRecordKind) + + +@dataclass(frozen=True) +class PendingSavedRecord: + """A saved record that holds only its API 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 an API 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 an API 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: + """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 API v1 region, and ``legacy_household_id`` a household report's + API 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 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 API 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 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 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 API 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, an API v1 policy's values are stored as.""" + + policy_id: UUID + dynamic_id: UUID | None + + +@dataclass(frozen=True) +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 API v1 report. + """ + + country_id: str + kind: ApiV2ReportKind + 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: ApiV2ReportDefinition) -> 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. + + ``api_v2_id`` is the policy, report or household ID the row now + 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 + row_id: UUID + country_id: str + legacy_id: int + outcome: RowOutcome + api_v2_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 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 + 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 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. + """ + + 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 + + +@dataclass(frozen=True) +class MigratedReportRun: + """A migrated economy report's newest successful run. + + ``legacy_report_id`` is the API 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: + """An API v1 report output's stored result and the package version it ran on. + + ``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 + country_package_version: str | None + + +@dataclass(frozen=True) +class ReportComparison: + """One migrated report's budgetary impact, as API v1 stored it and as run since. + + ``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. + """ + + country_id: str + legacy_report_id: int + report_id: UUID + report_run_id: UUID + 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 API v1's, for a person to read.""" + + size: int + country_ids: tuple[str, ...] + comparisons: tuple[ReportComparison, ...] 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..2b2025597 --- /dev/null +++ b/policyengine_api/services/v2/saved_record_migration/validators.py @@ -0,0 +1,241 @@ +"""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 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 + +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, + ) + +_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 API v1 ID.""" + + 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"API 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"API 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"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"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"API 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 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 + (``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"API 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"API 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, + # 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 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. + + 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: + 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(' ', '_')}" + 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 an API v1 economy report ran on. + + 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. + """ + 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 API v1 region {v1_region!r}" + raise SavedRecordMigrationRefusal(FailureReason.UNKNOWN_REGION, msg) + return by_spelling[spelled] diff --git a/pyproject.toml b/pyproject.toml index 1e33878f2..d3213baea 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -52,13 +52,16 @@ dependencies = [ # this requirement directly. "policyengine[models]==6.20.0", # The simulation service's generated client, which builds the requests of - # API v2's household calculation, simulation and report routes + # API v2's household calculation, simulation and report routes, and the + # one-time migration command's run-free report create # (policyengine_api.libs.simulation_service_operations). The pin is a # release whose request models hold every field those requests send, # including the inline household calculation's - # (InlineHouseholdCalculationRequest, from 0.20261201.450); moving it is - # its own change, tested by tests/unit/libs/test_simulation_generated_client.py. - "policyengine-api-simulation-client==0.20261201.450", + # (InlineHouseholdCalculationRequest, from 0.20261201.450), and that has + # create_report_without_run (from 0.20261201.454); moving it is its own + # change, tested by tests/unit/libs/test_simulation_generated_client.py and + # tests/unit/libs/test_simulation_reports_without_runs.py. + "policyengine-api-simulation-client==0.20261201.454", "pydantic", "pymysql", "python-dotenv", @@ -411,6 +414,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", @@ -429,6 +433,9 @@ banned-module-level-imports = [ "policyengine_api.services.v2.published_reports.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_api_v2.py b/scripts/migrate_saved_records_to_api_v2.py new file mode 100755 index 000000000..2d28205b6 --- /dev/null +++ b/scripts/migrate_saved_records_to_api_v2.py @@ -0,0 +1,398 @@ +#!/usr/bin/env python3 +"""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_api_v2.py [--dry-run] + [--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 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 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. +- 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. +- ``--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 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 +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`` + 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); +- for a run that migrates saved reports, the Cloud Run simulation service at + ``SIMULATION_ENTRYPOINT_URL`` with the gateway credentials + (``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. + A dry run calls no other service. +""" + +from __future__ import annotations + +import argparse +import contextlib +import json +import os +import sys +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.libs.gateway_auth import GatewayAuthError +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, + SavedRecordKind, +) + +if TYPE_CHECKING: + 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, + ) + +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 +# 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): + """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 compare_sample( + self, *, size: int, country_ids: tuple[str, ...] + ) -> SampleComparison: + """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 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 API 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, + ) + + +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 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 GatewayAuthError as error: + msg = ( + "API v1's simulation client can't be loaded without its gateway " + f"credentials: {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 ( + 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, + ) + + 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, + ) + + +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 an API v1 reference their " + "API v2 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( + "--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, + metavar="N", + help=( + "Migrate nothing: print API v1's stored budgetary impact next to the " + "newest successful run's for up to N migrated economy reports" + ), + ) + 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), + kinds=( + tuple(SavedRecordKind) + if arguments.kinds is None + else tuple( + kind for kind in SavedRecordKind if kind.value in arguments.kinds + ) + ), + ) + + +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. + + 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. + """ + 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 + or arguments.kinds is not None + ): + parser.error("--compare-sample takes only --country") + 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) + 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 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/fixtures/database_sessions.py b/tests/fixtures/database_sessions.py index 9a91f44b7..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,12 +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. + ``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} 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 new file mode 100644 index 000000000..94594579a --- /dev/null +++ b/tests/integration/saved_record_migration_support.py @@ -0,0 +1,567 @@ +"""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.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.fixtures.database_sessions import v2_role_sessions +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 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], +) -> 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 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_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: 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..37b701848 --- /dev/null +++ b/tests/integration/test_v2_saved_record_migration.py @@ -0,0 +1,740 @@ +"""The one-time migration of saved records' API v1 references (D4 · 1). + +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 typing import TYPE_CHECKING + +import pytest +from sqlalchemy import select +from sqlmodel import col + +from policyengine_api.data.v2.models import ( + LegacyHouseholdMapping, + UserDynamic, + UserHouseholdAssociation, + UserPolicy, + UserReportAssociation, + UserSimulationAssociation, +) +from policyengine_api.services.v2.saved_record_migration.types import ( + ApiV2ReportDefinition, + ApiV2ReportKind, + FailureReason, + PolicySide, + RowOutcome, + SavedRecordKind, +) +from tests.fixtures.economy_results import us_economy_result +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_runtime_role_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 ( + RunSettings, + store_report, + store_report_run, +) + +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) + + +@pytest.fixture +def read_only_runtime_sessions( + disposable_v2_database_url: str, managed_v2_roles: ManagedV2Roles +) -> Iterator[sessionmaker[Session]]: + yield from read_only_runtime_role_sessions( + disposable_v2_database_url, managed_v2_roles + ) + + +# 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_row( + v2_owner_sessions, + UserPolicy, + user_id=stored_rows.first_user, + legacy_policy_id=CTC_REFORM, + name="Bigger CTC", + ) + service = migration_service( + runtime_sessions, + v1_sessions, + simulation_service_for(v2_owner_sessions, stored_rows), + ) + + run = migrate(service, stored_rows) + + mapping = policy_mapping(v2_owner_sessions, CTC_REFORM) + assert mapping is not None + assert mapping.dynamic_id is None + row = stored_row(v2_owner_sessions, UserPolicy, saved) + assert (row.policy_id, row.legacy_policy_id) == (mapping.policy_id, CTC_REFORM) + 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 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_row( + 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 = migration_service( + runtime_sessions, + v1_sessions, + simulation_service_for(v2_owner_sessions, stored_rows), + ) + + run = migrate(service, stored_rows) + + 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) == { + (INCOME_ELASTICITY, 0.1) + } + result = result_of(run, saved) + assert result.saved_dynamic_id is not None + saved_dynamic = stored_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 ( + 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_row( + v2_owner_sessions, + UserPolicy, + user_id=stored_rows.first_user, + legacy_policy_id=CTC_REFORM_WITH_REMOVED_PARAMETER, + ) + service = migration_service( + runtime_sessions, + v1_sessions, + simulation_service_for(v2_owner_sessions, stored_rows), + ) + + run = migrate(service, stored_rows) + + result = result_of(run, saved) + assert result.outcome is RowOutcome.MISSING_PARAMETERS + assert result.missing_parameters == (REMOVED_PARAMETER,) + 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_row( + v2_owner_sessions, + UserPolicy, + user_id=stored_rows.first_user, + legacy_policy_id=CTC_REFORM_WITH_REMOVED_PARAMETER, + ) + wholly_missing = save_row( + v2_owner_sessions, + UserPolicy, + user_id=stored_rows.first_user, + legacy_policy_id=ONLY_REMOVED_PARAMETER, + ) + service = migration_service( + runtime_sessions, + v1_sessions, + simulation_service_for(v2_owner_sessions, stored_rows), + ) + + run = migrate(service, stored_rows, drop_missing_parameters=True) + + 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 = 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 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 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 + + +# 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_row( + v2_owner_sessions, + UserHouseholdAssociation, + user_id=stored_rows.first_user, + legacy_household_id=V1_HOUSEHOLD, + name="My household", + ) + service = migration_service( + runtime_sessions, + v1_sessions, + simulation_service_for(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 = stored_row(v2_owner_sessions, UserHouseholdAssociation, saved) + assert (row.household_id, row.legacy_household_id) == (household_id, V1_HOUSEHOLD) + 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_row( + v2_owner_sessions, + UserSimulationAssociation, + user_id=stored_rows.first_user, + legacy_simulation_id=SAVED_SIMULATION, + ) + service = migration_service( + runtime_sessions, + v1_sessions, + simulation_service_for(v2_owner_sessions, stored_rows), + ) + + run = migrate(service, stored_rows) + + assert result_of(run, saved).outcome is RowOutcome.NOT_MIGRATED + assert ( + stored_row(v2_owner_sessions, UserSimulationAssociation, saved).simulation_id + is None + ) + assert remaining_of(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_row( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=ECONOMY_REPORT, + name="CTC report", + ) + 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_for(v2_owner_sessions, stored_rows) + service = migration_service(runtime_sessions, v1_sessions, simulation_service) + + run = migrate(service, stored_rows) + + mapping = policy_mapping(v2_owner_sessions, CTC_REFORM_WITH_ELASTICITY) + assert mapping is not None + assert simulation_service.definitions == [ + ApiV2ReportDefinition( + country_id="us", + kind=ApiV2ReportKind.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 = 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_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_row( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=ECONOMY_REPORT, + budget_window_years=10, + ) + simulation_service = simulation_service_for(v2_owner_sessions, stored_rows) + service = migration_service(runtime_sessions, v1_sessions, simulation_service) + + 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 = stored_row(v2_owner_sessions, UserReportAssociation, saved) + assert row.report_id == simulation_service.reports[definition] + assert row.budget_window_years == 10 + 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_row( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=HOUSEHOLD_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) + + 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 = policy_mapping(v2_owner_sessions, CTC_REFORM) + assert reform_mapping is not None + assert simulation_service.definitions == [ + ApiV2ReportDefinition( + country_id="us", + kind=ApiV2ReportKind.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_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_row( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=MISSING_PARAMETER_REPORT, + ) + unknown_region = save_row( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=UNKNOWN_REGION_REPORT, + ) + refused = save_row( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=HOUSEHOLD_REPORT, + ) + no_v1_report = save_row( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=940_399, + ) + 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) + + skipped = result_of(run, missing_parameter) + assert skipped.outcome is RowOutcome.MISSING_PARAMETERS + assert skipped.missing_parameters == (REMOVED_PARAMETER,) + 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_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 ( + 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. + assert [item.kind for item in simulation_service.definitions] == [ + ApiV2ReportKind.HOUSEHOLD + ] + + +# Dry runs and running again. + + +def test_a_dry_run_writes_nothing_and_predicts_the_real_run( + runtime_sessions, + v1_sessions, + v2_owner_sessions, + stored_rows, + read_only_runtime_sessions, +) -> None: + saved_rows = [ + save_row( + 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_row( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=ECONOMY_REPORT, + ) + ) + saved_rows.append( + save_row( + v2_owner_sessions, + UserHouseholdAssociation, + user_id=stored_rows.first_user, + legacy_household_id=V1_HOUSEHOLD, + ) + ) + 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_runtime_sessions, v1_sessions, simulation_service + ) + before = row_counts(v2_owner_sessions) + + dry_run = migrate(read_only_service, stored_rows, apply=False) + + assert row_counts(v2_owner_sessions) == before + assert simulation_service.definitions == [] + 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 + ] == [ + (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_row( + v2_owner_sessions, + UserPolicy, + user_id=stored_rows.first_user, + legacy_policy_id=CTC_REFORM, + ) + 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) + service = migration_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_row( + v2_owner_sessions, + UserPolicy, + user_id=stored_rows.first_user, + legacy_policy_id=legacy_policy_id, + ) + service = migration_service( + runtime_sessions, + v1_sessions, + simulation_service_for(v2_owner_sessions, stored_rows), + ) + + run = migrate(service, stored_rows, limit=1) + + assert [result.outcome for result in run.results] == [RowOutcome.MIGRATED] + 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_row( + v2_owner_sessions, + UserPolicy, + user_id=stored_rows.first_user, + legacy_policy_id=CTC_REFORM, + ) + saved_report = 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) + service = migration_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 ( + 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] == [ + SavedRecordKind.SAVED_REFORM, + SavedRecordKind.SAVED_HOUSEHOLD, + ] + assert run.closing_check.passed + + +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_row( + 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 API v2 report wasn't migrated. + save_row( + 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_for(v2_owner_sessions, stored_rows) + service = migration_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.api_v1_budgetary_impact, item.api_v1_country_package_version) == ( + -10.0e9, + "1.420.0", + ) + 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 == [] + + +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_row( + v2_owner_sessions, + UserReportAssociation, + user_id=stored_rows.first_user, + legacy_report_id=legacy_report_id, + report_id=report.report_id, + ) + service = migration_service( + runtime_sessions, + v1_sessions, + simulation_service_for(v2_owner_sessions, stored_rows), + ) + + comparison = service.compare_sample( + size=1, country_ids=("us",), user_ids=(stored_rows.first_user,) + ) + + (item,) = comparison.comparisons + # 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/integration/test_v2_saved_record_migration_failures.py b/tests/integration/test_v2_saved_record_migration_failures.py new file mode 100644 index 000000000..9511493fe --- /dev/null +++ b/tests/integration/test_v2_saved_record_migration_failures.py @@ -0,0 +1,512 @@ +"""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_runtime_role_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) + + +@pytest.fixture +def read_only_runtime_sessions( + disposable_v2_database_url: str, managed_v2_roles: ManagedV2Roles +) -> Iterator[sessionmaker[Session]]: + yield from read_only_runtime_role_sessions( + disposable_v2_database_url, managed_v2_roles + ) + + +# 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, + read_only_runtime_sessions, +) -> 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_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/libs/test_simulation_reports_without_runs.py b/tests/unit/libs/test_simulation_reports_without_runs.py new file mode 100644 index 000000000..2b32cfb83 --- /dev/null +++ b/tests/unit/libs/test_simulation_reports_without_runs.py @@ -0,0 +1,440 @@ +"""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_simulation_client.api.default import create_report_without_run +from policyengine_api_simulation_client.models import ( + BudgetWindowReportRequest, + EconomyReportRequest, + 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, + 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 + + +@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=f"the {definition.kind.value} report has no"): + service.submit(dataclasses.replace(definition, 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 == [] + + +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", + [ + 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 new file mode 100644 index 000000000..1bb7c472f --- /dev/null +++ b/tests/unit/test_migrate_saved_records_script.py @@ -0,0 +1,545 @@ +"""Tests for the one-time command that migrates saved records' API v1 references.""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +from contextlib import contextmanager +from types import SimpleNamespace +from typing import TYPE_CHECKING +from uuid import UUID + +import pytest + +from policyengine_api.constants import REPO +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, + SampleComparison, + 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: + 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") +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: + """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] = [] + 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) + 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 + 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. + + ``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, submits_reports: bool + ) -> Iterator[FakeMigrator]: + self.dry_runs.append(dry_run) + self.report_submissions.append(submits_reports) + 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_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})) + + 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"], + ["--kind", "saved_policy"], + ["--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_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)], + ["--compare-sample", "5", "--kind", "saved_report"], + ], +) +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 == [] + + +@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 + + +@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="cloud_run_simulation_entrypoint", + SIMULATION_ENTRYPOINT_URL="https://simulation.example.test", + GATEWAY_AUTH_REQUIRED="1", + ) + + assert result.returncode == 0, result.stderr + 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: + 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_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" + "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/test_v2_integration_workflow.py b/tests/unit/test_v2_integration_workflow.py index dd0c5b185..d63fe6826 100644 --- a/tests/unit/test_v2_integration_workflow.py +++ b/tests/unit/test_v2_integration_workflow.py @@ -113,3 +113,23 @@ 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 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. + """ + commands = _step_commands(_runtime_job()) + 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 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..2af520fac --- /dev/null +++ b/tests/unit/v2/test_saved_record_migration_rules.py @@ -0,0 +1,683 @@ +"""The one-time migration's rules that need no database (D4 · 1). + +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. +""" + +from __future__ import annotations + +import json +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 ( + api_v2_report_definition, + budget_window_size, + closing_check, + kept_policy_snapshot, + migration_document, + relative_difference, + sample_comparison_document, +) +from policyengine_api.services.v2.saved_record_migration.types import ( + ApiV2ReportKind, + FailureReason, + MigrationOptions, + MigrationRun, + PolicySide, + ReportComparison, + RowOutcome, + SampleComparison, + SavedRecordKind, + SavedRecordResult, + V1ReportDefinition, + V1ReportKind, + V1ReportRecord, + V1SimulationRecord, +) +from policyengine_api.services.v2.saved_record_migration.validators import ( + SavedRecordMigrationRefusal, + require_catalog_region_code, + validate_v1_report, +) + +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 + + +# An API 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 + + +# API 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", "country/Northern Ireland", "country/northern_ireland"), + ("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 API v2 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 = api_v2_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 ApiV2ReportKind.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 = api_v2_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 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 = api_v2_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 ApiV2ReportKind.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, + api_v2_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", + "api_v2_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"] == [] + + +# The sample comparison of migrated reports' results with API v1's. + + +@pytest.mark.parametrize( + ("v1_value", "api_v2_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, + api_v2_value: float | None, + difference: float | None, +) -> None: + measured = relative_difference(v1_value, api_v2_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, + 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, + ), + ), + ) + + 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), + "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, + } + ], + } + + +# 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" + ) + + +@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 diff --git a/uv.lock b/uv.lock index 06ddad4da..7fbc3ee51 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.20261201.450" }, + { 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.20261201.450" +version = "0.20261201.454" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "attrs" }, { name = "httpx" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/b6/40/60ed8e05bdc8c15cdc56eec982ea52a22de3b92e13f9638696c37ee8a38c/policyengine_api_simulation_client-0.20261201.450.tar.gz", hash = "sha256:184f279698c246382bc1ad4eda672ec2f68f5862c2c85b4ae0894f4b87dc013a", size = 74845, upload-time = "2026-12-01T01:19:03.464Z" } +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/57/66/25ed2444fb94a160c52bbe2b52cd147ab662e2edb938882859bb4ef4cd1d/policyengine_api_simulation_client-0.20261201.450-py3-none-any.whl", hash = "sha256:d08dd5e705056fee906c4ce89137e58d6d4c60a1a618aa88b2723dc68a6100c5", size = 167982, upload-time = "2026-12-01T01:19:02.044Z" }, + { 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]]