Skip to content

Add the one-time command that migrates saved records' API v1 references to API v2 - #4359

Merged
anth-volk merged 25 commits into
masterfrom
v2plan/d4-1-migration-command
Dec 1, 2026
Merged

anth-volk merged 25 commits into
masterfrom
v2plan/d4-1-migration-command

Conversation

@anth-volk

@anth-volk anth-volk commented Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #4358

Summary

Adds scripts/migrate_saved_records_to_api_v2.py, API v1's one-time operator command (tracker task D4 · 1). It gives saved records that hold only an API v1 reference their API v2 record, and keeps the API v1 reference, so a row holding both is the record that it was migrated.

  • Saved reforms (user_policies) get their API v1 policy's copy from mirror_legacy_policy_in_session, which splits model assumptions (gov.simulation, US simulation, UK gov.dynamic) into a dynamic and maps the API v1 ID. When the copy has a dynamic, the owner gets a saved dynamic with the saved reform's name and description (create_user_dynamic_in_session).
  • Saved households get their API v1 household's copy (mirror_legacy_household_in_session).
  • Saved reports: the API v1 report is rebuilt from report_outputs, simulations and policy/household as ReportSpecService reads them.
    • Each side's policy is copied and split; a side with no policy values names no policy, so identical API v1 reports share one report.
    • Regions are translated through the catalog region reference files' v1_code.
    • A saved window of two years or more becomes a budget window.
    • The report is found or created through the simulation service's POST /reports/without-run (added by Find or create a report and its simulations by key without a run policyengine-sim-api#1167), once per API v1 report and window in a run, and each saved row is then pointed at it. The route finds a report by the key POST /reports uses and starts no run: app v3 starts a migrated report's first run through POST /v2/reports/{id}/runs when someone opens it.
  • Saved simulations are counted and listed, never migrated.
  • Missing parameters (decision A1 · 6): 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, without an API v1 ID mapping, and still leaves a row whose every parameter is missing.
  • Modes and filters: --dry-run (read-only transactions; calls no other service), --kind, --country, --limit, --user-id, and --compare-sample N, which prints API v1's stored budgetary impact next to the newest successful run's for up to N migrated economy reports and starts no run.
  • Output: one JSON document with every row's result (api_v2_id for a rollback) and a closing check counting the rows still holding only an API v1 reference, by kind and reason. Exit 0 when nothing failed or was left unattempted, 1 otherwise, 2 for bad arguments.
  • Connections: API v2's database as the runtime role (V2_RUNTIME_DATABASE_URL), and API v1's database read only as policyengine_schema_reader through the Cloud SQL Auth Proxy (POLICYENGINE_DB_READONLY_PASSWORD, POLICYENGINE_DB_PROXY_PORT). No new role, grant, setting or deployment.
  • Code: package services/v2/saved_record_migration (types, validators, transformations, sessions, connectors, copies/services.py, services.py).

Sending reports to the simulation service (policyengine_api/libs/simulation_reports_without_runs.py):

  • SimulationServiceReportSubmitter sends each report definition through the generated client's create_report_without_run operation (post_report_without_run in simulation_service_operations). The body is the one API v1's POST /v2/reports sends for the same report, built by the same functions from the same creation inputs; an economy report sends include_cliffs: false, which the route requires.
  • A 201 or 202 gives the report ID. A 400 or 422 fails the row as report_refused, with the service's code (or the status) and reason. Any other answer, an unreadable created answer, or a transport failure fails it as simulation_service_unavailable, naming only the status and a fixed-identifier code; the row keeps its API v1 reference and the next run sends it again, which finds the same report. A definition API v1's creation inputs refuse is report_refused (invalid_report_definition) before anything is sent.
  • The command builds the client only for a real run whose kinds include saved_report, before it connects to either database, and closes it last. It needs SIMULATION_ENTRYPOINT_URL, the GATEWAY_AUTH_* credentials with GATEWAY_AUTH_REQUIRED=1 as deployed, and SIM_ENTRYPOINT=cloud_run_simulation_entrypoint (API v1's simulation client reads the v1 economy routes' setting when loaded). It loads that client with standard output sent to standard error, so the logging runtime it builds writes no records among the JSON document.

Simulation client pin: policyengine-api-simulation-client is pinned to 0.20261201.454, the first release published after PolicyEngine/policyengine-sim-api#1167 deployed; it has create_report_without_run and the inline household calculation models master pinned 0.20261201.450 for.

What the merge waits for: D4 · 0 (PolicyEngine/policyengine-sim-api#1167) deployed, since this PR pins the client release its deployment published and the command calls its deployed POST /reports/without-run. It is deployed (done).

Migration scope: no route, route contract or migration flag changes. Nothing on the Flask/API v1 path changes. The command only reads API v1's tables and writes API v2's.

Inline suppressions

  • E501 on eight import lines: a dotted module path can't be wrapped (the repository's existing practice).
  • FBT001 on one parametrized test argument: pytest passes parameters positionally.
  • BLE001 twice in the service: an error other than a refusal is recorded on its row, or on every saved report of its report, so the run goes on and prints every row's result.
  • PLR0913 on _result (the record and outcome, then each optional field) and api_v2_report_definition (the API v1 definition, then each part the copies give).
  • N818 on SavedRecordMigrationRefusal: a refusal of one row, not a programming error.

Testing

  • Failing tests were committed first for each change, then the change.
  • 116 test cases for the migration itself pass, each run by node ID:
    • unit tests for the rules, the command's flags and output, and the workflow;
    • PostgreSQL 17 and MySQL 8.4 tests as the runtime role, in test_v2_saved_record_migration and test_v2_saved_record_migration_failures;
    • the privilege and CRUD guard cases the new connectors add.
  • Sending reports: c94595c6e adds tests that fail before the change (the script's 9 new cases failed, and the submitter's test module could not import its module); after 05932500c and the review fixes (586fb67c8 tests, ef0f38e02 change), all 75 cases in tests/unit/libs/test_simulation_reports_without_runs.py and tests/unit/test_migrate_saved_records_script.py pass, each run by node ID, against the client generated from Find or create a report and its simulations by key without a run policyengine-sim-api#1167, and again against the published 0.20261201.454. They cover each kind's request body against the generated operation's, every answer's mapping, transport failures, the client being built only for runs that send reports and closed after both databases, and the JSON document staying alone on standard output.
  • make quality-check, python -m scripts.rules validate, python scripts/run_quality_guards.py, lint-imports, alembic -c alembic-v2.ini check (no drift; no revision) and export_migration_contracts.py (no change) pass.
  • The cross-database workflow gains one step running the two integration modules. It reads the job's existing ALEMBIC_DATABASE_URL, V2_MIGRATION_DATABASE_URL and V2_ALEMBIC_DISPOSABLE_TEST, set as literal values in the job's env:.
  • Three rounds of adversarial review: round 1 found two bugs, fixed test-first; rounds 2 and 3 (round 3 on sending reports) found none, and their quality findings are fixed. No known bugs are left.

🤖 Generated with Claude Code

anth-volk and others added 13 commits November 28, 2026 02:13
Tests for API v1's one-time command that gives saved reforms, saved
reports and saved households holding only an API v1 reference their
API v2 records (D4 · 1): rebuilding API v1 reports, translating API v1
regions, dropping missing parameters in the second mode, the closing
check, the command's flags and output, and the cross-database run as
the runtime role. They fail because the command doesn't exist yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The cross-database integration workflow must run the migration's
PostgreSQL and MySQL tests after the managed roles' grants are checked.
The integration tests also take a catalog version of their own that is
a canonical PEP 440 version, as stored policies require.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
scripts/migrate_saved_records_to_detailed_save.py gives saved reforms,
saved households and saved reports that hold only an API v1 reference their
API v2 records (D4 · 1), keeping the API v1 reference:

- a saved reform gets its API v1 policy's copy from API v1's policy copy into API v2
  (mirror_legacy_policy_in_session, which splits model assumptions into
  a dynamic), and a saved dynamic with its name when the policy sets
  assumptions (create_user_dynamic_in_session);
- a saved household gets its API v1 household's copy;
- a saved report gets the report the simulation service finds or
  creates for the API v1 report's definition, each side's policy split the
  same way, a side left with no policy values naming no policy, and its
  region translated through the catalog's region reference files.

Saved simulations are only listed. Rows whose policies set a parameter
the running catalog lacks are left and listed; --drop-missing-parameters
migrates them from the parameters that still exist, without an API v1 ID
mapping, and still leaves a row whose every parameter is missing. A dry
run writes nothing. The command prints a JSON document with every row's
result and a closing check, and exits 1 when rows are left that the
decisions don't leave. It connects as the runtime role and reads API v1 as
its read-only role. The cross-database workflow runs its tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A separate run of the command (--compare-sample N) reads N migrated
economy reports that have a successful run and prints API v1's stored
budgetary impact next to the run's, with their relative difference and
both country package versions (decided 2026-11-28). It writes nothing,
starts no run and never fails on its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
--compare-sample N reads up to N migrated economy reports, each named by
a saved report that holds both its API v1 report output and its report and
having a successful run, and prints API v1's stored budgetary impact next to
the newest successful run's, rebuilt from its budget summary as
/v2/reports does, with the relative difference and both country package
versions. It reads both databases only, starts no run and exits 0: a
person reads it, since a newer model alone can change the numbers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The command becomes scripts/migrate_saved_records_to_api_v2.py, its
output fields api_v2_id, api_v1_budgetary_impact and
api_v2_budgetary_impact, and its types ApiV2ReportDefinition and
ApiV2ReportKind. Docstrings, messages and the changelog fragment name
API v1 and API v2 in full. Nothing else changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A run can take some kinds of saved record only (decided 2026-11-30), so
a rehearsal on a copy of production whose simulation service can't
calculate migrates saved reforms and households without asking it for
any report. The closing check and the JSON document cover only those
kinds and name them, and the document says the sample comparison wasn't
run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
--kind (repeatable: saved_reform, saved_household, saved_report,
saved_simulation; every kind without it) keeps a run to those kinds of
saved record. The closing check and the JSON document cover only those
kinds and name them (kinds), and the document says the sample
comparison wasn't run. --compare-sample takes no --kind. Docstrings that
still had a bare `v1` at the end of a line of text now name API v1 in
full.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A saved reform whose description a saved dynamic can't take fails its
  row alone, in the dry run too, and the run goes on.
- A refused report is asked for once for all its saved reports.
- An unexpected error fails its row, and the run still prints its rows.
- In the second mode, a report keeps what still exists on both sides,
  and a report left because every parameter of its own policy is missing
  lists both sides' missing parameters.
- A dry run fails an API v1 policy mapped from another source, as a run
  does.
- A UK nation typed with spaces matches its region.
- One rule says which saved windows are budget windows.

Tests for a row changed during the run, saved reforms sharing a copy and
a dry run through a read-only connection pass already and add coverage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A saved reform's saved dynamic is checked before anything is written:
  one that can't take the saved reform's name or description, such as a
  description over 10,000 characters, fails its row alone
  (saved_dynamic_not_valid), in a dry run too.
- Any error other than a refusal fails its row (unexpected_error, with
  the error's type and message), so the run goes on and prints every
  row's result.
- What happens to an API v1 report is worked out once per run and
  window, whatever its outcome, so a refused report is asked for once
  for all its saved reports; each saved row is then pointed at it.
- A report left because every parameter of its own policy is missing
  lists both sides' missing parameters.
- A dry run checks an existing policy mapping's source hash and a
  household mapping's fingerprint, as a run's copies do.
- A UK nation typed with spaces matches its region.
- One rule (budget_window_size) says which saved windows are budget
  windows, and two docstrings are corrected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A run without a client for the simulation service fails each saved
  report as simulation_service_unavailable before writing anything for
  it.
- An unexpected error keeps only its type and first line, so no row's
  contents reach the output.
- CI also runs the failures' integration tests.

Tests for an unexpected error in a saved household, an unexpected report
error met once for all its saved reports, and a read-only dry run of
the second mode over household, budget-window and missing-parameter
reports pass already and add coverage. The integration tests are split,
under the test file length limit, into saved_record_migration_support
(rows, the stand-in for the simulation service and helpers) and two
test modules; the tests themselves don't change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A run without a client for the simulation service fails each saved
  report as simulation_service_unavailable before it reads or writes
  anything for it.
- One helper turns an error into a failed row: a refusal keeps its
  reason and message, any other error only its type and first line, so
  a database error's statement and parameters never reach the output.
- The copy plan says why missing parameters are found before an
  existing copy is looked up (A1 · 6).
- The cross-database workflow also runs the failures' tests; the step
  reads only the job's existing database URLs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.42892% with 87 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.88%. Comparing base (9fa521b) to head (0e274f8).
⚠️ Report is 37 commits behind head on master.

Files with missing lines Patch % Lines
...api/services/v2/saved_record_migration/services.py 82.79% 21 Missing and 16 partials ⚠️
...vices/v2/saved_record_migration/transformations.py 70.73% 13 Missing and 11 partials ⚠️
...vices/v2/saved_record_migration/copies/services.py 84.33% 12 Missing and 1 partial ⚠️
..._migration/database_connectors/reads_v1_records.py 78.12% 3 Missing and 4 partials ⚠️
...aved_record_migration/database_connectors/reads.py 90.00% 1 Missing and 3 partials ⚠️
...i/services/v2/saved_record_migration/validators.py 97.75% 0 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #4359      +/-   ##
==========================================
- Coverage   94.04%   93.88%   -0.17%     
==========================================
  Files         449      459      +10     
  Lines       25349    26172     +823     
  Branches     3905     4047     +142     
==========================================
+ Hits        23840    24571     +731     
- Misses        860      916      +56     
- Partials      649      685      +36     
Flag Coverage Δ
integration 60.65% <76.30%> (+0.51%) ⬆️
unit 90.41% <59.53%> (-1.03%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

anth-volk and others added 3 commits November 30, 2026 21:54
- The ORM-only check refused the integration tests reading a session
  factory's engine (sessions.kw['bind']) to make read-only sessions.
  tests/fixtures/database_sessions gains v2_read_only_role_sessions,
  which builds read-only sessions for a role as v2_role_sessions builds
  them, and the dry-run tests take a read-only runtime fixture from it.
- The runtime SQL boundary check matched "database.transaction(" in the
  service. Its session attributes are now _database_session and
  _v1_database_session, as other services name theirs.
- The integration workflow keeps its seven coverage steps: the two
  saved-record migration modules join the step that tests saved
  records. The step reads only the job's existing database URLs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
v2_role_sessions takes read_only, for sessions that act as a role with
every transaction READ ONLY, as a dry run's are.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The review of the CI fix found no bug; its quality findings:
- v2_role_sessions takes read_only instead of a near-copy of it, and
  the Alembic skill's table of session factories says so.
- The saved-record migration tests' read-only runtime fixture shares its
  body through saved_record_migration_support.
- V2SavedRecordMigrationService's parameters are named as its
  attributes: database_session and v1_database_session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…-api into v2plan/d4-1-migration-command

# Conflicts:
#	.github/workflows/v2-integration-check.yml
anth-volk and others added 4 commits December 1, 2026 05:21
The migration command (D4 · 1) asks the simulation service to find or
create each saved report's API v2 report through POST /reports/without-run
(D4 · 0), which starts no run. These tests cover the request body for each
kind of report, how each answer is read, and the command building the
simulation service's client only for a run that migrates saved reports.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SimulationServiceReportSubmitter sends each saved report's API v2
definition to POST /reports/without-run (D4 · 0), with the body API v1's
POST /v2/reports builds for the same report, and returns the report the
service found or created. A 400 or 422 is a refusal with the service's
code and reason; any other answer leaves the row for the next run, which
finds the same report by its definition.

The command builds the client only for a run that migrates saved
reports, before it connects to either database, and loads it with
standard output sent to standard error, so the log records of the
runtime it builds stay off the JSON document.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- An economy report or budget window without a reform says it has none.
- A refusal of the whole definition names the definition, not an empty
  field.
- The command checks the v1 economy routes' entrypoint settings before
  loading API v1's simulation client, and names missing gateway
  credentials as a missing setting.
- The report client is closed after both databases, also when a setting
  is missing or the run fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The submitter validates each report's creation input from a mapping, so
  its types check, and says a report without a reform has none.
- A refusal of the whole definition names the definition.
- The command checks the v1 economy routes' entrypoint settings before
  loading API v1's simulation client, rather than catching every
  ValueError the load raises, and names missing gateway credentials as a
  missing setting. Its docs ask for GATEWAY_AUTH_REQUIRED=1, as deployed.
- Docstrings name the new route's request test and no longer say no
  route finds what a submission created.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk and others added 2 commits December 1, 2026 22:16
The pinned policyengine-api-simulation-client lacks
create_report_without_run until the release published after
PolicyEngine/policyengine-sim-api#1167 deploys, and API v1 fails to load
its simulation modules without it, which fails every test shard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…create"

This reverts commit cdd70d5. D4 · 0 is deployed and its client release
0.20261201.454 has create_report_without_run, so the pin is raised to it
instead of loading the operation only when a report is sent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk and others added 2 commits December 1, 2026 22:18
policyengine-api-simulation-client 0.20261201.454 is the first release
published after PolicyEngine/policyengine-sim-api#1167 deployed; it has
create_report_without_run, which the migration command's report
submitter calls.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Conflicts: master pinned policyengine-api-simulation-client 0.20261201.450
(the inline household calculation); this branch pins 0.20261201.454, the
first release with create_report_without_run, which also has
master's models. The pin comment names both; uv.lock is master's with the
client moved to 0.20261201.454.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@anth-volk
anth-volk marked this pull request as ready for review December 1, 2026 19:53
@anth-volk
anth-volk merged commit d385ad0 into master Dec 1, 2026
24 checks passed
@anth-volk
anth-volk deleted the v2plan/d4-1-migration-command branch December 1, 2026 19:55

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

One-time command to migrate saved records' API v1 references to API v2

1 participant