Skip to content

Make UK gov.dynamic a model assumption, and add a command that splits stored policies holding model assumptions - #4345

Merged
anth-volk merged 12 commits into
masterfrom
v2plan/c1-48-split-policy-copies
Nov 26, 2026
Merged

anth-volk merged 12 commits into
masterfrom
v2plan/c1-48-split-policy-copies

Conversation

@anth-volk

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

Copy link
Copy Markdown
Collaborator

Fixes #4344

Builds on #4337 (users' saved dynamics, user_dynamics), which merged into master as 9bcda036f; this branch contains it, so it targets master directly.

Summary

UK gov.dynamic. is a model assumption. DYNAMIC_PARAMETER_PREFIXES (policyengine_api/dynamic_parameters.py) gains UK gov.dynamic. beside gov.simulation.. In policyengine-uk 2.174.1 it holds one parameter, gov.dynamic.obr_labour_supply_assumptions, a yes/no switch nothing outside the package's tests reads. As a result:

  • POST /v2/policies refuses it with 422 dynamic_parameters;
  • POST /v2/dynamics accepts it;
  • the v1-to-v2 policy copy (mirror_legacy_policy_in_session, split_legacy_policy_json) puts it in the copy's dynamic.

canonical_parameter_name needs no change, since gov.dynamic has one spelling. The two errors' messages, the dynamics' field description and both routes' descriptions name the prefix; the generated contract documents don't change. US policies are unchanged.

A command splits stored policies that set model assumptions. scripts/split_v2_policy_copies.py, with the logic in services/v2/policy_copy_split/, handles every stored v2 policy that sets a parameter under gov.simulation., US simulation. or UK gov.dynamic.. For each one, in one transaction, it:

  • finds or creates the policy without the assumptions (empty when there are none) and the dynamic holding them. Both are on the copy's own catalog version, with the same parameter IDs, values and dates, and are stored through create_resolved_policy and create_resolved_dynamic;
  • points each legacy_policy_mappings row that names the copy at them. A mapping that already names a dynamic gets one dynamic holding both sets of values;
  • points each user_policies row that names the copy at the policy. It gives the owner a user_dynamics row with the saved policy's name and no description, through create_user_dynamic_in_session, unless the owner already has an identical one;
  • deletes the copy, with its values, once nothing names it.

D4 · 1's migration can reuse split_policy_copy_in_session, which runs in the caller's transaction.

Decisions (the user, 2026-11-25):

  • The command runs by hand from a checkout, as a temporary database role. It only lists what it would change, in READ ONLY transactions, unless given --apply.
  • A copy that a simulations, reports or household_jobs row names is split and re-pointed but kept. Those rows' keys hash the policy, and their policy_id is ON DELETE SET NULL. The run then exits with 1.
  • The saved dynamic takes the saved policy's name only, and an identical existing one is reused.
  • A mapping's existing dynamic is merged with the copy's assumptions. If they conflict, or are on another catalog version, the copy is refused and nothing changes for it.

Concurrency with API v1's live writes:

  • The split locks the mappings, then the copy (the order API v1's copy of a v1 saved policy uses), then each saved policy just before saving its owner's dynamic.
  • Its lock waits end after 500 ms, shorter than PostgreSQL's default one-second deadlock_timeout. A copy that meets a lock timeout or a deadlock is rolled back and tried again (five attempts in all). In a lock cycle with the sign-in merge or a user's deletion, the live write therefore goes ahead.
  • The command adds these limits, plus a 10-second connection timeout and a 60-second statement timeout, to its URL. It refuses Supavisor's transaction-mode port 6543, which doesn't keep them.

Output: one report per copy, giving:

  • the old copy's ID, country and catalog version;
  • its policy and dynamic (created or already stored);
  • each re-pointed mapping, with its earlier dynamic, and each re-pointed saved policy;
  • each saved dynamic created or reused;
  • the outcome: deleted, kept (with counts) or refused (with the reason).

The listing reports what --apply then does, including rows an earlier copy in the same run creates. The command exits with 0 only when no stored policy sets a model assumption afterwards.

How C1 · 49 runs it

As an operator step, from a checkout of the deployed release (runbook: docs/migration/stage-10-v2-policies.md, "Splitting stored policies that hold model assumptions"):

  1. Create the temporary role policyengine_v2_policy_copy_split with the runbook's DO block: a login with no other powers, a SCRAM-SHA-256 verifier in place of the password, USAGE on public, and exactly the grants POLICY_COPY_SPLIT_PRIVILEGES declares (a test keeps the two in step). Its only DELETE is on policies. It needs no DELETE on parameter_values, because the cascade runs as the table owner.
  2. Set these, in the shell only:
    • V2_POLICY_COPY_SPLIT_DATABASE_URL, the role's postgresql+psycopg:// URL with sslmode=require, on the direct host or on the pooler in session mode on port 5432;
    • V2_SUPABASE_PROJECT_REF and V2_SUPABASE_ENVIRONMENT, copied from the GitHub Actions environment variables of the same names.
  3. Run uv run --frozen python scripts/split_v2_policy_copies.py (read-only listing), then the same with --apply, then the listing again.
  4. Revoke the role's grants by name and drop it, with the runbook's second DO block. That works for a login that isn't a superuser, where DROP OWNED BY wouldn't.

Environment variables and secrets: none are stored or wired anywhere. The command reads only the three above, which the operator sets for the run. Nothing is deployed for it. No GitHub secret, Secret Manager secret or Modal secret is read.

Unverified for C1 · 49:

  • which login can create the role and grant it privileges on the migration role's tables. The C1 · 49 session's read-only preflight checks postgres's membership and grant options;
  • Supabase's deadlock_timeout, taken to be PostgreSQL's default of one second.

Deploy order

  1. This PR deploys in an environment (staging, then production), so the v1-to-v2 copy there splits UK gov.dynamic. too and no new policy holding model assumptions is stored.
  2. C1 · 49 runs the command there: the listing, --apply, and the listing again. A repeat listing that still lists kept or refused copies exits with 1. The operator settles those by hand, with the user's approval.
  3. Only then, once a listing lists nothing, does C1 · 50's revision run there. It refuses while a policy value names a dynamic parameter.

Overlap with open PRs

None. #4343 (C1 · 45) changes none of these files. #4333 and #4335, which also changed privileges.py and its test, have merged.

Changes outside the new package

  • data/v2/settings.py: V2_POLICY_COPY_SPLIT_DATABASE_URL and its loader.
  • data/v2/privileges.py: POLICY_COPY_SPLIT_ROLE and POLICY_COPY_SPLIT_PRIVILEGES, outside the managed roles. The deploy's grants check reads only the managed roles.
  • .github/workflows/v2-integration-check.yml: the policy step also runs tests/integration/test_v2_policy_copy_splits.py. It needs only the job's literal V2_MIGRATION_DATABASE_URL, V2_ALEMBIC_DISPOSABLE_TEST and DEPLOYMENT_ENVIRONMENT.
  • pyproject.toml: the package's session and service modules join banned-module-level-imports.
  • No new inline suppressions, and no schema or revision change.

Testing

  • 154 new and changed tests pass, run individually by node ID, and cover every line of the new package. They include 22 PostgreSQL tests run as a role holding exactly the declared grants, covering:
    • the split, re-pointing and saved dynamics;
    • the empty policy and the merged dynamic;
    • copies kept by a simulation, a report or a household job;
    • refusals;
    • the listing matching --apply across copies;
    • READ ONLY sessions refusing writes;
    • the time limits reaching the session;
    • lock cycles with the v1 saved-policy copy and with the sign-in merge, whichever side waits first.
    • a saved policy deleted or pointed elsewhere after the split reads it.
  • Checks: ruff and ruff format, mypy (plus mypy on the script and the changed data/v2 modules), lint-imports, python -m scripts.rules validate, python scripts/run_quality_guards.py, the ORM-only check, alembic -c alembic-v2.ini check (no new operations), and scripts/export_migration_contracts.py (no change).

Review

Three adversarial review rounds, with each bug fixed test-first:

  • Round 1: a deadlock with the v1 saved-policy copy, and the listing overstating what --apply creates across copies.
  • Round 2: a deadlock with the sign-in merge, a role-dropping statement that needed a superuser, and port 6543 dropping the time limits.
  • Round 3: the sign-in merge could still be aborted when it waited first.

The code-quality findings were fixed too, apart from column-level UPDATE grants. The repository's privilege analysis counts only whole-table privileges for a connector's needs, row locks included.

🤖 Generated with Claude Code

anth-volk and others added 10 commits November 25, 2026 22:25
…(failing)

Failing tests for tracker task C1 · 48 (API v1):

- UK gov.dynamic. joins the model-assumption prefixes: /v2/policies refuses
  it, /v2/dynamics accepts it, and the v1-to-v2 copy puts it in the dynamic.
- A command splits every stored policy that sets a model assumption into a
  policy and a dynamic on its own catalog version, re-points its legacy
  mappings and saved policies, gives each saved policy a saved dynamic with
  its name, and deletes the old copy once nothing names it. A copy that a
  simulation, report or household calculation names is split and re-pointed
  but kept; a mapping that already names a dynamic gets one merged dynamic.
- The command runs as a temporary role holding only the grants it declares,
  and only lists what it would change unless given --apply.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tored policy copies

- DYNAMIC_PARAMETER_PREFIXES gains UK gov.dynamic., so /v2/policies refuses
  it with 422 dynamic_parameters, /v2/dynamics accepts it, and the v1-to-v2
  copy puts it in the copy's dynamic. The errors, OpenAPI descriptions and
  docs that list the prefixes name it.
- services/v2/policy_copy_split splits each stored policy that sets a model
  assumption into a policy and a dynamic on its own catalog version, through
  create_resolved_policy and create_resolved_dynamic. In one transaction per
  copy, which locks it first, it re-points the legacy mappings (merging a
  mapping's existing dynamic with the copy's assumptions) and saved policies,
  gives each saved policy's owner a saved dynamic with its name unless an
  identical one exists, and deletes the copy once nothing names it. A copy a
  simulation, report or household job names is kept; one whose mapping's
  dynamic conflicts is refused. split_policy_copy_in_session is D4 · 1's.
- scripts/split_v2_policy_copies.py lists what would change in READ ONLY
  transactions, or with --apply makes the changes, as the temporary role
  policyengine_v2_policy_copy_split. POLICY_COPY_SPLIT_PRIVILEGES declares its
  grants, and docs/migration/stage-10-v2-policies.md gives the SQL that
  creates and drops it, with the deploy order.
- The Postgres tests run in the cross-database integration job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The split deadlocks with API v1's copy of a v1 saved policy, which locks
  the mapping and then inserts a saved policy naming the copy: the split
  locks the copy first, then the mapping.
- The read-only listing says a later copy's dynamic and saved dynamic would
  be created when --apply reuses the ones an earlier copy created.
- The command's connection has no connection, lock or statement timeout.

Also covers a copy a simulation names, and the listing's READ ONLY sessions
refusing a write.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The split locks the legacy mappings and saved policies naming a copy
  before the copy, and reads them again once it is locked, so it waits for
  API v1's copy of a v1 saved policy (which locks a mapping, then names the
  copy) instead of deadlocking with it.
- The listing carries the rows it reports across copies, so a dynamic or
  saved dynamic an earlier copy would create is reported as reused, as
  --apply then does; the command says "the one listed above would be
  reused" for such a row.
- The command adds a 10-second connection timeout, a 10-second lock timeout
  and a 60-second statement timeout to its URL.
- The runbook says what the repeat listing may show and what the operator
  does about kept and refused copies, names the saved policy's baseline and
  provenance instead of a label, and describes the lock order and the
  timeouts. A comment in privileges moves back above _RESULT.

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

Brings v2plan/c1-43-user-dynamics at 2a9184b, which merged master at
019acda, with its ORM-only rule and session factories.

- policyengine_api/data/v2/database.py: master's version, which has the
  same unpooled_v2_sessions and unpooled_v2_read_only_sessions.
- v2-integration-check.yml: the policy step runs both master's
  test_v2_dynamic_persistence.py and test_v2_policy_copy_splits.py.
- The split's Postgres tests use the v2_owner_sessions and
  v2_sessions_as_role fixtures, and the listing acts as the temporary role
  (act_as) in the owner's READ ONLY sessions; the grant test names
  RequiredPrivilege.table_name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The split deadlocks with API v1's sign-in merge, which locks the browser's
  user and then moves its saved policies, while the split holds a saved
  policy's lock and waits for the user's to save its dynamic. The split
  should give way: a lock timeout shorter than PostgreSQL's one-second
  deadlock_timeout (500 ms), then the copy tried again.
- The runbook's DROP OWNED BY fails for a login that isn't a superuser; it
  should revoke each grant, then drop the role.
- The split's URL accepts Supavisor's transaction-mode port 6543, where the
  lock and statement timeouts don't apply.

Also covers a refusal for a mapping's dynamic on another catalog version,
the listing of a merged dynamic, and a copy kept by a household
calculation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The split gives way to API v1's live writes in a lock cycle, such as the
  sign-in merge: the command's lock timeout is now 500 ms, shorter than
  PostgreSQL's default one-second deadlock_timeout, and the service rolls a
  copy back and tries it again after a lock timeout or a deadlock, up to
  five times a second apart.
- The runbook revokes each of the temporary role's grants by name, then
  drops it, which a login that isn't a superuser can do; DROP OWNED BY
  can't.
- The split's URL refuses Supavisor's transaction-mode port 6543, which
  doesn't keep its lock and statement timeouts.
- Listing and applying share one per-copy path (_split_prepared), with the
  listing's rows and the run's rows behind one interface, so they report
  the same steps. count_rows_naming_policy returns CopyReferences, and the
  runbook says "two null names".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When API v1's sign-in merge waits for a saved policy the split locked
early, and the split joins the lock cycle more than half a second later
(slow round trips between locking the copy and saving the owner's
dynamic), PostgreSQL aborts the merge rather than the split.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The split locks each saved policy naming the copy only just before saving
its owner's dynamic, and reads it again then (its owner may have moved to
an account at sign-in, or it may have been deleted or pointed elsewhere),
instead of locking it with the mappings at the start. Its two waits in a
lock cycle with a live write that locks the user first (API v1's sign-in
merge, or a deletion of the user) then come within a few statements of
each other, so its half-second lock timeout always ends its wait first and
the live write goes ahead.

The docs say five attempts in all, not five retries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings #4337's merge (9bcda03) and the release version bump (888ae61).

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

codecov Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.35294% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.92%. Comparing base (9ed45bc) to head (b798285).
⚠️ Report is 13 commits behind head on master.

Files with missing lines Patch % Lines
...gine_api/services/v2/policy_copy_split/services.py 98.01% 0 Missing and 4 partials ⚠️
...i/services/v2/policy_copy_split/transformations.py 90.00% 0 Missing and 2 partials ⚠️
...ne_api/services/v2/policy_copy_split/validators.py 97.43% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #4345      +/-   ##
==========================================
+ Coverage   93.85%   93.92%   +0.06%     
==========================================
  Files         426      434       +8     
  Lines       23866    24291     +425     
  Branches     3703     3767      +64     
==========================================
+ Hits        22400    22815     +415     
- Misses        846      851       +5     
- Partials      620      625       +5     
Flag Coverage Δ
integration 59.68% <94.82%> (+0.64%) ⬆️
unit 90.52% <64.00%> (-0.50%) ⬇️

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.

Brings C1 · 45 (#4343, dynamics on household calculations) and the
release version bump (9ed45bc).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Codecov's report on #4345 listed lines in the new package that only
concurrency or unusual rows reach. Tests now cover them:

- a saved policy deleted, or pointed at another policy, after the split
  read it and before it locks it, which is skipped;
- the listing of a refused copy, and a policy that is gone or sets no
  model assumption, for which listing and splitting return None;
- count_policy_copies, after a run that deletes one copy and keeps one;
- the refusal's message, and require_stored_row raising.

read_saved_policies_naming_policy loses its lock parameter, which nothing
has passed since the split began locking each saved policy on its own.
The Postgres tests' row helpers move to tests/integration/
policy_copy_split_rows.py, keeping the test module under the 1,500-line
limit for test code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@anth-volk
anth-volk marked this pull request as ready for review November 26, 2026 14:01
@anth-volk
anth-volk merged commit 1cf1d1a into master Nov 26, 2026
24 checks passed
@anth-volk
anth-volk deleted the v2plan/c1-48-split-policy-copies branch November 26, 2026 14:01

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.

Make UK gov.dynamic a model assumption, and split stored v2 policies that set model assumptions

1 participant