Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/v2-integration-check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,8 @@ jobs:
run: uv run --frozen --extra dev python scripts/reconcile_v2_privileges.py verify
- name: Test v2 metadata publication, resource routes, the countries list, reports, simulations and users' report runs
run: uv run --frozen --extra dev coverage run --branch -m pytest -q tests/integration/test_v2_catalog_publication.py tests/integration/test_v2_catalog_publication_time_periods.py tests/integration/test_v2_catalog_publication_pruning.py tests/integration/test_v2_catalog_spm_availability.py tests/integration/test_v2_catalog_statistics.py tests/integration/test_v2_metadata_routes.py tests/integration/test_v2_country_routes.py tests/integration/test_v2_report_reads.py tests/integration/test_v2_report_creation.py tests/integration/test_v2_budget_window_report_reads.py tests/integration/test_v2_budget_window_report_creation.py tests/integration/test_v2_report_runs.py tests/integration/test_v2_report_reads_by_run.py tests/integration/test_v2_user_report_runs.py tests/integration/test_v2_user_report_run_requesters.py tests/integration/test_v2_user_budget_window_runs.py tests/integration/test_v2_forced_report_reruns.py tests/integration/test_v2_user_report_views.py
- name: Test v2 policy 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 v2 policy and dynamic persistence, immediate v1 mirroring and the policy copy split
run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_policy_persistence.py tests/integration/test_v2_dynamic_persistence.py tests/integration/test_v2_policy_copy_splits.py tests/integration/test_v1_policy_dual_write.py tests/integration/test_mysql_policy_dual_write.py tests/integration/test_v2_user_policy_mirroring.py tests/integration/test_v1_user_policy_dual_write.py
- name: Test signed-in identity provisioning, user associations, saved detailed-save records and user types
run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_user_identity_persistence.py tests/integration/test_v2_user_type_persistence.py tests/integration/test_v2_saved_detailed_save_records.py tests/integration/test_v2_saved_budget_window_reports.py
- name: Test comparison-run persistence, the simulation API's roles, shared reports and runs, privilege reconciliation as the managed roles, the v2 migration target checks as roles that don't own the database, and the tests' database sessions
Expand Down
1 change: 1 addition & 0 deletions changelog.d/v2-policy-copy-split.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
UK `gov.dynamic.` parameters (in policyengine-uk 2.174.1, the yes/no switch `gov.dynamic.obr_labour_supply_assumptions`) are now model assumptions, like `gov.simulation.`: `POST /v2/policies` refuses them with 422 `dynamic_parameters`, `POST /v2/dynamics` accepts them, and the v1-to-v2 policy copy puts them in the copy's dynamic. A new command, `scripts/split_v2_policy_copies.py`, splits every stored v2 policy that sets a model assumption into a policy and a dynamic on its own catalog version, re-points its legacy policy mappings and saved policies (giving each saved policy's owner a saved dynamic with its name), and deletes the old policy once nothing names it; it only lists what it would change unless given `--apply`, and runs as a temporary database role (`docs/migration/stage-10-v2-policies.md`).
183 changes: 179 additions & 4 deletions docs/migration/stage-10-v2-policies.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,9 @@ parameter path it sets exists in the running catalog and its periods and values
are valid.

The copy splits off the v1 policy's model assumptions: every value under
`gov.simulation.`, and in the US also `simulation.`
(`policyengine_api/dynamic_parameters.py`). It stores them as a v2 dynamic,
`gov.simulation.`, plus `simulation.` in the US and `gov.dynamic.` in the UK
(`policyengine_api/dynamic_parameters.py`; UK `gov.dynamic.` joined on
C1 · 48's deploy). It stores them as a v2 dynamic,
hashed and deduplicated as a policy is, and keeps the rest in the v2 policy,
which is empty when the v1 policy set nothing else. Before looking up the
parameters it rewrites the UK's old spelling
Expand All @@ -148,8 +149,10 @@ v1 policy that sets one parameter under both spellings with different values
fails as `conflicting_values`. The mapping in `legacy_policy_mappings` names the
policy and the dynamic (`dynamic_id`), or no dynamic when the v1 policy sets no
assumptions. A v1 policy copied before the split existed keeps its copy: its
assumptions stay policy values and its mapping names no dynamic, until the
one-time migration splits it again. Native `POST /v2/policies` refuses such
assumptions stay policy values and its mapping names no dynamic, and a UK
copy made before `gov.dynamic.` joined keeps those values in its policy too,
until the split command splits it (see "Splitting stored policies that hold
model assumptions" below). Native `POST /v2/policies` refuses such
values with 422 instead (code `dynamic_parameters`), and they are created
through `POST /v2/dynamics`.

Expand Down Expand Up @@ -287,3 +290,175 @@ is deleted, and existing Cloud SQL `user_policies` rows are kept.
The Public API also no longer serves Canada, Nigeria and Israel: their v1
policy requests are rejected as unknown countries before any write, so every
v1 policy write is now for a country that v2 supports.

## Splitting stored policies that hold model assumptions

`scripts/split_v2_policy_copies.py` (C1 · 48, run as the operator step C1 · 49)
splits every stored v2 policy that sets a model assumption: a parameter under
`gov.simulation.`, US `simulation.` or UK `gov.dynamic.`
(`policyengine_api/dynamic_parameters.py`). The v1-to-v2 copy made such
policies before it split model assumptions off, and for UK `gov.dynamic.`
values until that prefix joined; a v1 policy is never copied again. C1 · 50's
revision, which moves dynamic parameters into their own tables, refuses to
run while any policy value names one, because the foreign key's cascade would
otherwise change those policies silently.

For each such policy, in one transaction, the command
(`policyengine_api/services/v2/policy_copy_split/services.py`) locks the
legacy mappings that name it, then the policy itself (`SELECT … FOR
UPDATE`, so nothing can start naming it meanwhile), in the order API v1's
copy of a v1 saved policy takes the same locks, so the two wait for each
other instead of deadlocking. It locks each saved policy that names the
copy only just before saving its owner's dynamic, whose foreign-key check
waits for any lock on the owner's user, so its two waits come within a few
statements of each other. Its lock waits end after half a second, shorter
than PostgreSQL's default one-second `deadlock_timeout`, so in a lock cycle
with a live write that locks the user first, such as API v1's sign-in merge
(which locks a browser's user, then moves its saved policies) or a deletion
of the user, the split's wait ends first: it rolls back that copy and tries
it again a second later, for five attempts in all, and the live write goes
ahead. It then:

- finds or creates a policy holding the values that aren't model assumptions,
empty when there are none, and a dynamic holding the model assumptions,
both on the copy's own catalog version, with the same parameter IDs, values
and dates, through the services `POST /v2/policies` and `POST /v2/dynamics`
store them with;
- points each `legacy_policy_mappings` row that names the copy at that policy
and dynamic. A mapping that already names a dynamic (a UK copy made after
C1 · 36 holding `gov.dynamic.` values) gets one dynamic holding that
dynamic's values and the copy's model assumptions together; the earlier
dynamic is kept;
- points each `user_policies` row that names the copy at that policy, keeping
its name, description, `baseline` and `provenance`, and gives its owner a `user_dynamics` row
with the saved policy's name and no description, naming the dynamic the
saved policy's own v1 policy's mapping now names, or else the copy's
dynamic. When the owner already has a saved dynamic in that country naming
the same dynamic with the same name (two null names count as the same),
that one is reused;
- deletes the copy, and its values with it, once nothing names it.

A copy that a `simulations`, `reports` or `household_jobs` row names is
split and its mappings and saved policies are re-pointed, but the copy is
kept: those rows' keys hash the policy, and their `policy_id` is `ON DELETE
SET NULL`, so deleting the copy would silently make them current law. A copy
whose mapping's dynamic sets one of its model assumptions for the same start
date differently, is bound to another catalog version, or would hold more
than 1,000 values together with it, is refused, and nothing changes for it.
The user decided these cases on 2026-11-25.

Running the command again changes nothing: a re-pointed mapping or saved
policy no longer names the copy, and the policy and dynamic are found by
their content hashes. A kept copy is listed as kept again, and a refused
copy as refused.

### Deploy order

1. API v1's release containing C1 · 48 (and so C1 · 36 and C1 · 43) deploys
in the environment, so the v1-to-v2 copy there splits UK `gov.dynamic.`
values too and no new policy holding model assumptions is stored.
2. C1 · 49 runs the command there: the read-only listing, then `--apply`,
then the listing again. That listing lists nothing and exits with 0, or
lists only kept and refused copies and exits with 1. Each of those still
holds model assumptions as policy values, so the operator settles it by
hand first (for example by deleting the test simulations, reports or
household calculations that name it), with the user's approval.
3. Only then, once a listing lists nothing, does C1 · 50's revision run in
that environment.

### The temporary role

The command connects as `policyengine_v2_policy_copy_split`, which holds only
the grants `POLICY_COPY_SPLIT_PRIVILEGES` declares
(`policyengine_api/data/v2/privileges.py`; a test checks the statements below
match it). No deploy grants, checks or reports the role. Create it in the
environment's v2 database, as a login that may grant on the migration role's
tables, with a SCRAM-SHA-256 verifier made locally in place of the password,
so the database never receives the password itself. Each block is one
statement, so `supabase db query` takes it in one call:

```sql
DO $$
BEGIN
CREATE ROLE policyengine_v2_policy_copy_split LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS NOINHERIT PASSWORD '<SCRAM-SHA-256 verifier>';
GRANT USAGE ON SCHEMA public TO policyengine_v2_policy_copy_split;
GRANT DELETE, INSERT, SELECT, UPDATE ON TABLE public.policies TO policyengine_v2_policy_copy_split;
GRANT INSERT, SELECT ON TABLE public.dynamics TO policyengine_v2_policy_copy_split;
GRANT INSERT, SELECT ON TABLE public.parameter_values TO policyengine_v2_policy_copy_split;
GRANT INSERT, SELECT ON TABLE public.user_dynamics TO policyengine_v2_policy_copy_split;
GRANT SELECT ON TABLE public.household_jobs TO policyengine_v2_policy_copy_split;
GRANT SELECT ON TABLE public.parameters TO policyengine_v2_policy_copy_split;
GRANT SELECT ON TABLE public.reports TO policyengine_v2_policy_copy_split;
GRANT SELECT ON TABLE public.simulations TO policyengine_v2_policy_copy_split;
GRANT SELECT ON TABLE public.tax_benefit_model_versions TO policyengine_v2_policy_copy_split;
GRANT SELECT, UPDATE ON TABLE public.legacy_policy_mappings TO policyengine_v2_policy_copy_split;
GRANT SELECT, UPDATE ON TABLE public.user_policies TO policyengine_v2_policy_copy_split;
END
$$;
```

Deleting a policy needs no privilege on `parameter_values`: PostgreSQL runs a
foreign key's cascade as the table's owner. After the run, revoke each grant
and drop the role, as the login that created it. `DROP OWNED BY` would need
the role's own privileges, which a login that isn't a superuser lacks on
PostgreSQL 16 and later, so each grant is revoked by name:

```sql
DO $$
BEGIN
REVOKE ALL ON TABLE public.dynamics FROM policyengine_v2_policy_copy_split;
REVOKE ALL ON TABLE public.household_jobs FROM policyengine_v2_policy_copy_split;
REVOKE ALL ON TABLE public.legacy_policy_mappings FROM policyengine_v2_policy_copy_split;
REVOKE ALL ON TABLE public.parameter_values FROM policyengine_v2_policy_copy_split;
REVOKE ALL ON TABLE public.parameters FROM policyengine_v2_policy_copy_split;
REVOKE ALL ON TABLE public.policies FROM policyengine_v2_policy_copy_split;
REVOKE ALL ON TABLE public.reports FROM policyengine_v2_policy_copy_split;
REVOKE ALL ON TABLE public.simulations FROM policyengine_v2_policy_copy_split;
REVOKE ALL ON TABLE public.tax_benefit_model_versions FROM policyengine_v2_policy_copy_split;
REVOKE ALL ON TABLE public.user_dynamics FROM policyengine_v2_policy_copy_split;
REVOKE ALL ON TABLE public.user_policies FROM policyengine_v2_policy_copy_split;
REVOKE USAGE ON SCHEMA public FROM policyengine_v2_policy_copy_split;
DROP ROLE policyengine_v2_policy_copy_split;
END
$$;
```

### Running it

From a checkout of the deployed release, with three variables set in the
shell for the run only:

- `V2_POLICY_COPY_SPLIT_DATABASE_URL`: the temporary role's
`postgresql+psycopg://` URL with `sslmode=require` (or `verify-ca` or
`verify-full`), on the project's direct host or its pooler in session
mode on port 5432. Transaction mode (port 6543) is refused, because it
doesn't keep the command's timeouts;
- `V2_SUPABASE_PROJECT_REF` and `V2_SUPABASE_ENVIRONMENT`: the values of the
GitHub Actions environment variables of the same names, which the command
checks the URL against.

```bash
uv run --frozen python scripts/split_v2_policy_copies.py
uv run --frozen python scripts/split_v2_policy_copies.py --apply
```

Without `--apply`, every transaction is `READ ONLY`, and the command lists
for each copy the policy and dynamic it would point at (by ID when stored,
otherwise by content hash), each legacy mapping (country and v1 policy ID,
with the dynamic it named before) and saved policy it would re-point, each
saved dynamic it would add or reuse, and whether the copy would be deleted,
kept (with how many simulations, reports and household calculations name it)
or refused (with the reason). With `--apply` it reports the same with the IDs
of the rows it points at or creates, as each copy's transaction commits. It
prints no URL, saved-policy name or user ID.

The listing reports a row that an earlier copy in the same run would create
as reused, since `--apply` commits each copy before the next.

It exits with 0 when no stored policy sets a model assumption afterwards (for
the listing: when every listed copy would be deleted), and with 1 otherwise.
Missing settings, a failed connection, or a copy that still can't get its
locks after five attempts raise, and also exit with 1; the copies already
reported have committed, and running the command again carries on. The
command adds a 10-second connection timeout, a half-second lock timeout and
a 60-second statement timeout to the URL.
3 changes: 2 additions & 1 deletion policyengine_api/data/v2/models/policies.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,8 @@ class Dynamic(TimestampedModel, table=True):

A dynamic holds parameter values a simulation applies alongside its
policy: every parameter under ``gov.simulation.``, plus the US's
top-level ``simulation.`` (``policyengine_api.dynamic_parameters``). It
top-level ``simulation.`` and the UK's ``gov.dynamic.``
(``policyengine_api.dynamic_parameters``). It
is stored and hashed as a policy is, bound to one catalog version, with
no name or description: a user's saved dynamics (``user_dynamics``) name
it. Its parameter values are deleted with it; dynamics that users have
Expand Down
28 changes: 28 additions & 0 deletions policyengine_api/data/v2/privileges.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,13 @@
The migration role (``policyengine_v2_migrator``) owns every table, and
Supabase's ``postgres`` role administers the project; neither is managed here.

``POLICY_COPY_SPLIT_PRIVILEGES`` declares what the policy copy split command
(``scripts/split_v2_policy_copies.py``) needs, for the temporary role
``policyengine_v2_policy_copy_split`` that an operator creates for one run
(C1 · 49) and drops afterwards. No deploy grants, checks or reports it: it is
not one of the managed roles, and ``docs/migration/stage-10-v2-policies.md``
gives the statements that create and drop it.

Extra privileges a database holds beyond this manifest are reported, not
revoked, with one exception: a privilege a role holds on a whole table that
this manifest declares for named columns only is revoked, with the role's
Expand Down Expand Up @@ -234,6 +241,27 @@ def _run_table(
)


# The policy copy split's temporary role (see the module docstring). It locks
# and deletes the old copies (their values go with them by the foreign key's
# cascade), re-points legacy mappings and saved policies, inserts policies,
# dynamics, their values and saved dynamics, and reads the catalog and the
# rows that may name a copy.
POLICY_COPY_SPLIT_ROLE: Final = "policyengine_v2_policy_copy_split"
_READ_UPDATE: Final = frozenset({TablePrivilege.SELECT, TablePrivilege.UPDATE})
POLICY_COPY_SPLIT_PRIVILEGES: Final[dict[str, frozenset[DeclaredPrivilege]]] = {
"dynamics": READ_INSERT,
"household_jobs": READ,
"legacy_policy_mappings": _READ_UPDATE,
"parameter_values": READ_INSERT,
"parameters": READ,
"policies": READ_WRITE,
"reports": READ,
"simulations": READ,
"tax_benefit_model_versions": READ,
"user_dynamics": READ_INSERT,
"user_policies": _READ_UPDATE,
}

# The Modal workers write results, keyed by run, once each.
_RESULT = _access(runtime=READ, modal_worker=READ_INSERT)
# What a run needs from the Public API's policies, dynamics, households and
Expand Down
28 changes: 28 additions & 0 deletions policyengine_api/data/v2/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
V2_RUNTIME_DATABASE_URL_SECRET_RESOURCE = "V2_RUNTIME_DATABASE_URL_SECRET_RESOURCE" # noqa: S105 # an environment variable name, not a secret
V2_MIGRATION_DATABASE_URL = "V2_MIGRATION_DATABASE_URL"
V2_DATA_WRITE_DATABASE_URL = "V2_DATA_WRITE_DATABASE_URL"
# The temporary role C1 · 49 creates to run scripts/split_v2_policy_copies.py.
V2_POLICY_COPY_SPLIT_DATABASE_URL = "V2_POLICY_COPY_SPLIT_DATABASE_URL"
V2_SUPABASE_PROJECT_REF = "V2_SUPABASE_PROJECT_REF"
V2_SUPABASE_ENVIRONMENT = "V2_SUPABASE_ENVIRONMENT"

Expand Down Expand Up @@ -267,6 +269,32 @@ def load_v2_migration_database_settings(
)


def load_v2_policy_copy_split_database_settings(
environ: Mapping[str, str] | None = None,
) -> V2DatabaseSettings:
"""Load the policy copy split command's temporary Postgres identity explicitly.

The operator creates the role for the run with the grants
``privileges.POLICY_COPY_SPLIT_PRIVILEGES`` declares, and drops it after.
Supavisor's transaction-mode port is refused, as for the runtime: it
doesn't keep the command's lock and statement timeouts.
"""
values = _environment(environ)
settings = _database_settings(
_required(values, V2_POLICY_COPY_SPLIT_DATABASE_URL),
setting_name=V2_POLICY_COPY_SPLIT_DATABASE_URL,
environ=values,
)
if settings.connection.url.port == SUPABASE_TRANSACTION_POOLER_PORT:
msg = (
f"{V2_POLICY_COPY_SPLIT_DATABASE_URL} must use a direct connection or "
"Supavisor session mode on port 5432 so the command's lock and "
"statement timeouts are applied"
)
raise V2ConfigurationError(msg)
return settings


def load_v2_data_write_database_settings(
environ: Mapping[str, str] | None = None,
) -> V2DatabaseSettings:
Expand Down
Loading
Loading