From a2fc294294e4788b85881823546b155681c81976 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:00:08 +0400 Subject: [PATCH 01/10] =?UTF-8?q?Remove=20the=20policy=20copy=20split=20co?= =?UTF-8?q?mmand,=20which=20has=20nothing=20to=20split=20after=20C1=20?= =?UTF-8?q?=C2=B7=2050?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit C1 · 48's scripts/split_v2_policy_copies.py split each stored v2 policy that held model assumptions into a policy and a dynamic, and C1 · 49 runs it in staging and production before C1 · 50's revision. That revision moves dynamic parameters into their own tables and refuses to run while any policy value names one, so afterwards no stored policy can hold a model assumption, and the command's dynamics could no longer be stored either. The user decided on 2026-11-25 that C1 · 50 removes it. Removed: the policy_copy_split package, the script, its temporary role's privileges, V2_POLICY_COPY_SPLIT_DATABASE_URL and its loader, its import rules, its integration workflow entry and its tests. The stage-10 runbook keeps a short account of what the command did. The UK gov.dynamic. prefix and C1 · 48's other changes stay. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/v2-integration-check.yml | 4 +- docs/migration/stage-10-v2-policies.md | 187 +-- policyengine_api/data/v2/privileges.py | 28 - policyengine_api/data/v2/settings.py | 28 - policyengine_api/dynamic_parameters.py | 5 +- .../services/v2/policy_copy_split/__init__.py | 1 - .../database_connectors/__init__.py | 1 - .../database_connectors/deletes.py | 25 - .../database_connectors/reads.py | 176 --- .../database_connectors/updates.py | 38 - .../v2/policy_copy_split/database_session.py | 36 - .../services/v2/policy_copy_split/services.py | 713 --------- .../v2/policy_copy_split/transformations.py | 64 - .../services/v2/policy_copy_split/types.py | 207 --- .../v2/policy_copy_split/validators.py | 125 -- pyproject.toml | 2 - scripts/split_v2_policy_copies.py | 297 ---- .../integration/test_v2_policy_copy_splits.py | 1375 ----------------- .../test_split_v2_policy_copies_script.py | 363 ----- tests/unit/test_v2_integration_workflow.py | 10 - .../unit/v2/test_policy_copy_split_retries.py | 116 -- tests/unit/v2/test_policy_copy_split_rules.py | 314 ---- .../unit/v2/test_policy_copy_split_runbook.py | 92 -- tests/unit/v2/test_privilege_manifest.py | 83 - tests/unit/v2/test_settings.py | 42 - 25 files changed, 19 insertions(+), 4313 deletions(-) delete mode 100644 policyengine_api/services/v2/policy_copy_split/__init__.py delete mode 100644 policyengine_api/services/v2/policy_copy_split/database_connectors/__init__.py delete mode 100644 policyengine_api/services/v2/policy_copy_split/database_connectors/deletes.py delete mode 100644 policyengine_api/services/v2/policy_copy_split/database_connectors/reads.py delete mode 100644 policyengine_api/services/v2/policy_copy_split/database_connectors/updates.py delete mode 100644 policyengine_api/services/v2/policy_copy_split/database_session.py delete mode 100644 policyengine_api/services/v2/policy_copy_split/services.py delete mode 100644 policyengine_api/services/v2/policy_copy_split/transformations.py delete mode 100644 policyengine_api/services/v2/policy_copy_split/types.py delete mode 100644 policyengine_api/services/v2/policy_copy_split/validators.py delete mode 100755 scripts/split_v2_policy_copies.py delete mode 100644 tests/integration/test_v2_policy_copy_splits.py delete mode 100644 tests/unit/test_split_v2_policy_copies_script.py delete mode 100644 tests/unit/v2/test_policy_copy_split_retries.py delete mode 100644 tests/unit/v2/test_policy_copy_split_rules.py delete mode 100644 tests/unit/v2/test_policy_copy_split_runbook.py diff --git a/.github/workflows/v2-integration-check.yml b/.github/workflows/v2-integration-check.yml index d21e6836e..7ddd676db 100644 --- a/.github/workflows/v2-integration-check.yml +++ b/.github/workflows/v2-integration-check.yml @@ -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, 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 v2 policy and dynamic persistence and immediate v1 mirroring + run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_policy_persistence.py tests/integration/test_v2_dynamic_persistence.py tests/integration/test_v1_policy_dual_write.py tests/integration/test_mysql_policy_dual_write.py tests/integration/test_v2_user_policy_mirroring.py tests/integration/test_v1_user_policy_dual_write.py - name: Test signed-in identity provisioning, user associations, saved detailed-save records and user types run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_user_identity_persistence.py tests/integration/test_v2_user_type_persistence.py tests/integration/test_v2_saved_detailed_save_records.py tests/integration/test_v2_saved_budget_window_reports.py - name: Test 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 diff --git a/docs/migration/stage-10-v2-policies.md b/docs/migration/stage-10-v2-policies.md index 0cacf86e8..a2731566a 100644 --- a/docs/migration/stage-10-v2-policies.md +++ b/docs/migration/stage-10-v2-policies.md @@ -291,174 +291,19 @@ 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 ''; - 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. +## Splitting stored policies that held model assumptions + +Until C1 · 36, the v1-to-v2 copy kept a v1 policy's model assumptions in its +v2 policy, and UK `gov.dynamic.` values until C1 · 48. A one-time command +added by C1 · 48, `scripts/split_v2_policy_copies.py`, split every such +stored policy into a policy and a dynamic on its own catalog version, +re-pointed its legacy mappings and saved policies, gave each saved policy's +owner a saved dynamic with its name, and deleted the old copy once nothing +named it. The operator step C1 · 49 ran it in staging and production, as a +temporary database role, before C1 · 50's revision. + +C1 · 50 removed the command. Its revision moves dynamic parameters into +`dynamic_parameters` and refuses to run while any policy value names one, so +afterwards no stored policy can hold a model assumption and the command has +nothing to split. The command is in the repository's history at C1 · 48's +merge. diff --git a/policyengine_api/data/v2/privileges.py b/policyengine_api/data/v2/privileges.py index 64afb4619..2a8d00208 100644 --- a/policyengine_api/data/v2/privileges.py +++ b/policyengine_api/data/v2/privileges.py @@ -60,13 +60,6 @@ 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 @@ -241,27 +234,6 @@ 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 diff --git a/policyengine_api/data/v2/settings.py b/policyengine_api/data/v2/settings.py index 0d978a8c1..33d8fdfea 100644 --- a/policyengine_api/data/v2/settings.py +++ b/policyengine_api/data/v2/settings.py @@ -23,8 +23,6 @@ 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" @@ -269,32 +267,6 @@ 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: diff --git a/policyengine_api/dynamic_parameters.py b/policyengine_api/dynamic_parameters.py index d25611307..76d30c8e4 100644 --- a/policyengine_api/dynamic_parameters.py +++ b/policyengine_api/dynamic_parameters.py @@ -16,10 +16,7 @@ - The copy of each v1 policy into v2 splits the v1 policy's values with ``split_legacy_policy_json``: these values become a dynamic and the rest the policy. -- The one-time migration splits v1 policies with the same functions, and - the policy copy split command - (``policyengine_api.services.v2.policy_copy_split``) splits the v2 copies - stored before a prefix applied to them. +- The one-time migration splits v1 policies with the same functions. The UK renamed ``gov.simulation.labor_supply_responses`` to ``gov.simulation.labour_supply_responses`` on 2026-05-01. Its catalog has diff --git a/policyengine_api/services/v2/policy_copy_split/__init__.py b/policyengine_api/services/v2/policy_copy_split/__init__.py deleted file mode 100644 index 963318fea..000000000 --- a/policyengine_api/services/v2/policy_copy_split/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Split stored policies that set model assumptions into a policy and a dynamic.""" diff --git a/policyengine_api/services/v2/policy_copy_split/database_connectors/__init__.py b/policyengine_api/services/v2/policy_copy_split/database_connectors/__init__.py deleted file mode 100644 index 45d734f58..000000000 --- a/policyengine_api/services/v2/policy_copy_split/database_connectors/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Database statements of the policy copy split.""" diff --git a/policyengine_api/services/v2/policy_copy_split/database_connectors/deletes.py b/policyengine_api/services/v2/policy_copy_split/database_connectors/deletes.py deleted file mode 100644 index 9592d0647..000000000 --- a/policyengine_api/services/v2/policy_copy_split/database_connectors/deletes.py +++ /dev/null @@ -1,25 +0,0 @@ -"""Database deletes used by the policy copy split.""" - -from __future__ import annotations - -from typing import TYPE_CHECKING - -from sqlalchemy import delete -from sqlmodel import col - -from policyengine_api.data.v2.models import Policy - -if TYPE_CHECKING: - from uuid import UUID - - from sqlmodel import Session - - -def delete_policy(session: Session, policy_id: UUID) -> None: - """Delete a policy that nothing names; its values go with it. - - ``parameter_values.policy_id`` cascades, and every other foreign key to - ``policies`` either refuses the delete or sets its column to null, so the - service checks first that nothing else names it. - """ - session.execute(delete(Policy).where(col(Policy.id) == policy_id)) diff --git a/policyengine_api/services/v2/policy_copy_split/database_connectors/reads.py b/policyengine_api/services/v2/policy_copy_split/database_connectors/reads.py deleted file mode 100644 index 1747db0a1..000000000 --- a/policyengine_api/services/v2/policy_copy_split/database_connectors/reads.py +++ /dev/null @@ -1,176 +0,0 @@ -"""Database selections used by the policy copy split.""" - -from __future__ import annotations - -from typing import TYPE_CHECKING - -from sqlalchemy import and_, func, or_ -from sqlmodel import Session, col, select - -from policyengine_api.data.v2.models import ( - HouseholdJob, - LegacyPolicyMapping, - Parameter, - ParameterValue, - Policy, - Report, - Simulation, - UserDynamic, - UserPolicy, -) -from policyengine_api.services.v2.policy_copy_split.types import CopyReferences - -if TYPE_CHECKING: - from collections.abc import Mapping - from uuid import UUID - - from policyengine_api.supported_countries import SupportedCountryId - - -def read_policy_ids_setting_parameters( - session: Session, prefixes_by_country: Mapping[SupportedCountryId, tuple[str, ...]] -) -> list[UUID]: - """Return the stored policies that set a parameter under their country's prefixes. - - Oldest first. Only a policy's own values count, not current law's or a - dynamic's. - """ - sets_prefixed_parameter = or_( - *( - and_( - col(Policy.country_id) == country_id, - or_( - *( - col(Parameter.name).startswith(prefix, autoescape=True) - for prefix in prefixes - ) - ), - ) - for country_id, prefixes in prefixes_by_country.items() - ) - ) - policy_sets_prefixed_parameter = ( - select(ParameterValue.id) - .join(Parameter, col(Parameter.id) == col(ParameterValue.parameter_id)) - .where(col(ParameterValue.policy_id) == col(Policy.id), sets_prefixed_parameter) - .exists() - ) - return list( - session.exec( - select(Policy.id) - .where(policy_sets_prefixed_parameter) - .order_by(col(Policy.created_at), col(Policy.id)) - ).all() - ) - - -def read_policy_for_split( - session: Session, policy_id: UUID, *, lock: bool -) -> Policy | None: - """Return the stored policy, or None. - - With ``lock``, the row is selected FOR UPDATE, so until the transaction - ends no other transaction can add a row that names it (a foreign key's - check locks the row it names) or delete it. - """ - statement = select(Policy).where(Policy.id == policy_id) - if lock: - statement = statement.with_for_update() - return session.exec(statement).one_or_none() - - -def read_mappings_naming_policy( - session: Session, policy_id: UUID, *, lock: bool -) -> list[LegacyPolicyMapping]: - """Return the legacy policy mappings that name the policy, by v1 policy ID. - - With ``lock``, they are selected FOR UPDATE, as the v1-to-v2 copy selects - a mapping it reads. - """ - statement = ( - select(LegacyPolicyMapping) - .where(LegacyPolicyMapping.policy_id == policy_id) - .order_by( - col(LegacyPolicyMapping.country_id), - col(LegacyPolicyMapping.legacy_policy_id), - ) - ) - if lock: - statement = statement.with_for_update() - return list(session.exec(statement).all()) - - -def read_saved_policies_naming_policy( - session: Session, policy_id: UUID, *, lock: bool -) -> list[UserPolicy]: - """Return the saved policies that name the policy, oldest first. - - With ``lock``, they are selected FOR UPDATE. - """ - statement = ( - select(UserPolicy) - .where(UserPolicy.policy_id == policy_id) - .order_by(col(UserPolicy.created_at), col(UserPolicy.id)) - ) - if lock: - statement = statement.with_for_update() - return list(session.exec(statement).all()) - - -def read_saved_policy_for_update( - session: Session, saved_policy_id: UUID -) -> UserPolicy | None: - """Return the saved policy, selected FOR UPDATE, or None if it was deleted.""" - return session.exec( - select(UserPolicy).where(UserPolicy.id == saved_policy_id).with_for_update() - ).one_or_none() - - -def count_rows_naming_policy(session: Session, policy_id: UUID) -> CopyReferences: - """Return how many simulations, reports and household jobs name the policy.""" - simulations = session.exec( - select(func.count()) - .select_from(Simulation) - .where(col(Simulation.policy_id) == policy_id) - ).one() - reports = session.exec( - select(func.count()) - .select_from(Report) - .where(col(Report.policy_id) == policy_id) - ).one() - household_jobs = session.exec( - select(func.count()) - .select_from(HouseholdJob) - .where(col(HouseholdJob.policy_id) == policy_id) - ).one() - return CopyReferences( - simulations=simulations, reports=reports, household_jobs=household_jobs - ) - - -def read_saved_dynamic_with_name( - session: Session, - *, - user_id: UUID, - country_id: str, - dynamic_id: UUID, - name: str | None, -) -> UserDynamic | None: - """Return the user's oldest saved dynamic of this dynamic with this name, or None. - - A null name matches only a null name. - """ - name_matches = ( - col(UserDynamic.name).is_(None) if name is None else UserDynamic.name == name - ) - return session.exec( - select(UserDynamic) - .where( - UserDynamic.user_id == user_id, - UserDynamic.country_id == country_id, - UserDynamic.dynamic_id == dynamic_id, - name_matches, - ) - .order_by(col(UserDynamic.created_at), col(UserDynamic.id)) - .limit(1) - ).first() diff --git a/policyengine_api/services/v2/policy_copy_split/database_connectors/updates.py b/policyengine_api/services/v2/policy_copy_split/database_connectors/updates.py deleted file mode 100644 index a20b29b44..000000000 --- a/policyengine_api/services/v2/policy_copy_split/database_connectors/updates.py +++ /dev/null @@ -1,38 +0,0 @@ -"""Database updates used by the policy copy split.""" - -from __future__ import annotations - -from typing import TYPE_CHECKING - -from sqlalchemy import update -from sqlmodel import col - -from policyengine_api.data.v2.models import LegacyPolicyMapping, UserPolicy -from policyengine_api.data.v2.models.base import utc_now - -if TYPE_CHECKING: - from uuid import UUID - - from sqlmodel import Session - - -def repoint_legacy_policy_mapping( - session: Session, mapping_id: UUID, *, policy_id: UUID, dynamic_id: UUID -) -> None: - """Point a legacy policy mapping at a policy and a dynamic.""" - session.execute( - update(LegacyPolicyMapping) - .where(col(LegacyPolicyMapping.id) == mapping_id) - .values(policy_id=policy_id, dynamic_id=dynamic_id, updated_at=utc_now()) - ) - - -def repoint_saved_policy( - session: Session, saved_policy_id: UUID, *, policy_id: UUID -) -> None: - """Point a saved policy at another policy; its name and description stay.""" - session.execute( - update(UserPolicy) - .where(col(UserPolicy.id) == saved_policy_id) - .values(policy_id=policy_id, updated_at=utc_now()) - ) diff --git a/policyengine_api/services/v2/policy_copy_split/database_session.py b/policyengine_api/services/v2/policy_copy_split/database_session.py deleted file mode 100644 index 38ca3b696..000000000 --- a/policyengine_api/services/v2/policy_copy_split/database_session.py +++ /dev/null @@ -1,36 +0,0 @@ -"""Database session lifetime management for the policy copy split.""" - -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 sessionmaker - from sqlmodel import Session - - -class PolicyCopySplitDatabaseSession: - """Open read sessions and transaction-scoped sessions for the split. - - The command builds it on read-only Session factories for its listing, so - the database itself refuses any write there. - """ - - def __init__(self, session_factory: sessionmaker[Session]) -> None: - """Use ``session_factory`` to open every session.""" - self._session_factory = session_factory - - @contextmanager - def read(self) -> Iterator[Session]: - """Yield a session for reads; nothing is committed.""" - with self._session_factory() as session: - yield session - - @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 diff --git a/policyengine_api/services/v2/policy_copy_split/services.py b/policyengine_api/services/v2/policy_copy_split/services.py deleted file mode 100644 index 8e6a9c1cd..000000000 --- a/policyengine_api/services/v2/policy_copy_split/services.py +++ /dev/null @@ -1,713 +0,0 @@ -"""Split stored policies that set model assumptions into a policy and a dynamic. - -The v1-to-v2 copy kept a v1 policy's model assumptions in its v2 policy until -C1 · 36, and UK ``gov.dynamic.`` values until C1 · 48, and a v1 policy is -never copied again. For each stored policy that sets a model assumption -(``policyengine_api.dynamic_parameters``), the split: - -- finds or creates the policy without the assumptions (empty when the copy - set nothing else) and the dynamic holding them, on the copy's own catalog - version, through C1 · 36's ``create_resolved_policy`` and - ``create_resolved_dynamic``; -- points each legacy mapping that names the copy at them. A mapping that - already names a dynamic gets one dynamic holding that dynamic's values and - the copy's assumptions together; -- points each saved policy that names the copy at the policy, and gives its - owner a saved dynamic with the saved policy's name and no description, - naming the dynamic its v1 policy's mapping now names (or the copy's own - dynamic), unless the owner already has an identical one; -- deletes the copy, its values with it, once nothing names it. A copy that a - simulation, report or household calculation names is kept: their keys - hash the policy, and deleting it would set their policy to null. - -A copy whose mapping's dynamic can't take its assumptions is refused, and -nothing changes for it. ``scripts/split_v2_policy_copies.py`` runs this as a -temporary role (C1 · 49), and D4 · 1's migration reuses -``split_policy_copy_in_session``. The user's decisions are recorded in -``docs/migration/stage-10-v2-policies.md``. -""" - -from __future__ import annotations - -import time -from dataclasses import replace -from typing import TYPE_CHECKING, Protocol - -from sqlalchemy.exc import OperationalError - -from policyengine_api.dynamic_parameters import DYNAMIC_PARAMETER_PREFIXES -from policyengine_api.services.v2.dynamics.database_connectors.reads import ( - read_dynamic_by_content_identity, - read_dynamic_parameter_values, - read_dynamic_row, -) -from policyengine_api.services.v2.policies.database_connectors.reads import ( - read_model_version, - read_parameter_values_with_names, - read_policy_by_content_identity, -) -from policyengine_api.services.v2.policies.transformations import ( - canonicalize_policy, - stored_policy_creation_input, -) -from policyengine_api.services.v2.policy_copy_split.database_connectors.deletes import ( - delete_policy, -) -from policyengine_api.services.v2.policy_copy_split.database_connectors.reads import ( - count_rows_naming_policy, - read_mappings_naming_policy, - read_policy_for_split, - read_policy_ids_setting_parameters, - read_saved_dynamic_with_name, - read_saved_policies_naming_policy, - read_saved_policy_for_update, -) -from policyengine_api.services.v2.policy_copy_split.database_connectors.updates import ( - repoint_legacy_policy_mapping, - repoint_saved_policy, -) -from policyengine_api.services.v2.policy_copy_split.transformations import ( - split_stored_policy, -) -from policyengine_api.services.v2.policy_copy_split.types import ( - ListedRows, - MappingTarget, - PolicyCopyOutcome, - PolicyCopySplit, - PreparedPolicyCopySplit, - RepointedMapping, - RepointedSavedPolicy, - SavedDynamicIdentity, - SavedPolicyTarget, - SplitContent, -) -from policyengine_api.services.v2.policy_copy_split.validators import ( - PolicyCopySplitRefusedError, - is_lock_conflict, - merge_dynamic_content, - require_stored_row, -) -from policyengine_api.services.v2.user_dynamics.types import UserDynamicCreationInput - -if TYPE_CHECKING: - from collections.abc import Callable, Iterator - from uuid import UUID - - from sqlmodel import Session - - from policyengine_api.data.v2.models import Dynamic, LegacyPolicyMapping, Policy - from policyengine_api.services.v2.dynamics.types import ( - ResolvedDynamicCreationInput, - ) - from policyengine_api.services.v2.policies.types import ( - ResolvedPolicyCreationInput, - ) - from policyengine_api.services.v2.policy_copy_split.database_session import ( - PolicyCopySplitDatabaseSession, - ) - from policyengine_api.services.v2.policy_copy_split.types import ( - StoredPolicySplit, - ) - - -def read_policy_copy_ids(session: Session) -> tuple[UUID, ...]: - """Return every stored policy that sets a model assumption, oldest first.""" - return tuple( - read_policy_ids_setting_parameters(session, DYNAMIC_PARAMETER_PREFIXES) - ) - - -def _mapping_dynamic( - session: Session, mapping: LegacyPolicyMapping, split: StoredPolicySplit -) -> ResolvedDynamicCreationInput: - """Return the dynamic the mapping will name: the copy's, or merged with its own. - - Raise PolicyCopySplitRefusedError when the mapping's dynamic can't take - the copy's assumptions. - """ - if mapping.dynamic_id is None: - return split.dynamic - existing = require_stored_row( - read_dynamic_row( - session, country_id=mapping.country_id, dynamic_id=mapping.dynamic_id - ), - f"dynamic {mapping.dynamic_id} of legacy policy {mapping.legacy_policy_id}", - ) - model_version = require_stored_row( - read_model_version(session, existing.tax_benefit_model_version_id), - f"model version of dynamic {existing.id}", - ) - return merge_dynamic_content( - stored_policy_creation_input( - existing, model_version, read_dynamic_parameter_values(session, existing.id) - ), - split.dynamic, - ) - - -def _prepare( - session: Session, policy_id: UUID, *, lock: bool -) -> PreparedPolicyCopySplit | None: - """Read what the split of one copy needs, locking the copy with ``lock``. - - The locks are taken in the order API v1's copies take them, so the split - waits for a copy instead of deadlocking with it: the copy of a v1 saved - policy locks the legacy mapping, then saves a policy naming the mapped - copy, whose foreign-key check locks the copy's row. So the mappings - naming the copy are locked before the copy, and read again once it is - locked, since one committed meanwhile can name it and none can be added - after. The saved policies naming it are read, not locked: each is locked - only just before its owner's saved dynamic is saved - (``_StoredSplitRows.current_saved_policy``). Return None when the policy - is no longer stored or sets no model assumption. - """ - if lock: - read_mappings_naming_policy(session, policy_id, lock=True) - policy = read_policy_for_split(session, policy_id, lock=lock) - if policy is None: - return None - model_version = require_stored_row( - read_model_version(session, policy.tax_benefit_model_version_id), - f"model version of policy {policy.id}", - ) - split = split_stored_policy( - policy, model_version, read_parameter_values_with_names(session, [policy.id]) - ) - if split is None: - return None - prepared = PreparedPolicyCopySplit( - policy_id=policy.id, - country_id=policy.country_id, - policyengine_version=model_version.version, - split=split, - mapping_targets=(), - saved_policy_targets=(), - references=count_rows_naming_policy(session, policy.id), - refusal_reason=None, - ) - mappings = read_mappings_naming_policy(session, policy.id, lock=lock) - try: - mapping_targets = tuple( - MappingTarget( - mapping_id=mapping.id, - country_id=mapping.country_id, - legacy_policy_id=mapping.legacy_policy_id, - previous_dynamic_id=mapping.dynamic_id, - dynamic=_mapping_dynamic(session, mapping, split), - ) - for mapping in mappings - ) - except PolicyCopySplitRefusedError as refusal: - return replace(prepared, refusal_reason=refusal.reason) - dynamics_by_legacy_policy = { - (target.country_id, target.legacy_policy_id): target.dynamic - for target in mapping_targets - } - saved_policy_targets = tuple( - SavedPolicyTarget( - user_policy_id=saved_policy.id, - user_id=saved_policy.user_id, - country_id=saved_policy.country_id, - name=saved_policy.name, - dynamic=( - split.dynamic - if saved_policy.legacy_policy_id is None - else dynamics_by_legacy_policy.get( - (saved_policy.country_id, saved_policy.legacy_policy_id), - split.dynamic, - ) - ), - ) - for saved_policy in read_saved_policies_naming_policy( - session, policy.id, lock=False - ) - ) - return replace( - prepared, - mapping_targets=mapping_targets, - saved_policy_targets=saved_policy_targets, - ) - - -def _content_hash(content: ResolvedPolicyCreationInput) -> str: - return canonicalize_policy(content).content_hash - - -def _refused(prepared: PreparedPolicyCopySplit, *, applied: bool) -> PolicyCopySplit: - return PolicyCopySplit( - old_policy_id=prepared.policy_id, - country_id=prepared.country_id, - policyengine_version=prepared.policyengine_version, - applied=applied, - outcome=PolicyCopyOutcome.REFUSED, - policy=None, - dynamic=None, - mappings=(), - saved_policies=(), - references=prepared.references, - refusal_reason=prepared.refusal_reason, - ) - - -def _remaining_outcome(prepared: PreparedPolicyCopySplit) -> PolicyCopyOutcome: - """Return deleted, unless a simulation, report or household job names the copy.""" - if prepared.references.total: - return PolicyCopyOutcome.KEPT - return PolicyCopyOutcome.DELETED - - -class _SplitRows(Protocol): - """Where one copy's split finds or puts its rows: in a listing, or for real.""" - - def policy(self, content: ResolvedPolicyCreationInput) -> SplitContent: - """Find, or create or report as new, the policy with this content.""" - ... - - def dynamic(self, content: ResolvedDynamicCreationInput) -> SplitContent: - """Find, or create or report as new, the dynamic with this content.""" - ... - - def repoint_mapping( - self, target: MappingTarget, *, policy: SplitContent, dynamic: SplitContent - ) -> None: - """Point the mapping at the policy and dynamic.""" - ... - - def current_saved_policy( - self, target: SavedPolicyTarget - ) -> SavedPolicyTarget | None: - """Return the saved policy as it is now, or None if it no longer names the copy. - - A run locks it here, so its owner and name are current. - """ - ... - - def repoint_saved_policy( - self, target: SavedPolicyTarget, *, policy: SplitContent - ) -> None: - """Point the saved policy at the policy.""" - ... - - def saved_dynamic( - self, target: SavedPolicyTarget, *, dynamic: SplitContent - ) -> tuple[UUID | None, bool]: - """Give the saved policy's owner a saved dynamic naming the dynamic. - - Return the saved dynamic's ID (None when a listing would create it) - and whether it is new. - """ - ... - - def delete_copy(self, policy_id: UUID) -> None: - """Delete the copy, which nothing names any more.""" - ... - - -def _split_prepared( - prepared: PreparedPolicyCopySplit, rows: _SplitRows, *, applied: bool -) -> PolicyCopySplit: - """Carry out one copy's split through ``rows``, and say what it did. - - A listing and a run both go through here, so they report the same steps. - """ - policy = rows.policy(prepared.split.policy) - plain_dynamic = rows.dynamic(prepared.split.dynamic) - mappings = [] - for mapping_target in prepared.mapping_targets: - dynamic = rows.dynamic(mapping_target.dynamic) - rows.repoint_mapping(mapping_target, policy=policy, dynamic=dynamic) - mappings.append( - RepointedMapping( - country_id=mapping_target.country_id, - legacy_policy_id=mapping_target.legacy_policy_id, - previous_dynamic_id=mapping_target.previous_dynamic_id, - dynamic=dynamic, - ) - ) - saved_policies = [] - for prepared_target in prepared.saved_policy_targets: - dynamic = rows.dynamic(prepared_target.dynamic) - # Lock the saved policy only now, just before saving its owner's - # dynamic, whose foreign-key check waits for any lock on the owner's - # user: the two waits then come within a few statements of each - # other, so 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) the - # split's half-second lock timeout always ends its wait first. - saved_policy_target = rows.current_saved_policy(prepared_target) - if saved_policy_target is None: - continue - saved_dynamic_id, saved_dynamic_created = rows.saved_dynamic( - saved_policy_target, dynamic=dynamic - ) - rows.repoint_saved_policy(saved_policy_target, policy=policy) - saved_policies.append( - RepointedSavedPolicy( - user_policy_id=saved_policy_target.user_policy_id, - dynamic=dynamic, - saved_dynamic_id=saved_dynamic_id, - saved_dynamic_created=saved_dynamic_created, - ) - ) - outcome = _remaining_outcome(prepared) - if outcome is PolicyCopyOutcome.DELETED: - rows.delete_copy(prepared.policy_id) - return PolicyCopySplit( - old_policy_id=prepared.policy_id, - country_id=prepared.country_id, - policyengine_version=prepared.policyengine_version, - applied=applied, - outcome=outcome, - policy=policy, - dynamic=plain_dynamic, - mappings=tuple(mappings), - saved_policies=tuple(saved_policies), - references=prepared.references, - refusal_reason=None, - ) - - -class _StoredRowReader(Protocol): - def __call__( - self, session: Session, *, canonicalization_version: int, content_hash: str - ) -> Policy | Dynamic | None: ... - - -class _ListedSplitRows: - """Report the rows one copy's split would find or create, changing nothing. - - ``listed`` carries what earlier copies in the listing reported: a run - commits each copy before the next, so a later copy finds a row an - earlier one created, and is reported so. Within one copy, a row is - reported the same way each time, as a run reports it. - """ - - def __init__(self, session: Session, listed: ListedRows) -> None: - """Read through ``session``, adding to ``listed``.""" - self._session = session - self._listed = listed - self._copy_policies: dict[str, SplitContent] = {} - self._copy_dynamics: dict[str, SplitContent] = {} - - def _row( - self, - content: ResolvedPolicyCreationInput, - *, - copy_rows: dict[str, SplitContent], - run_rows: dict[str, SplitContent], - read_stored: _StoredRowReader, - ) -> SplitContent: - canonical = canonicalize_policy(content) - if canonical.content_hash in copy_rows: - return copy_rows[canonical.content_hash] - earlier = run_rows.get(canonical.content_hash) - if earlier is not None: - row = SplitContent( - id=earlier.id, content_hash=canonical.content_hash, created=False - ) - else: - stored = read_stored( - self._session, - canonicalization_version=canonical.version, - content_hash=canonical.content_hash, - ) - row = SplitContent( - id=None if stored is None else stored.id, - content_hash=canonical.content_hash, - created=stored is None, - ) - run_rows[canonical.content_hash] = row - copy_rows[canonical.content_hash] = row - return row - - def policy(self, content: ResolvedPolicyCreationInput) -> SplitContent: - """Report the policy as stored, or as one this run would create.""" - return self._row( - content, - copy_rows=self._copy_policies, - run_rows=self._listed.policies, - read_stored=read_policy_by_content_identity, - ) - - def dynamic(self, content: ResolvedDynamicCreationInput) -> SplitContent: - """Report the dynamic as stored, or as one this run would create.""" - return self._row( - content, - copy_rows=self._copy_dynamics, - run_rows=self._listed.dynamics, - read_stored=read_dynamic_by_content_identity, - ) - - def repoint_mapping( - self, target: MappingTarget, *, policy: SplitContent, dynamic: SplitContent - ) -> None: - """Change nothing: a listing only reports the mapping.""" - - def current_saved_policy( - self, target: SavedPolicyTarget - ) -> SavedPolicyTarget | None: - """Return the saved policy as the listing read it.""" - return target - - def repoint_saved_policy( - self, target: SavedPolicyTarget, *, policy: SplitContent - ) -> None: - """Change nothing: a listing only reports the saved policy.""" - - def saved_dynamic( - self, target: SavedPolicyTarget, *, dynamic: SplitContent - ) -> tuple[UUID | None, bool]: - """Report the owner's identical saved dynamic, or one this run would add.""" - existing = ( - None - if dynamic.id is None - else read_saved_dynamic_with_name( - self._session, - user_id=target.user_id, - country_id=target.country_id, - dynamic_id=dynamic.id, - name=target.name, - ) - ) - identity = SavedDynamicIdentity( - user_id=target.user_id, - country_id=target.country_id, - dynamic_content_hash=dynamic.content_hash, - name=target.name, - ) - created = existing is None and identity not in self._listed.saved_dynamics - self._listed.saved_dynamics.add(identity) - return (None if existing is None else existing.id), created - - def delete_copy(self, policy_id: UUID) -> None: - """Change nothing: a listing only reports the deletion.""" - - -def _stored_id(content: SplitContent) -> UUID: - """Return the ID of a row the run found or created; it always has one.""" - return require_stored_row( - content.id, f"the row with content {content.content_hash}" - ) - - -class _StoredSplitRows: - """Find or create one copy's rows, and change what names the copy.""" - - def __init__(self, session: Session, copy_id: UUID) -> None: - """Write through ``session``, in the caller's transaction, for one copy.""" - self._session = session - self._copy_id = copy_id - self._policies: dict[str, SplitContent] = {} - self._dynamics: dict[str, SplitContent] = {} - - def policy(self, content: ResolvedPolicyCreationInput) -> SplitContent: - """Find or create the policy (C1 · 36's ``create_resolved_policy``).""" - from policyengine_api.services.v2.policies.services import ( - create_resolved_policy, - ) - - content_hash = _content_hash(content) - if content_hash not in self._policies: - result = create_resolved_policy(self._session, content) - self._policies[content_hash] = SplitContent( - id=result.policy_id, content_hash=content_hash, created=result.created - ) - return self._policies[content_hash] - - def dynamic(self, content: ResolvedDynamicCreationInput) -> SplitContent: - """Find or create the dynamic (C1 · 36's ``create_resolved_dynamic``).""" - from policyengine_api.services.v2.dynamics.services import ( - create_resolved_dynamic, - ) - - content_hash = _content_hash(content) - if content_hash not in self._dynamics: - result = create_resolved_dynamic(self._session, content) - self._dynamics[content_hash] = SplitContent( - id=result.dynamic_id, content_hash=content_hash, created=result.created - ) - return self._dynamics[content_hash] - - def repoint_mapping( - self, target: MappingTarget, *, policy: SplitContent, dynamic: SplitContent - ) -> None: - """Point the mapping at the policy and dynamic.""" - repoint_legacy_policy_mapping( - self._session, - target.mapping_id, - policy_id=_stored_id(policy), - dynamic_id=_stored_id(dynamic), - ) - - def current_saved_policy( - self, target: SavedPolicyTarget - ) -> SavedPolicyTarget | None: - """Lock the saved policy and read it again. - - Its owner may have changed since ``_prepare`` read it, as when a - browser's saved policies move to an account at sign-in, and it may - have been deleted or pointed elsewhere. The copy is locked, so no - saved policy can start naming it. - """ - saved_policy = read_saved_policy_for_update( - self._session, target.user_policy_id - ) - if saved_policy is None or saved_policy.policy_id != self._copy_id: - return None - return replace(target, user_id=saved_policy.user_id, name=saved_policy.name) - - def repoint_saved_policy( - self, target: SavedPolicyTarget, *, policy: SplitContent - ) -> None: - """Point the saved policy at the policy; its name and description stay.""" - repoint_saved_policy( - self._session, target.user_policy_id, policy_id=_stored_id(policy) - ) - - def saved_dynamic( - self, target: SavedPolicyTarget, *, dynamic: SplitContent - ) -> tuple[UUID | None, bool]: - """Give the saved policy's owner a saved dynamic naming the dynamic. - - It takes the saved policy's name and no description (C1 · 43's - ``create_user_dynamic_in_session``); an identical one the owner - already has is reused. - """ - from policyengine_api.services.v2.user_dynamics.services import ( - create_user_dynamic_in_session, - ) - - dynamic_id = _stored_id(dynamic) - existing = read_saved_dynamic_with_name( - self._session, - user_id=target.user_id, - country_id=target.country_id, - dynamic_id=dynamic_id, - name=target.name, - ) - if existing is not None: - return existing.id, False - saved_dynamic = create_user_dynamic_in_session( - self._session, - UserDynamicCreationInput.model_validate( - { - "country_id": target.country_id, - "user_id": target.user_id, - "dynamic_id": dynamic_id, - "name": target.name, - "description": None, - } - ), - ) - return saved_dynamic.id, True - - def delete_copy(self, policy_id: UUID) -> None: - """Delete the copy; its values go with it.""" - delete_policy(self._session, policy_id) - - -def plan_policy_copy_split( - session: Session, policy_id: UUID, listed: ListedRows | None = None -) -> PolicyCopySplit | None: - """Return what splitting one copy would change, reading only. - - Rows that don't exist yet have no ID. ``listed`` holds what the listing - reported for earlier copies. Return None when the policy is no longer - stored or sets no model assumption. - """ - prepared = _prepare(session, policy_id, lock=False) - if prepared is None: - return None - if prepared.refusal_reason is not None: - return _refused(prepared, applied=False) - return _split_prepared( - prepared, - _ListedSplitRows(session, ListedRows() if listed is None else listed), - applied=False, - ) - - -def split_policy_copy_in_session( - session: Session, policy_id: UUID -) -> PolicyCopySplit | None: - """Split one copy in the caller's transaction, which commits it. - - The rows it changes are locked first, so nothing can start naming the - copy before the transaction ends. Return None when the policy is no - longer stored or sets no model assumption. Raise PolicyCopyIntegrityError, - and the policy and dynamic creation errors, for stored rows that - contradict their keys. - """ - prepared = _prepare(session, policy_id, lock=True) - if prepared is None: - return None - if prepared.refusal_reason is not None: - return _refused(prepared, applied=True) - return _split_prepared( - prepared, _StoredSplitRows(session, prepared.policy_id), applied=True - ) - - -class V2PolicyCopySplitService: - """List or apply the split of every stored copy, one transaction per copy. - - A copy whose transaction meets a lock conflict (the lock timeout ran out, - or PostgreSQL found a deadlock) is rolled back and tried again, - ``retry_delay_seconds`` apart, for ``attempts`` attempts in all. With the command's - lock timeout shorter than PostgreSQL's deadlock_timeout, the split gives - way to API v1's live writes in a lock cycle. - """ - - def __init__( - self, - database_session: PolicyCopySplitDatabaseSession, - *, - attempts: int = 5, - retry_delay_seconds: float = 1.0, - sleep: Callable[[float], None] = time.sleep, - ) -> None: - """Open sessions through ``database_session``.""" - self._database_session = database_session - self._attempts = attempts - self._retry_delay_seconds = retry_delay_seconds - self._sleep = sleep - - def list_policy_copy_splits(self) -> tuple[PolicyCopySplit, ...]: - """Return what splitting every copy would change, in one read session.""" - listed = ListedRows() - with self._database_session.read() as session: - planned = ( - plan_policy_copy_split(session, policy_id, listed) - for policy_id in read_policy_copy_ids(session) - ) - return tuple(split for split in planned if split is not None) - - def split_policy_copies(self) -> Iterator[PolicyCopySplit]: - """Split each copy in its own transaction, yielding each as it commits.""" - with self._database_session.read() as session: - policy_ids = read_policy_copy_ids(session) - for policy_id in policy_ids: - split = self._split_with_retries(policy_id) - if split is not None: - yield split - - def _split_with_retries(self, policy_id: UUID) -> PolicyCopySplit | None: - """Split one copy, trying it again after a lock conflict. - - Raise the last lock conflict when every attempt meets one, and any - other database error at once. - """ - attempt = 1 - while True: - try: - with self._database_session.transaction() as session: - return split_policy_copy_in_session(session, policy_id) - except OperationalError as error: - if attempt >= self._attempts or not is_lock_conflict(error): - raise - attempt += 1 - self._sleep(self._retry_delay_seconds) - - def count_policy_copies(self) -> int: - """Return how many stored policies still set a model assumption.""" - with self._database_session.read() as session: - return len(read_policy_copy_ids(session)) diff --git a/policyengine_api/services/v2/policy_copy_split/transformations.py b/policyengine_api/services/v2/policy_copy_split/transformations.py deleted file mode 100644 index 2e835871a..000000000 --- a/policyengine_api/services/v2/policy_copy_split/transformations.py +++ /dev/null @@ -1,64 +0,0 @@ -"""Pure representation transformations for the policy copy split. - -A stored copy is split on its own catalog version: its values keep their -parameter IDs, values and dates, and only move to a policy or a dynamic by -``policyengine_api.dynamic_parameters``. Its content hash is a policy's -(``policies.transformations.canonicalize_policy``). -""" - -from __future__ import annotations - -from typing import TYPE_CHECKING - -from policyengine_api.dynamic_parameters import is_dynamic_parameter -from policyengine_api.services.v2.dynamics.types import ResolvedDynamicCreationInput -from policyengine_api.services.v2.policies.transformations import ( - stored_policy_creation_input, -) -from policyengine_api.services.v2.policies.types import ResolvedPolicyCreationInput -from policyengine_api.services.v2.policy_copy_split.types import StoredPolicySplit - -if TYPE_CHECKING: - from collections.abc import Sequence - - from policyengine_api.data.v2.models import ( - ParameterValue, - Policy, - TaxBenefitModelVersion, - ) - - -def split_stored_policy( - policy: Policy, - model_version: TaxBenefitModelVersion, - values: Sequence[tuple[ParameterValue, str]], -) -> StoredPolicySplit | None: - """Split a stored policy's values, each with its parameter's name, in two. - - The model assumptions go into the dynamic and the rest into the policy, - which is empty when the copy set only assumptions. Both are bound to the - copy's own model and catalog version. Return None when the policy sets - no model assumption. - """ - whole = stored_policy_creation_input( - policy, model_version, [value for value, _parameter_name in values] - ) - names_by_parameter_id = {value.parameter_id: name for value, name in values} - policy_values = [] - dynamic_values = [] - for value in whole.parameter_values: - parameter_name = names_by_parameter_id[value.parameter_id] - if is_dynamic_parameter(whole.country_id, parameter_name): - dynamic_values.append(value) - else: - policy_values.append(value) - if not dynamic_values: - return None - return StoredPolicySplit( - policy=ResolvedPolicyCreationInput.model_validate( - {**dict(whole), "parameter_values": policy_values} - ), - dynamic=ResolvedDynamicCreationInput.model_validate( - {**dict(whole), "parameter_values": dynamic_values} - ), - ) diff --git a/policyengine_api/services/v2/policy_copy_split/types.py b/policyengine_api/services/v2/policy_copy_split/types.py deleted file mode 100644 index 9cf7133ba..000000000 --- a/policyengine_api/services/v2/policy_copy_split/types.py +++ /dev/null @@ -1,207 +0,0 @@ -"""Framework-independent data exchanged by the layers of the policy copy split. - -A policy copy here is a stored v2 policy that sets a model assumption -(``policyengine_api.dynamic_parameters``): the v1-to-v2 copy made such -policies before it split model assumptions off (C1 · 36), and for UK -``gov.dynamic.`` values until that prefix joined (C1 · 48). -""" - -from __future__ import annotations - -from dataclasses import dataclass, field -from enum import StrEnum -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from uuid import UUID - - from policyengine_api.services.v2.dynamics.types import ( - ResolvedDynamicCreationInput, - ) - from policyengine_api.services.v2.policies.types import ( - ResolvedPolicyCreationInput, - ) - - -class PolicyCopyOutcome(StrEnum): - """What happens to the old copy once its split is stored.""" - - # Nothing names it any more, so it is deleted with its values. - DELETED = "deleted" - # A simulation, report or household calculation still names it, so it is - # kept, although its legacy mappings and saved policies are re-pointed. - KEPT = "kept" - # It can't be split as decided, so nothing changes for it. - REFUSED = "refused" - - -class PolicyCopyRefusalReason(StrEnum): - """Why a copy is refused: a mapping's dynamic can't take its assumptions.""" - - # The mapping's dynamic sets one of the copy's assumptions, for the same - # start date, to another value or end date. - CONFLICTING_DYNAMIC_VALUES = "conflicting_dynamic_values" - # The mapping's dynamic is bound to another model or catalog version. - DYNAMIC_ON_ANOTHER_CATALOG = "dynamic_on_another_catalog" - # Together they hold more values than a dynamic may. - TOO_MANY_VALUES = "too_many_values" - - -@dataclass(frozen=True) -class StoredPolicySplit: - """A stored copy's values, split on its own catalog version. - - ``policy`` holds the values that aren't model assumptions, and may be - empty; ``dynamic`` holds the model assumptions. - """ - - policy: ResolvedPolicyCreationInput - dynamic: ResolvedDynamicCreationInput - - -@dataclass(frozen=True) -class MappingTarget: - """A legacy mapping naming the copy, and the dynamic it will name. - - ``previous_dynamic_id`` is read before the mapping changes. - """ - - mapping_id: UUID - country_id: str - legacy_policy_id: int - previous_dynamic_id: UUID | None - dynamic: ResolvedDynamicCreationInput - - -@dataclass(frozen=True) -class SavedPolicyTarget: - """A saved policy naming the copy, and the dynamic its saved dynamic will name.""" - - user_policy_id: UUID - user_id: UUID - country_id: str - name: str | None - dynamic: ResolvedDynamicCreationInput - - -@dataclass(frozen=True) -class PreparedPolicyCopySplit: - """Everything the split of one copy reads before it writes anything. - - ``refusal_reason`` is set when the copy can't be split; the targets are - then empty. - """ - - policy_id: UUID - country_id: str - policyengine_version: str - split: StoredPolicySplit - mapping_targets: tuple[MappingTarget, ...] - saved_policy_targets: tuple[SavedPolicyTarget, ...] - references: CopyReferences - refusal_reason: PolicyCopyRefusalReason | None - - -@dataclass(frozen=True) -class SplitContent: - """A policy or dynamic the split points a row at, found by its content hash. - - ``id`` is the stored row's ID. It is None only in a read-only listing, - for a row that doesn't exist yet. ``created`` says whether this run - created the row, or in a listing would. - """ - - id: UUID | None - content_hash: str - created: bool - - -@dataclass(frozen=True) -class CopyReferences: - """How many simulations, reports and household calculations name a copy.""" - - simulations: int - reports: int - household_jobs: int - - @property - def total(self) -> int: - """All three counts together; any of them keeps the copy.""" - return self.simulations + self.reports + self.household_jobs - - -@dataclass(frozen=True) -class RepointedMapping: - """A legacy policy mapping moved from the old copy to its split. - - ``previous_dynamic_id`` is the dynamic the mapping named before; when it - named one, ``dynamic`` holds that dynamic's values and the copy's model - assumptions together. - """ - - country_id: str - legacy_policy_id: int - previous_dynamic_id: UUID | None - dynamic: SplitContent - - -@dataclass(frozen=True) -class RepointedSavedPolicy: - """A saved policy moved from the old copy to its split, and its saved dynamic. - - The saved dynamic belongs to the saved policy's owner, names ``dynamic`` - and takes the saved policy's name. ``saved_dynamic_created`` is false when - the owner already had an identical one, which is then reused. - ``saved_dynamic_id`` is None only in a listing, for one that doesn't - exist yet. - """ - - user_policy_id: UUID - dynamic: SplitContent - saved_dynamic_id: UUID | None - saved_dynamic_created: bool - - -@dataclass(frozen=True) -class PolicyCopySplit: - """What the split did to one stored copy, or in a listing would do. - - ``applied`` is false for a read-only listing. ``policy`` and ``dynamic`` - are the plain split of the copy, None only when it is refused. - """ - - old_policy_id: UUID - country_id: str - policyengine_version: str - applied: bool - outcome: PolicyCopyOutcome - policy: SplitContent | None - dynamic: SplitContent | None - mappings: tuple[RepointedMapping, ...] - saved_policies: tuple[RepointedSavedPolicy, ...] - references: CopyReferences - refusal_reason: PolicyCopyRefusalReason | None - - -@dataclass(frozen=True) -class SavedDynamicIdentity: - """What makes two saved dynamics identical: owner, country, dynamic and name.""" - - user_id: UUID - country_id: str - dynamic_content_hash: str - name: str | None - - -@dataclass -class ListedRows: - """What a listing has reported so far, across copies, by content hash. - - Applying commits each copy before the next, so a later copy finds the - policies, dynamics and saved dynamics an earlier copy created; the - listing reports those as found, as applying will. - """ - - policies: dict[str, SplitContent] = field(default_factory=dict) - dynamics: dict[str, SplitContent] = field(default_factory=dict) - saved_dynamics: set[SavedDynamicIdentity] = field(default_factory=set) diff --git a/policyengine_api/services/v2/policy_copy_split/validators.py b/policyengine_api/services/v2/policy_copy_split/validators.py deleted file mode 100644 index cc337eabe..000000000 --- a/policyengine_api/services/v2/policy_copy_split/validators.py +++ /dev/null @@ -1,125 +0,0 @@ -"""Database-independent validation for the policy copy split.""" - -from __future__ import annotations - -import json -from typing import TYPE_CHECKING, TypeVar - -from policyengine_api.services.v2.dynamics.types import ResolvedDynamicCreationInput -from policyengine_api.services.v2.policies.validators import ( - MAXIMUM_POLICY_PARAMETER_VALUES, -) -from policyengine_api.services.v2.policy_copy_split.types import ( - PolicyCopyRefusalReason, -) - -if TYPE_CHECKING: - from datetime import datetime - from uuid import UUID - - from policyengine_api.services.v2.policies.types import ( - PolicyParameterValueInput, - ResolvedPolicyCreationInput, - ) - -StoredRow = TypeVar("StoredRow") -# PostgreSQL's lock_not_available (a lock timeout ran out) and deadlock_detected. -LOCK_CONFLICT_SQLSTATES = frozenset({"55P03", "40P01"}) - - -class PolicyCopySplitRefusedError(ValueError): - """Raised when a copy can't be split as decided; nothing changes for it. - - ``reason`` says why, as the command reports it. - """ - - def __init__(self, reason: PolicyCopyRefusalReason) -> None: - """Keep the reason, which the command's report names.""" - self.reason = reason - super().__init__(reason) - - def __str__(self) -> str: - """Name the reason.""" - return f"the policy copy can't be split: {self.reason.value}" - - -class PolicyCopyIntegrityError(RuntimeError): - """Raised when a row the split reads is missing although a key requires it.""" - - -def require_stored_row(row: StoredRow | None, description: str) -> StoredRow: - """Return the row, or raise PolicyCopyIntegrityError naming what is missing.""" - if row is None: - msg = f"{description} is missing although a foreign key requires it" - raise PolicyCopyIntegrityError(msg) - return row - - -def _same_value( - earlier: PolicyParameterValueInput, later: PolicyParameterValueInput -) -> bool: - """Return whether two values for one parameter and start date are identical. - - The JSON values are compared as JSON, so ``true`` differs from ``1``, which - Python would count as equal. - """ - return earlier.end_date == later.end_date and json.dumps( - earlier.value, sort_keys=True - ) == json.dumps(later.value, sort_keys=True) - - -def merge_dynamic_content( - existing: ResolvedPolicyCreationInput, - split_off: ResolvedDynamicCreationInput, -) -> ResolvedDynamicCreationInput: - """Return one dynamic holding a mapping's dynamic and a copy's assumptions. - - ``existing`` is the dynamic a legacy mapping already names, rebuilt from - its stored rows, and ``split_off`` the model assumptions split from the - copy the mapping names. A value both set identically for the same - parameter and start date is kept once. Raise PolicyCopySplitRefusedError - when they are bound to different models or catalog versions, set one - parameter for the same start date differently, or hold more values - together than a dynamic may. - """ - if ( - existing.country_id, - existing.tax_benefit_model_id, - existing.tax_benefit_model_version_id, - ) != ( - split_off.country_id, - split_off.tax_benefit_model_id, - split_off.tax_benefit_model_version_id, - ): - raise PolicyCopySplitRefusedError( - PolicyCopyRefusalReason.DYNAMIC_ON_ANOTHER_CATALOG - ) - merged: dict[tuple[UUID, datetime], PolicyParameterValueInput] = { - (value.parameter_id, value.start_date): value - for value in existing.parameter_values - } - for value in split_off.parameter_values: - identity = (value.parameter_id, value.start_date) - earlier = merged.get(identity) - if earlier is None: - merged[identity] = value - elif not _same_value(earlier, value): - raise PolicyCopySplitRefusedError( - PolicyCopyRefusalReason.CONFLICTING_DYNAMIC_VALUES - ) - if len(merged) > MAXIMUM_POLICY_PARAMETER_VALUES: - raise PolicyCopySplitRefusedError(PolicyCopyRefusalReason.TOO_MANY_VALUES) - return ResolvedDynamicCreationInput.model_validate( - {**dict(split_off), "parameter_values": list(merged.values())} - ) - - -def is_lock_conflict(error: BaseException) -> bool: - """Return whether a database error is a lock timeout or a deadlock. - - SQLAlchemy wraps the driver's error in ``orig``, whose ``sqlstate`` names - it. A transaction that fails this way changed nothing and can be tried - again. - """ - driver_error = getattr(error, "orig", None) - return getattr(driver_error, "sqlstate", None) in LOCK_CONFLICT_SQLSTATES diff --git a/pyproject.toml b/pyproject.toml index ede5123eb..898b592a2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -415,8 +415,6 @@ banned-module-level-imports = [ "policyengine_api.services.v2.metadata.services", "policyengine_api.services.v2.policies.database_session", "policyengine_api.services.v2.policies.services", - "policyengine_api.services.v2.policy_copy_split.database_session", - "policyengine_api.services.v2.policy_copy_split.services", "policyengine_api.services.v2.report_run_records.database_session", "policyengine_api.services.v2.report_run_records.services", "policyengine_api.services.v2.simulation_service.services", diff --git a/scripts/split_v2_policy_copies.py b/scripts/split_v2_policy_copies.py deleted file mode 100755 index 6be2f5aa9..000000000 --- a/scripts/split_v2_policy_copies.py +++ /dev/null @@ -1,297 +0,0 @@ -#!/usr/bin/env python3 -"""Split each stored v2 policy that sets a model assumption into a policy and dynamic. - -Usage:: - - split_v2_policy_copies.py # list what would change; change nothing - split_v2_policy_copies.py --apply # make the changes - -Without ``--apply`` it reads in one READ ONLY transaction and lists, for each -stored policy that sets a model assumption (``gov.simulation.``, US -``simulation.``, UK ``gov.dynamic.``), the policy and dynamic it would split -into, the legacy mappings and saved policies it would re-point, the saved -dynamics it would add, and whether the old copy would be deleted, kept or -refused. With ``--apply`` it makes those changes, one transaction per copy, -and reports the IDs of every row it points at or creates. -``policyengine_api.services.v2.policy_copy_split.services`` describes the -split. - -It exits with 0 when, afterwards, no stored policy sets a model assumption -(for the listing: when every copy would be deleted), and with 1 otherwise, -such as when a copy is kept because a simulation, report or household -calculation names it, or refused. A copy that waits more than half a second -for a lock, or meets a deadlock, is rolled back and tried again a second -later, for five attempts in all, so the split gives way to API v1's live -writes. Any -other failure, such as missing settings, an unreachable database (after 10 -seconds) or a copy that still can't get its locks, raises, so Python prints -its traceback and also exits with 1; the copies already reported have -committed, and running it again carries on. - -It connects as the temporary role ``policyengine_v2_policy_copy_split``, -which the operator creates with the grants in -``docs/migration/stage-10-v2-policies.md`` and drops afterwards: -``V2_POLICY_COPY_SPLIT_DATABASE_URL`` names it, and ``V2_SUPABASE_PROJECT_REF`` -and ``V2_SUPABASE_ENVIRONMENT`` the Supabase project the URL must name. -""" - -from __future__ import annotations - -import argparse -from contextlib import contextmanager -from typing import TYPE_CHECKING, Protocol - -from policyengine_api.data.v2.settings import ( - load_v2_policy_copy_split_database_settings, -) -from policyengine_api.services.v2.policy_copy_split.types import ( - PolicyCopyOutcome, -) - -if TYPE_CHECKING: - from collections.abc import Callable, Iterable, Iterator, Sequence - from contextlib import AbstractContextManager - - from sqlalchemy.engine import URL - - from policyengine_api.services.v2.policy_copy_split.types import ( - CopyReferences, - PolicyCopySplit, - RepointedSavedPolicy, - SplitContent, - ) - - -CONNECT_TIMEOUT_SECONDS = 10 -# Shorter than PostgreSQL's default one-second deadlock_timeout, so in a lock -# cycle with a live write the split's wait ends first, and the service tries -# that copy again. -LOCK_TIMEOUT_MILLISECONDS = 500 -STATEMENT_TIMEOUT_MILLISECONDS = 60_000 - - -class PolicyCopySplitter(Protocol): - """The split service operations this command calls.""" - - def list_policy_copy_splits(self) -> tuple[PolicyCopySplit, ...]: - """Return what splitting every copy would change.""" - ... - - def split_policy_copies(self) -> Iterator[PolicyCopySplit]: - """Split each copy in its own transaction, yielding each as it commits.""" - ... - - def count_policy_copies(self) -> int: - """Return how many stored policies still set a model assumption.""" - ... - - -@contextmanager -def splitter_on_temporary_role(*, writable: bool) -> Iterator[PolicyCopySplitter]: - """Yield the split service on the temporary role's database connection. - - Without ``writable``, every transaction is READ ONLY, so the database - refuses any write. Raise V2ConfigurationError for missing or invalid - settings. - """ - settings = load_v2_policy_copy_split_database_settings() - url = with_time_limits(settings.connection.url) - # These modules are imported only when the command runs, as they need the - # connection. - from policyengine_api.data.v2.database import ( - unpooled_v2_read_only_sessions, - unpooled_v2_sessions, - ) - from policyengine_api.services.v2.policy_copy_split.database_session import ( - PolicyCopySplitDatabaseSession, - ) - from policyengine_api.services.v2.policy_copy_split.services import ( - V2PolicyCopySplitService, - ) - - open_sessions = unpooled_v2_sessions if writable else unpooled_v2_read_only_sessions - with open_sessions(url) as session_factory: - yield V2PolicyCopySplitService(PolicyCopySplitDatabaseSession(session_factory)) - - -def with_time_limits(url: URL) -> URL: - """Return the URL with a connection timeout, and lock and statement timeouts. - - A lock wait then ends after half a second instead of lasting while the - split holds a copy's locks, which a live write may be waiting for; the - service rolls that copy back and tries it again. - """ - time_limits = ( - f"-c lock_timeout={LOCK_TIMEOUT_MILLISECONDS} " - f"-c statement_timeout={STATEMENT_TIMEOUT_MILLISECONDS}" - ) - existing_options = url.query.get("options") - return url.update_query_dict( - { - "connect_timeout": str(CONNECT_TIMEOUT_SECONDS), - "options": ( - time_limits - if existing_options is None - else f"{existing_options} {time_limits}" - ), - } - ) - - -def _parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser( - description=( - "Split every stored v2 policy that sets a model assumption into a " - "policy and a dynamic. Without --apply, only list what would change." - ) - ) - parser.add_argument( - "--apply", - action="store_true", - help="make the changes; without it, nothing is changed", - ) - return parser - - -def _plural(count: int, singular: str, plural: str | None = None) -> str: - return f"{count} {singular if count == 1 else plural or singular + 's'}" - - -def _content(kind: str, content: SplitContent) -> str: - """Name a policy or dynamic: its ID, or its content hash if it is still to come.""" - if content.id is None and content.created: - return f"{kind}: would be created (content hash {content.content_hash[:12]})" - if content.id is None: - return ( - f"{kind}: the one listed above would be reused " - f"(content hash {content.content_hash[:12]})" - ) - return f"{kind} {content.id} ({'created' if content.created else 'already stored'})" - - -def _dynamic_name(content: SplitContent) -> str: - if content.id is None: - return f"a new dynamic (content hash {content.content_hash[:12]})" - return f"dynamic {content.id}" - - -def _references(references: CopyReferences) -> str: - return ( - f"named by {_plural(references.simulations, 'simulation')}, " - f"{_plural(references.reports, 'report')} and " - f"{_plural(references.household_jobs, 'household calculation')}" - ) - - -def _outcome(split: PolicyCopySplit) -> str: - if split.outcome is PolicyCopyOutcome.REFUSED: - refused = "refused" if split.applied else "would be refused" - reason = split.refusal_reason.value if split.refusal_reason else "unknown" - return f"{refused} ({reason}); nothing changes for it" - if split.outcome is PolicyCopyOutcome.KEPT: - kept = "kept" if split.applied else "would be kept" - return f"{kept}: {_references(split.references)}" - return "deleted" if split.applied else "would be deleted" - - -def _describe(split: PolicyCopySplit) -> list[str]: - """Return the report on one copy: one heading, then one entry per change.""" - report = [ - f"Policy copy {split.old_policy_id} ({split.country_id}, catalog version " - f"{split.policyengine_version}): {_outcome(split)}" - ] - if split.policy is None or split.dynamic is None: - return report - policy_name = ( - "the new policy" if split.policy.id is None else f"policy {split.policy.id}" - ) - report += [ - " " + _content("policy", split.policy), - " " + _content("dynamic", split.dynamic), - ] - now = "now" if split.applied else "would point at" - for mapping in split.mappings: - report.append( - f" legacy policy {mapping.country_id} {mapping.legacy_policy_id}: " - f"{now} {policy_name} and {_dynamic_name(mapping.dynamic)} " - f"(was dynamic {mapping.previous_dynamic_id or 'none'})" - ) - for saved_policy in split.saved_policies: - report.append( - f" saved policy {saved_policy.user_policy_id}: {now} {policy_name}; " - f"{_saved_dynamic(saved_policy)} for {_dynamic_name(saved_policy.dynamic)}" - ) - return report - - -def _saved_dynamic(saved_policy: RepointedSavedPolicy) -> str: - """Name the saved dynamic a saved policy's owner gets, or would get.""" - if saved_policy.saved_dynamic_id is None: - if saved_policy.saved_dynamic_created: - return "saved dynamic: would be created" - return "saved dynamic: an identical one listed above would be reused" - if saved_policy.saved_dynamic_created: - return f"saved dynamic {saved_policy.saved_dynamic_id} (created)" - return f"saved dynamic {saved_policy.saved_dynamic_id} (already saved)" - - -def _counts(splits: Iterable[PolicyCopySplit]) -> dict[PolicyCopyOutcome, int]: - counts = dict.fromkeys(PolicyCopyOutcome, 0) - for split in splits: - counts[split.outcome] += 1 - return counts - - -def _list(splitter: PolicyCopySplitter) -> int: - print("Read-only listing: nothing was changed. Run with --apply to change it.") - splits = splitter.list_policy_copy_splits() - for split in splits: - print("\n".join(_describe(split))) - if not splits: - print("No stored policy sets a model assumption.") - return 0 - counts = _counts(splits) - print( - f"{_plural(len(splits), 'policy copy', 'policy copies')} " - f"{'sets' if len(splits) == 1 else 'set'} a model assumption: " - f"{counts[PolicyCopyOutcome.DELETED]} would be deleted, " - f"{counts[PolicyCopyOutcome.KEPT]} would be kept and " - f"{counts[PolicyCopyOutcome.REFUSED]} would be refused." - ) - return 0 if len(splits) == counts[PolicyCopyOutcome.DELETED] else 1 - - -def _apply(splitter: PolicyCopySplitter) -> int: - print("Applying: each policy copy is changed in its own transaction.") - splits = [] - for split in splitter.split_policy_copies(): - splits.append(split) - print("\n".join(_describe(split)), flush=True) - remaining = splitter.count_policy_copies() - counts = _counts(splits) - print( - f"{_plural(len(splits), 'policy copy', 'policy copies')}: " - f"{counts[PolicyCopyOutcome.DELETED]} deleted, " - f"{counts[PolicyCopyOutcome.KEPT]} kept and " - f"{counts[PolicyCopyOutcome.REFUSED]} refused. " - f"{_plural(remaining, 'stored policy', 'stored policies')} still " - f"{'sets' if remaining == 1 else 'set'} a model assumption." - ) - return 0 if remaining == 0 else 1 - - -def main( - argv: Sequence[str] | None = None, - *, - splitter_factory: Callable[..., AbstractContextManager[PolicyCopySplitter]] = ( - splitter_on_temporary_role - ), -) -> int: - """List or apply the split; return 0 when no copy is left, and 1 otherwise.""" - arguments = _parser().parse_args(argv) - with splitter_factory(writable=arguments.apply) as splitter: - return _apply(splitter) if arguments.apply else _list(splitter) - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tests/integration/test_v2_policy_copy_splits.py b/tests/integration/test_v2_policy_copy_splits.py deleted file mode 100644 index 21d28022b..000000000 --- a/tests/integration/test_v2_policy_copy_splits.py +++ /dev/null @@ -1,1375 +0,0 @@ -"""PostgreSQL tests for C1 · 48's split of stored policies holding model assumptions. - -The command runs as the temporary role C1 · 49 creates, holding exactly -``POLICY_COPY_SPLIT_PRIVILEGES``, so a statement those grants don't allow -fails here. Rows are written and removed as the disposable database's -superuser. Each test's catalog has a model of its own, and assertions look -only at the rows the test wrote, since the command reads every stored policy. -""" - -from __future__ import annotations - -import threading -import time -from contextlib import contextmanager -from dataclasses import dataclass, field -from datetime import UTC, datetime -from typing import TYPE_CHECKING -from uuid import UUID, uuid4 - -import pytest -from sqlalchemy import delete, func, or_, update -from sqlalchemy.engine import make_url -from sqlalchemy.exc import DBAPIError -from sqlmodel import Session, col, select - -from policyengine_api.data.v2.database import ( - unpooled_v2_read_only_sessions, - unpooled_v2_sessions, -) -from policyengine_api.data.v2.models import ( - Dataset, - Dynamic, - Household, - HouseholdJob, - LegacyPolicyMapping, - Parameter, - ParameterValue, - Policy, - Report, - Simulation, - TaxBenefitModel, - TaxBenefitModelVersion, - User, - UserDynamic, - UserPolicy, -) -from policyengine_api.data.v2.privilege_reconciliation import ( - apply_declared_privileges, - create_missing_roles, -) -from policyengine_api.data.v2.privileges import ( - POLICY_COPY_SPLIT_PRIVILEGES, - POLICY_COPY_SPLIT_ROLE, -) -from policyengine_api.services.v2.dynamics.services import create_resolved_dynamic -from policyengine_api.services.v2.dynamics.types import ResolvedDynamicCreationInput -from policyengine_api.services.v2.policies.services import create_resolved_policy -from policyengine_api.services.v2.policies.types import ResolvedPolicyCreationInput -from policyengine_api.services.v2.policy_copy_split import services as split_services -from policyengine_api.services.v2.policy_copy_split.database_session import ( - PolicyCopySplitDatabaseSession, -) -from policyengine_api.services.v2.policy_copy_split.services import ( - V2PolicyCopySplitService, - read_policy_copy_ids, - split_policy_copy_in_session, -) -from policyengine_api.services.v2.policy_copy_split.types import ( - PolicyCopyOutcome, - PolicyCopyRefusalReason, - PolicyCopySplit, -) -from scripts.split_v2_policy_copies import with_time_limits -from tests.fixtures.database_sessions import act_as - -if TYPE_CHECKING: - from collections.abc import Callable, Iterator - - from sqlalchemy.orm import sessionmaker - -CATALOG_VERSION = "6.17.1" -US_TAX_RATE = "gov.irs.income.rate" -US_INCOME_ELASTICITY = "gov.simulation.labor_supply_responses.elasticities.income" -US_MTR_DELTA = "simulation.marginal_tax_rate_delta" -UK_TAX_RATE = "gov.hmrc.income_tax.rates.uk[0].rate" -UK_INCOME_ELASTICITY = "gov.simulation.labour_supply_responses.income_elasticity" -UK_OBR_SWITCH = "gov.dynamic.obr_labour_supply_assumptions" -START_2026 = datetime(2026, 1, 1, tzinfo=UTC) -END_2026 = datetime(2026, 12, 31, tzinfo=UTC) - - -@pytest.fixture(scope="module") -def owner_sessions( - v2_owner_sessions: sessionmaker[Session], -) -> sessionmaker[Session]: - """Session factories of the disposable database's owner, its superuser.""" - return v2_owner_sessions - - -@pytest.fixture(scope="module") -def split_role_sessions( - v2_owner_sessions: sessionmaker[Session], - v2_sessions_as_role: Callable[[str], sessionmaker[Session]], -) -> sessionmaker[Session]: - """Session factories acting as the temporary role, with only its declared grants.""" - with v2_owner_sessions.begin() as session: - create_missing_roles(session, [POLICY_COPY_SPLIT_ROLE]) - plan, _default_privileges = apply_declared_privileges( - session, {POLICY_COPY_SPLIT_ROLE: POLICY_COPY_SPLIT_PRIVILEGES} - ) - assert plan.can_apply - return v2_sessions_as_role(POLICY_COPY_SPLIT_ROLE) - - -@pytest.fixture(scope="module") -def listing_sessions( - disposable_v2_database_url: str, split_role_sessions: sessionmaker[Session] -) -> Iterator[sessionmaker[Session]]: - """Yield the owner's READ ONLY Session factories, as the command's listing has. - - ``split_role_sessions`` creates the temporary role, which the listing's - service acts as in each session. - """ - with unpooled_v2_read_only_sessions(disposable_v2_database_url) as sessions: - yield sessions - - -@pytest.fixture(scope="module") -def time_limited_sessions( - disposable_v2_database_url: str, split_role_sessions: sessionmaker[Session] -) -> Iterator[sessionmaker[Session]]: - """Yield the owner's Session factories with the command's time limits. - - Their URL is the command's (``with_time_limits``), so a lock wait ends as - the command's does. ``split_role_sessions`` creates the temporary role. - """ - url = with_time_limits(make_url(disposable_v2_database_url)) - with unpooled_v2_sessions(url) as sessions: - yield sessions - - -class ActingAsTheSplitRole(PolicyCopySplitDatabaseSession): - """Act as the temporary role in each of the owner's sessions (SET LOCAL ROLE).""" - - @contextmanager - def read(self) -> Iterator[Session]: - """Yield a session acting as the temporary role.""" - with super().read() as session: - act_as(session, POLICY_COPY_SPLIT_ROLE) - yield session - - @contextmanager - def transaction(self) -> Iterator[Session]: - """Yield a transaction acting as the temporary role.""" - with super().transaction() as session: - act_as(session, POLICY_COPY_SPLIT_ROLE) - yield session - - -def _service(sessions: sessionmaker[Session]) -> V2PolicyCopySplitService: - return V2PolicyCopySplitService(PolicyCopySplitDatabaseSession(sessions)) - - -def _listing_service(sessions: sessionmaker[Session]) -> V2PolicyCopySplitService: - return V2PolicyCopySplitService(ActingAsTheSplitRole(sessions)) - - -@dataclass -class Scenario: - """One test's model, catalog version and parameters, and what it stored.""" - - country_id: str - model_id: UUID - version_id: UUID - parameter_ids: dict[str, UUID] - policyengine_version: str = CATALOG_VERSION - user_ids: list[UUID] = field(default_factory=list) - legacy_policy_ids: list[int] = field(default_factory=list) - household_ids: list[UUID] = field(default_factory=list) - - def parameter_value( - self, name: str, *, value: object, end_date: datetime | None = END_2026 - ) -> dict[str, object]: - return { - "parameter_id": self.parameter_ids[name], - "value": value, - "start_date": START_2026, - "end_date": end_date, - } - - def content(self, *values: dict[str, object]) -> dict[str, object]: - return { - "country_id": self.country_id, - "tax_benefit_model_id": self.model_id, - "tax_benefit_model_version_id": self.version_id, - "policyengine_version": self.policyengine_version, - "parameter_values": list(values), - } - - -def _store_catalog( - owner_sessions: sessionmaker[Session], country_id: str, names: list[str] -) -> Scenario: - with owner_sessions() as session: - model = TaxBenefitModel(name=f"split-{country_id}-{uuid4().hex[:16]}") - version = TaxBenefitModelVersion( - model=model, - version=CATALOG_VERSION, - current_law_id=1, - metadata_time_periods=[2026], - ) - parameters = [ - Parameter(name=name, tax_benefit_model_version=version) for name in names - ] - session.add_all(parameters) - session.commit() - return Scenario( - country_id=country_id, - model_id=model.id, - version_id=version.id, - parameter_ids={parameter.name: parameter.id for parameter in parameters}, - ) - - -def _remove(owner_sessions: sessionmaker[Session], scenario: Scenario) -> None: - policy_ids = select(Policy.id).where( - Policy.tax_benefit_model_id == scenario.model_id - ) - dynamic_ids = select(Dynamic.id).where( - Dynamic.tax_benefit_model_id == scenario.model_id - ) - with owner_sessions() as session: - session.execute( - delete(UserDynamic).where(col(UserDynamic.dynamic_id).in_(dynamic_ids)) - ) - session.execute( - delete(UserPolicy).where(col(UserPolicy.policy_id).in_(policy_ids)) - ) - session.execute(delete(User).where(col(User.id).in_(scenario.user_ids))) - session.execute( - delete(LegacyPolicyMapping).where( - or_( - col(LegacyPolicyMapping.policy_id).in_(policy_ids), - col(LegacyPolicyMapping.dynamic_id).in_(dynamic_ids), - ) - ) - ) - session.execute( - delete(Report).where(Report.tax_benefit_model_id == scenario.model_id) - ) - session.execute( - delete(Simulation).where( - Simulation.tax_benefit_model_version_id == scenario.version_id - ) - ) - session.execute( - delete(Dataset).where( - Dataset.tax_benefit_model_version_id == scenario.version_id - ) - ) - session.execute( - delete(Policy).where(Policy.tax_benefit_model_id == scenario.model_id) - ) - session.execute( - delete(Dynamic).where(Dynamic.tax_benefit_model_id == scenario.model_id) - ) - version_ids = select(TaxBenefitModelVersion.id).where( - TaxBenefitModelVersion.model_id == scenario.model_id - ) - session.execute( - delete(HouseholdJob).where( - col(HouseholdJob.tax_benefit_model_version_id).in_(version_ids) - ) - ) - session.execute( - delete(Household).where(col(Household.id).in_(scenario.household_ids)) - ) - parameter_ids = select(Parameter.id).where( - col(Parameter.tax_benefit_model_version_id).in_(version_ids) - ) - session.execute( - delete(ParameterValue).where( - col(ParameterValue.parameter_id).in_(parameter_ids) - ) - ) - session.execute( - delete(Parameter).where( - col(Parameter.tax_benefit_model_version_id).in_(version_ids) - ) - ) - session.execute( - delete(TaxBenefitModelVersion).where( - TaxBenefitModelVersion.model_id == scenario.model_id - ) - ) - session.execute( - delete(TaxBenefitModel).where(TaxBenefitModel.id == scenario.model_id) - ) - session.commit() - - -@pytest.fixture -def us_scenario(owner_sessions: sessionmaker[Session]) -> Iterator[Scenario]: - scenario = _store_catalog( - owner_sessions, "us", [US_TAX_RATE, US_INCOME_ELASTICITY, US_MTR_DELTA] - ) - try: - yield scenario - finally: - _remove(owner_sessions, scenario) - - -@pytest.fixture -def uk_scenario(owner_sessions: sessionmaker[Session]) -> Iterator[Scenario]: - scenario = _store_catalog( - owner_sessions, "uk", [UK_TAX_RATE, UK_INCOME_ELASTICITY, UK_OBR_SWITCH] - ) - try: - yield scenario - finally: - _remove(owner_sessions, scenario) - - -def _store_other_version( - owner_sessions: sessionmaker[Session], scenario: Scenario, names: list[str] -) -> Scenario: - """Store another catalog version of the scenario's model, with these parameters.""" - with owner_sessions() as session: - version = TaxBenefitModelVersion( - model_id=scenario.model_id, - version="6.20.0", - current_law_id=1, - metadata_time_periods=[2026], - ) - parameters = [ - Parameter(name=name, tax_benefit_model_version=version) for name in names - ] - session.add_all(parameters) - session.commit() - return Scenario( - country_id=scenario.country_id, - model_id=scenario.model_id, - version_id=version.id, - parameter_ids={parameter.name: parameter.id for parameter in parameters}, - policyengine_version="6.20.0", - ) - - -def _store_policy( - owner_sessions: sessionmaker[Session], - scenario: Scenario, - *values: dict[str, object], -) -> UUID: - """Store a policy as the v1-to-v2 copy did before C1 · 36: no split.""" - with owner_sessions() as session: - result = create_resolved_policy( - session, - ResolvedPolicyCreationInput.model_validate(scenario.content(*values)), - ) - session.commit() - return result.policy_id - - -def _store_dynamic( - owner_sessions: sessionmaker[Session], - scenario: Scenario, - *values: dict[str, object], -) -> UUID: - with owner_sessions() as session: - result = create_resolved_dynamic( - session, - ResolvedDynamicCreationInput.model_validate(scenario.content(*values)), - ) - session.commit() - return result.dynamic_id - - -def _store_mapping( - owner_sessions: sessionmaker[Session], - scenario: Scenario, - *, - policy_id: UUID, - dynamic_id: UUID | None = None, -) -> int: - legacy_policy_id = 900_000_000 + uuid4().int % 100_000_000 - with owner_sessions() as session: - session.add( - LegacyPolicyMapping( - country_id=scenario.country_id, - legacy_policy_id=legacy_policy_id, - policy_id=policy_id, - dynamic_id=dynamic_id, - source_policy_hash=f"legacy-hash-{legacy_policy_id}", - ) - ) - session.commit() - scenario.legacy_policy_ids.append(legacy_policy_id) - return legacy_policy_id - - -def _store_user(owner_sessions: sessionmaker[Session], scenario: Scenario) -> UUID: - with owner_sessions() as session: - user = User(user_type="unauthenticated") - session.add(user) - session.commit() - scenario.user_ids.append(user.id) - return user.id - - -def _store_saved_policy( - owner_sessions: sessionmaker[Session], - scenario: Scenario, - **saved_policy_fields: object, -) -> UUID: - """Store a saved policy with the given user, policy, name and other fields.""" - with owner_sessions() as session: - saved_policy = UserPolicy(country_id=scenario.country_id, **saved_policy_fields) - session.add(saved_policy) - session.commit() - return saved_policy.id - - -def _values( - owner_sessions: sessionmaker[Session], *, policy_id=None, dynamic_id=None -) -> set: - """Each value a policy or dynamic sets: its parameter, value and end date.""" - with owner_sessions() as session: - owner_column = ( - ParameterValue.policy_id - if dynamic_id is None - else ParameterValue.dynamic_id - ) - rows = session.exec( - select(ParameterValue).where(owner_column == (policy_id or dynamic_id)) - ).all() - return {(row.parameter_id, row.value_json, row.end_date) for row in rows} - - -def _mapping( - owner_sessions: sessionmaker[Session], scenario: Scenario, legacy_policy_id: int -): - with owner_sessions() as session: - return session.exec( - select(LegacyPolicyMapping).where( - LegacyPolicyMapping.country_id == scenario.country_id, - LegacyPolicyMapping.legacy_policy_id == legacy_policy_id, - ) - ).one() - - -def _saved_policy_target( - owner_sessions: sessionmaker[Session], saved_policy_id: UUID -) -> UUID: - with owner_sessions() as session: - return session.get(UserPolicy, saved_policy_id).policy_id - - -def _saved_dynamics( - owner_sessions: sessionmaker[Session], user_id: UUID -) -> list[UserDynamic]: - with owner_sessions() as session: - return list( - session.exec( - select(UserDynamic) - .where(UserDynamic.user_id == user_id) - .order_by(col(UserDynamic.created_at), col(UserDynamic.id)) - ).all() - ) - - -def _policy_exists(owner_sessions: sessionmaker[Session], policy_id: UUID) -> bool: - with owner_sessions() as session: - return session.get(Policy, policy_id) is not None - - -def _result_for(splits, policy_id: UUID) -> PolicyCopySplit: - [split] = [split for split in splits if split.old_policy_id == policy_id] - return split - - -def test_a_us_copy_is_split_re_pointed_given_a_saved_dynamic_and_deleted( - owner_sessions: sessionmaker[Session], - split_role_sessions: sessionmaker[Session], - us_scenario: Scenario, -) -> None: - scenario = us_scenario - old_copy_id = _store_policy( - owner_sessions, - scenario, - scenario.parameter_value(US_TAX_RATE, value=0.3), - scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), - scenario.parameter_value(US_MTR_DELTA, value=0.01, end_date=None), - ) - legacy_policy_id = _store_mapping(owner_sessions, scenario, policy_id=old_copy_id) - user_id = _store_user(owner_sessions, scenario) - saved_policy_id = _store_saved_policy( - owner_sessions, - scenario, - user_id=user_id, - policy_id=old_copy_id, - name="My reform", - legacy_policy_id=legacy_policy_id, - description="Raises the rate, with labour supply responses", - ) - - split = _result_for( - list(_service(split_role_sessions).split_policy_copies()), old_copy_id - ) - - assert split.applied - assert split.outcome is PolicyCopyOutcome.DELETED - assert split.country_id == "us" - assert split.policyengine_version == CATALOG_VERSION - assert split.policy is not None - assert split.policy.created - assert split.dynamic is not None - assert split.dynamic.created - new_policy_id, new_dynamic_id = split.policy.id, split.dynamic.id - assert not _policy_exists(owner_sessions, old_copy_id) - assert _values(owner_sessions, policy_id=old_copy_id) == set() - assert _values(owner_sessions, policy_id=new_policy_id) == { - (scenario.parameter_ids[US_TAX_RATE], 0.3, END_2026) - } - assert _values(owner_sessions, dynamic_id=new_dynamic_id) == { - (scenario.parameter_ids[US_INCOME_ELASTICITY], 0.25, END_2026), - (scenario.parameter_ids[US_MTR_DELTA], 0.01, None), - } - mapping = _mapping(owner_sessions, scenario, legacy_policy_id) - assert (mapping.policy_id, mapping.dynamic_id) == (new_policy_id, new_dynamic_id) - [repointed_mapping] = split.mappings - assert repointed_mapping.legacy_policy_id == legacy_policy_id - assert repointed_mapping.previous_dynamic_id is None - assert repointed_mapping.dynamic.id == new_dynamic_id - assert _saved_policy_target(owner_sessions, saved_policy_id) == new_policy_id - [saved_dynamic] = _saved_dynamics(owner_sessions, user_id) - assert (saved_dynamic.dynamic_id, saved_dynamic.country_id) == ( - new_dynamic_id, - "us", - ) - assert (saved_dynamic.name, saved_dynamic.description) == ("My reform", None) - [repointed_saved_policy] = split.saved_policies - assert repointed_saved_policy.user_policy_id == saved_policy_id - assert repointed_saved_policy.saved_dynamic_id == saved_dynamic.id - assert repointed_saved_policy.saved_dynamic_created - with split_role_sessions() as session: - assert old_copy_id not in read_policy_copy_ids(session) - - second_run = list(_service(split_role_sessions).split_policy_copies()) - - assert old_copy_id not in {split.old_policy_id for split in second_run} - mapping_after = _mapping(owner_sessions, scenario, legacy_policy_id) - assert (mapping_after.policy_id, mapping_after.dynamic_id) == ( - new_policy_id, - new_dynamic_id, - ) - assert _saved_policy_target(owner_sessions, saved_policy_id) == new_policy_id - assert [row.id for row in _saved_dynamics(owner_sessions, user_id)] == [ - saved_dynamic.id - ] - - -def test_a_uk_copy_of_only_model_assumptions_points_at_an_empty_policy( - owner_sessions: sessionmaker[Session], - split_role_sessions: sessionmaker[Session], - uk_scenario: Scenario, -) -> None: - scenario = uk_scenario - old_copy_id = _store_policy( - owner_sessions, scenario, scenario.parameter_value(UK_OBR_SWITCH, value=False) - ) - legacy_policy_id = _store_mapping(owner_sessions, scenario, policy_id=old_copy_id) - - split = _result_for( - list(_service(split_role_sessions).split_policy_copies()), old_copy_id - ) - - assert split.outcome is PolicyCopyOutcome.DELETED - mapping = _mapping(owner_sessions, scenario, legacy_policy_id) - assert mapping.policy_id == split.policy.id - assert _values(owner_sessions, policy_id=mapping.policy_id) == set() - with owner_sessions() as session: - empty_policy = session.get(Policy, mapping.policy_id) - assert empty_policy.tax_benefit_model_version_id == scenario.version_id - assert _values(owner_sessions, dynamic_id=mapping.dynamic_id) == { - (scenario.parameter_ids[UK_OBR_SWITCH], False, END_2026) - } - assert not _policy_exists(owner_sessions, old_copy_id) - - -def test_a_mapping_that_already_names_a_dynamic_gets_one_merged_dynamic( - owner_sessions: sessionmaker[Session], - split_role_sessions: sessionmaker[Session], - uk_scenario: Scenario, -) -> None: - scenario = uk_scenario - old_copy_id = _store_policy( - owner_sessions, - scenario, - scenario.parameter_value(UK_TAX_RATE, value=0.21), - scenario.parameter_value(UK_OBR_SWITCH, value=False), - ) - earlier_dynamic_id = _store_dynamic( - owner_sessions, - scenario, - scenario.parameter_value(UK_INCOME_ELASTICITY, value=0.1), - ) - legacy_policy_id = _store_mapping( - owner_sessions, scenario, policy_id=old_copy_id, dynamic_id=earlier_dynamic_id - ) - user_id = _store_user(owner_sessions, scenario) - mapped_saved_policy_id = _store_saved_policy( - owner_sessions, - scenario, - user_id=user_id, - policy_id=old_copy_id, - name="Copied from v1", - legacy_policy_id=legacy_policy_id, - ) - native_saved_policy_id = _store_saved_policy( - owner_sessions, scenario, user_id=user_id, policy_id=old_copy_id, name="Native" - ) - - split = _result_for( - list(_service(split_role_sessions).split_policy_copies()), old_copy_id - ) - - assert split.outcome is PolicyCopyOutcome.DELETED - mapping = _mapping(owner_sessions, scenario, legacy_policy_id) - assert mapping.policy_id == split.policy.id - assert _values(owner_sessions, policy_id=mapping.policy_id) == { - (scenario.parameter_ids[UK_TAX_RATE], 0.21, END_2026) - } - merged_dynamic_id = mapping.dynamic_id - assert merged_dynamic_id not in {earlier_dynamic_id, split.dynamic.id} - assert _values(owner_sessions, dynamic_id=merged_dynamic_id) == { - (scenario.parameter_ids[UK_INCOME_ELASTICITY], 0.1, END_2026), - (scenario.parameter_ids[UK_OBR_SWITCH], False, END_2026), - } - assert _values(owner_sessions, dynamic_id=split.dynamic.id) == { - (scenario.parameter_ids[UK_OBR_SWITCH], False, END_2026) - } - [repointed_mapping] = split.mappings - assert repointed_mapping.previous_dynamic_id == earlier_dynamic_id - assert repointed_mapping.dynamic.id == merged_dynamic_id - saved_dynamics = { - row.name: row.dynamic_id for row in _saved_dynamics(owner_sessions, user_id) - } - assert saved_dynamics == { - "Copied from v1": merged_dynamic_id, - "Native": split.dynamic.id, - } - for saved_policy_id in (mapped_saved_policy_id, native_saved_policy_id): - assert ( - _saved_policy_target(owner_sessions, saved_policy_id) == mapping.policy_id - ) - with owner_sessions() as session: - assert session.get(Dynamic, earlier_dynamic_id) is not None - - -def test_a_copy_a_report_names_is_split_and_re_pointed_but_kept( - owner_sessions: sessionmaker[Session], - split_role_sessions: sessionmaker[Session], - us_scenario: Scenario, -) -> None: - scenario = us_scenario - old_copy_id = _store_policy( - owner_sessions, - scenario, - scenario.parameter_value(US_TAX_RATE, value=0.3), - scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), - ) - legacy_policy_id = _store_mapping(owner_sessions, scenario, policy_id=old_copy_id) - user_id = _store_user(owner_sessions, scenario) - saved_policy_id = _store_saved_policy( - owner_sessions, scenario, user_id=user_id, policy_id=old_copy_id, name="Kept" - ) - with owner_sessions() as session: - report = Report( - country="us", - tax_benefit_model_id=scenario.model_id, - policy_id=old_copy_id, - ) - session.add(report) - session.commit() - report_id = report.id - - split = _result_for( - list(_service(split_role_sessions).split_policy_copies()), old_copy_id - ) - - assert split.outcome is PolicyCopyOutcome.KEPT - assert ( - split.references.simulations, - split.references.reports, - split.references.household_jobs, - ) == (0, 1, 0) - assert _policy_exists(owner_sessions, old_copy_id) - assert len(_values(owner_sessions, policy_id=old_copy_id)) == 2 - with owner_sessions() as session: - assert session.get(Report, report_id).policy_id == old_copy_id - mapping = _mapping(owner_sessions, scenario, legacy_policy_id) - assert (mapping.policy_id, mapping.dynamic_id) == ( - split.policy.id, - split.dynamic.id, - ) - assert _saved_policy_target(owner_sessions, saved_policy_id) == split.policy.id - [saved_dynamic] = _saved_dynamics(owner_sessions, user_id) - with split_role_sessions() as session: - assert old_copy_id in read_policy_copy_ids(session) - - second_split = _result_for( - list(_service(split_role_sessions).split_policy_copies()), old_copy_id - ) - - assert second_split.outcome is PolicyCopyOutcome.KEPT - assert second_split.mappings == () - assert second_split.saved_policies == () - assert [row.id for row in _saved_dynamics(owner_sessions, user_id)] == [ - saved_dynamic.id - ] - with owner_sessions() as session: - session.execute(delete(Report).where(Report.id == report_id)) - session.commit() - - -def test_a_conflicting_merge_refuses_the_copy_and_changes_nothing( - owner_sessions: sessionmaker[Session], - split_role_sessions: sessionmaker[Session], - uk_scenario: Scenario, -) -> None: - scenario = uk_scenario - old_copy_id = _store_policy( - owner_sessions, - scenario, - scenario.parameter_value(UK_TAX_RATE, value=0.21), - scenario.parameter_value(UK_INCOME_ELASTICITY, value=0.2), - ) - earlier_dynamic_id = _store_dynamic( - owner_sessions, - scenario, - scenario.parameter_value(UK_INCOME_ELASTICITY, value=0.1), - ) - legacy_policy_id = _store_mapping( - owner_sessions, scenario, policy_id=old_copy_id, dynamic_id=earlier_dynamic_id - ) - user_id = _store_user(owner_sessions, scenario) - saved_policy_id = _store_saved_policy( - owner_sessions, - scenario, - user_id=user_id, - policy_id=old_copy_id, - name="Conflicting", - legacy_policy_id=legacy_policy_id, - ) - - split = _result_for( - list(_service(split_role_sessions).split_policy_copies()), old_copy_id - ) - - assert split.outcome is PolicyCopyOutcome.REFUSED - assert split.refusal_reason is PolicyCopyRefusalReason.CONFLICTING_DYNAMIC_VALUES - assert _policy_exists(owner_sessions, old_copy_id) - mapping = _mapping(owner_sessions, scenario, legacy_policy_id) - assert (mapping.policy_id, mapping.dynamic_id) == (old_copy_id, earlier_dynamic_id) - assert _saved_policy_target(owner_sessions, saved_policy_id) == old_copy_id - assert _saved_dynamics(owner_sessions, user_id) == [] - with owner_sessions() as session: - stored = session.exec( - select(Policy.id).where(Policy.tax_benefit_model_id == scenario.model_id) - ).all() - assert list(stored) == [old_copy_id] - dynamics = session.exec( - select(Dynamic.id).where(Dynamic.tax_benefit_model_id == scenario.model_id) - ).all() - assert list(dynamics) == [earlier_dynamic_id] - - -def test_the_listing_reads_only_and_reports_what_would_change( - owner_sessions: sessionmaker[Session], - split_role_sessions: sessionmaker[Session], - us_scenario: Scenario, - listing_sessions: sessionmaker[Session], -) -> None: - scenario = us_scenario - stored_policy_part_id = _store_policy( - owner_sessions, scenario, scenario.parameter_value(US_TAX_RATE, value=0.3) - ) - old_copy_id = _store_policy( - owner_sessions, - scenario, - scenario.parameter_value(US_TAX_RATE, value=0.3), - scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), - ) - legacy_policy_id = _store_mapping(owner_sessions, scenario, policy_id=old_copy_id) - user_id = _store_user(owner_sessions, scenario) - saved_policy_id = _store_saved_policy( - owner_sessions, scenario, user_id=user_id, policy_id=old_copy_id, name="Listed" - ) - - split = _result_for( - _listing_service(listing_sessions).list_policy_copy_splits(), - old_copy_id, - ) - - assert not split.applied - assert split.outcome is PolicyCopyOutcome.DELETED - assert (split.policy.id, split.policy.created) == (stored_policy_part_id, False) - assert (split.dynamic.id, split.dynamic.created) == (None, True) - [listed_mapping] = split.mappings - assert listed_mapping.legacy_policy_id == legacy_policy_id - assert listed_mapping.dynamic.content_hash == split.dynamic.content_hash - [listed_saved_policy] = split.saved_policies - assert listed_saved_policy.user_policy_id == saved_policy_id - assert listed_saved_policy.saved_dynamic_id is None - assert listed_saved_policy.saved_dynamic_created - assert _policy_exists(owner_sessions, old_copy_id) - mapping = _mapping(owner_sessions, scenario, legacy_policy_id) - assert (mapping.policy_id, mapping.dynamic_id) == (old_copy_id, None) - assert _saved_policy_target(owner_sessions, saved_policy_id) == old_copy_id - assert _saved_dynamics(owner_sessions, user_id) == [] - with owner_sessions() as session: - dynamics = session.exec( - select(Dynamic.id).where(Dynamic.tax_benefit_model_id == scenario.model_id) - ).all() - assert dynamics == [] - - -def test_an_identical_saved_dynamic_is_reused_and_another_name_gets_its_own( - owner_sessions: sessionmaker[Session], - split_role_sessions: sessionmaker[Session], - us_scenario: Scenario, -) -> None: - scenario = us_scenario - old_copy_id = _store_policy( - owner_sessions, - scenario, - scenario.parameter_value(US_TAX_RATE, value=0.3), - scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), - ) - user_id = _store_user(owner_sessions, scenario) - first_id, second_id, other_id, unnamed_id, also_unnamed_id = ( - _store_saved_policy( - owner_sessions, scenario, user_id=user_id, policy_id=old_copy_id, name=name - ) - for name in ("Reform A", "Reform A", "Reform B", None, None) - ) - - split = _result_for( - list(_service(split_role_sessions).split_policy_copies()), old_copy_id - ) - - by_saved_policy = { - repointed.user_policy_id: repointed for repointed in split.saved_policies - } - assert by_saved_policy[first_id].saved_dynamic_created - assert not by_saved_policy[second_id].saved_dynamic_created - assert ( - by_saved_policy[second_id].saved_dynamic_id - == by_saved_policy[first_id].saved_dynamic_id - ) - assert by_saved_policy[other_id].saved_dynamic_created - assert by_saved_policy[unnamed_id].saved_dynamic_created - assert not by_saved_policy[also_unnamed_id].saved_dynamic_created - assert sorted( - (row.name or "") for row in _saved_dynamics(owner_sessions, user_id) - ) == ["", "Reform A", "Reform B"] - - -def test_policies_setting_no_model_assumption_are_left_alone( - owner_sessions: sessionmaker[Session], - split_role_sessions: sessionmaker[Session], - us_scenario: Scenario, -) -> None: - scenario = us_scenario - policy_id = _store_policy( - owner_sessions, scenario, scenario.parameter_value(US_TAX_RATE, value=0.3) - ) - legacy_policy_id = _store_mapping(owner_sessions, scenario, policy_id=policy_id) - - splits = list(_service(split_role_sessions).split_policy_copies()) - - assert policy_id not in {split.old_policy_id for split in splits} - assert _policy_exists(owner_sessions, policy_id) - assert _mapping(owner_sessions, scenario, legacy_policy_id).dynamic_id is None - - -def test_one_copy_splits_in_a_caller_owned_transaction( - owner_sessions: sessionmaker[Session], - split_role_sessions: sessionmaker[Session], - uk_scenario: Scenario, -) -> None: - """D4 · 1's migration reuses the split in a transaction of its own.""" - scenario = uk_scenario - old_copy_id = _store_policy( - owner_sessions, - scenario, - scenario.parameter_value(UK_TAX_RATE, value=0.21), - scenario.parameter_value(UK_OBR_SWITCH, value=False), - ) - legacy_policy_id = _store_mapping(owner_sessions, scenario, policy_id=old_copy_id) - - with split_role_sessions() as session: - split = split_policy_copy_in_session(session, old_copy_id) - session.rollback() - - assert split is not None - assert split.outcome is PolicyCopyOutcome.DELETED - assert _policy_exists(owner_sessions, old_copy_id) - assert _mapping(owner_sessions, scenario, legacy_policy_id).policy_id == old_copy_id - - with split_role_sessions() as session: - assert split_policy_copy_in_session(session, uuid4()) is None - - -def test_a_copy_a_simulation_names_is_kept( - owner_sessions: sessionmaker[Session], - split_role_sessions: sessionmaker[Session], - us_scenario: Scenario, -) -> None: - scenario = us_scenario - old_copy_id = _store_policy( - owner_sessions, - scenario, - scenario.parameter_value(US_TAX_RATE, value=0.3), - scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), - ) - with owner_sessions() as session: - dataset = Dataset( - name="split-test-dataset", - year=2026, - is_output_dataset=False, - tax_benefit_model_version_id=scenario.version_id, - ) - session.add(dataset) - session.flush() - simulation = Simulation( - dataset_id=dataset.id, - tax_benefit_model_version_id=scenario.version_id, - policy_id=old_copy_id, - ) - session.add(simulation) - session.commit() - simulation_id = simulation.id - - split = _result_for( - list(_service(split_role_sessions).split_policy_copies()), old_copy_id - ) - - assert split.outcome is PolicyCopyOutcome.KEPT - assert ( - split.references.simulations, - split.references.reports, - split.references.household_jobs, - ) == (1, 0, 0) - assert _policy_exists(owner_sessions, old_copy_id) - with owner_sessions() as session: - assert session.get(Simulation, simulation_id).policy_id == old_copy_id - - -def test_the_split_waits_for_a_live_saved_policy_copy_instead_of_deadlocking( - owner_sessions: sessionmaker[Session], - split_role_sessions: sessionmaker[Session], - us_scenario: Scenario, -) -> None: - """API v1's copy of a v1 saved policy locks the mapping, then names the copy. - - It holds the mapping row FOR UPDATE, then inserts a saved policy naming - the mapped copy, whose foreign-key check locks the copy's row. The split - takes the same two locks in the same order, so it waits for the copy to - commit, and then re-points the saved policy the copy added. - """ - scenario = us_scenario - old_copy_id = _store_policy( - owner_sessions, - scenario, - scenario.parameter_value(US_TAX_RATE, value=0.3), - scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), - ) - legacy_policy_id = _store_mapping(owner_sessions, scenario, policy_id=old_copy_id) - user_id = _store_user(owner_sessions, scenario) - split_results: list[PolicyCopySplit] = [] - split_errors: list[Exception] = [] - - def run_split() -> None: - try: - split_results.extend(_service(split_role_sessions).split_policy_copies()) - except DBAPIError as error: - split_errors.append(error) - - split_thread = threading.Thread(target=run_split) - with owner_sessions() as live_copy_session: - live_copy_session.exec( - select(LegacyPolicyMapping) - .where( - LegacyPolicyMapping.country_id == scenario.country_id, - LegacyPolicyMapping.legacy_policy_id == legacy_policy_id, - ) - .with_for_update() - ).one() - split_thread.start() - # Give the split time to reach its locks while the mapping is held. - time.sleep(0.5) - saved_policy = UserPolicy( - user_id=user_id, - country_id=scenario.country_id, - policy_id=old_copy_id, - legacy_policy_id=legacy_policy_id, - name="Saved while splitting", - ) - live_copy_session.add(saved_policy) - live_copy_session.commit() - saved_policy_id = saved_policy.id - split_thread.join(timeout=60) - - assert not split_thread.is_alive() - assert split_errors == [] - split = _result_for(split_results, old_copy_id) - assert split.outcome is PolicyCopyOutcome.DELETED - assert [repointed.user_policy_id for repointed in split.saved_policies] == [ - saved_policy_id - ] - assert _saved_policy_target(owner_sessions, saved_policy_id) == split.policy.id - assert not _policy_exists(owner_sessions, old_copy_id) - - -def test_the_listing_reports_rows_an_earlier_copy_creates_as_reused( - owner_sessions: sessionmaker[Session], - split_role_sessions: sessionmaker[Session], - uk_scenario: Scenario, - listing_sessions: sessionmaker[Session], -) -> None: - """Applying commits each copy before the next, so later copies reuse its rows. - - The listing reports what applying then does: the second copy's dynamic - and saved dynamic are the first copy's. - """ - scenario = uk_scenario - copy_ids = [ - _store_policy( - owner_sessions, - scenario, - scenario.parameter_value(UK_TAX_RATE, value=tax_rate), - scenario.parameter_value(UK_OBR_SWITCH, value=False), - ) - for tax_rate in (0.21, 0.22) - ] - user_id = _store_user(owner_sessions, scenario) - for copy_id in copy_ids: - _store_saved_policy( - owner_sessions, scenario, user_id=user_id, policy_id=copy_id, name=None - ) - - listed = _listing_service(listing_sessions).list_policy_copy_splits() - applied = list(_service(split_role_sessions).split_policy_copies()) - - def created_rows(split: PolicyCopySplit) -> tuple[bool, bool, list[bool]]: - return ( - split.policy.created, - split.dynamic.created, - [saved.saved_dynamic_created for saved in split.saved_policies], - ) - - assert [created_rows(_result_for(listed, copy_id)) for copy_id in copy_ids] == [ - (True, True, [True]), - (True, False, [False]), - ] - assert [created_rows(_result_for(applied, copy_id)) for copy_id in copy_ids] == [ - created_rows(_result_for(listed, copy_id)) for copy_id in copy_ids - ] - assert len(_saved_dynamics(owner_sessions, user_id)) == 1 - - -def test_the_listing_s_sessions_refuse_writes(disposable_v2_database_url: str) -> None: - with ( - unpooled_v2_read_only_sessions(disposable_v2_database_url) as sessions, - sessions() as session, - ): - session.add(User(user_type="unauthenticated")) - with pytest.raises(DBAPIError, match="read-only transaction"): - session.flush() - - -def test_the_command_s_time_limits_reach_its_sessions( - disposable_v2_database_url: str, -) -> None: - url = with_time_limits(make_url(disposable_v2_database_url)) - - with unpooled_v2_read_only_sessions(url) as sessions, sessions() as session: - lock_timeout = session.exec(select(func.current_setting("lock_timeout"))) - assert lock_timeout.one() == "500ms" - statement_timeout = session.exec( - select(func.current_setting("statement_timeout")) - ) - assert statement_timeout.one() == "1min" - - -def test_the_split_gives_way_to_a_live_sign_in_merge( - owner_sessions: sessionmaker[Session], - time_limited_sessions: sessionmaker[Session], - us_scenario: Scenario, -) -> None: - """API v1's sign-in merge locks the browser's user, then moves its saved policies. - - The split holds a saved policy's lock while saving its owner's dynamic, - whose foreign-key check waits for the user's lock: a lock cycle. The - split's wait ends first (its lock timeout is shorter than PostgreSQL's - deadlock_timeout), so it rolls back, the merge commits, and the split - tries the copy again, for the account the saved policy now belongs to. - """ - scenario = us_scenario - old_copy_id = _store_policy( - owner_sessions, - scenario, - scenario.parameter_value(US_TAX_RATE, value=0.3), - scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), - ) - browser_user_id = _store_user(owner_sessions, scenario) - account_user_id = _store_user(owner_sessions, scenario) - saved_policy_id = _store_saved_policy( - owner_sessions, - scenario, - user_id=browser_user_id, - policy_id=old_copy_id, - name="Saved before signing in", - ) - service = V2PolicyCopySplitService( - ActingAsTheSplitRole(time_limited_sessions), - attempts=10, - retry_delay_seconds=0.2, - ) - split_results: list[PolicyCopySplit] = [] - split_errors: list[Exception] = [] - - def run_split() -> None: - try: - split_results.extend(service.split_policy_copies()) - except DBAPIError as error: - split_errors.append(error) - - split_thread = threading.Thread(target=run_split) - with owner_sessions() as sign_in_session: - sign_in_session.exec( - select(User).where(User.id == browser_user_id).with_for_update() - ).one() - split_thread.start() - # Give the split time to wait for the browser user's lock. - time.sleep(0.3) - sign_in_session.execute( - update(UserPolicy) - .where(col(UserPolicy.user_id) == browser_user_id) - .values(user_id=account_user_id) - ) - sign_in_session.commit() - split_thread.join(timeout=60) - - assert not split_thread.is_alive() - assert split_errors == [] - split = _result_for(split_results, old_copy_id) - assert split.outcome is PolicyCopyOutcome.DELETED - with owner_sessions() as session: - saved_policy = session.get(UserPolicy, saved_policy_id) - assert (saved_policy.user_id, saved_policy.policy_id) == ( - account_user_id, - split.policy.id, - ) - [saved_dynamic] = _saved_dynamics(owner_sessions, account_user_id) - assert saved_dynamic.dynamic_id == split.dynamic.id - assert _saved_dynamics(owner_sessions, browser_user_id) == [] - - -def test_the_split_gives_way_to_a_sign_in_merge_that_waits_first( - owner_sessions: sessionmaker[Session], - time_limited_sessions: sessionmaker[Session], - us_scenario: Scenario, - monkeypatch: pytest.MonkeyPatch, -) -> None: - """The merge waits for the saved policy first; the split joins the cycle later. - - Re-pointing the mapping is slowed by 0.7 seconds, as a remote database's - round trips might slow the statements between locking the copy and - saving the owner's dynamic. The merge, holding the browser user's lock, - moves the saved policy meanwhile. It must commit, and the split must - give the account the saved dynamic. - """ - scenario = us_scenario - old_copy_id = _store_policy( - owner_sessions, - scenario, - scenario.parameter_value(US_TAX_RATE, value=0.3), - scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), - ) - legacy_policy_id = _store_mapping(owner_sessions, scenario, policy_id=old_copy_id) - browser_user_id = _store_user(owner_sessions, scenario) - account_user_id = _store_user(owner_sessions, scenario) - saved_policy_id = _store_saved_policy( - owner_sessions, - scenario, - user_id=browser_user_id, - policy_id=old_copy_id, - legacy_policy_id=legacy_policy_id, - name="Saved before signing in", - ) - repoint_mapping = split_services.repoint_legacy_policy_mapping - - def slow_repoint_mapping(*arguments: object, **keywords: object) -> None: - time.sleep(0.7) - repoint_mapping(*arguments, **keywords) - - monkeypatch.setattr( - split_services, "repoint_legacy_policy_mapping", slow_repoint_mapping - ) - service = V2PolicyCopySplitService( - ActingAsTheSplitRole(time_limited_sessions), - attempts=10, - retry_delay_seconds=0.2, - ) - split_results: list[PolicyCopySplit] = [] - split_errors: list[Exception] = [] - - def run_split() -> None: - try: - split_results.extend(service.split_policy_copies()) - except DBAPIError as error: - split_errors.append(error) - - split_thread = threading.Thread(target=run_split) - with owner_sessions() as sign_in_session: - sign_in_session.exec( - select(User).where(User.id == browser_user_id).with_for_update() - ).one() - split_thread.start() - # The split is re-pointing the mapping, slowly, when the merge moves - # the browser's saved policies. - time.sleep(0.15) - sign_in_session.execute( - update(UserPolicy) - .where(col(UserPolicy.user_id) == browser_user_id) - .values(user_id=account_user_id) - ) - sign_in_session.commit() - split_thread.join(timeout=60) - - assert not split_thread.is_alive() - assert split_errors == [] - split = _result_for(split_results, old_copy_id) - assert split.outcome is PolicyCopyOutcome.DELETED - with owner_sessions() as session: - saved_policy = session.get(UserPolicy, saved_policy_id) - assert (saved_policy.user_id, saved_policy.policy_id) == ( - account_user_id, - split.policy.id, - ) - [saved_dynamic] = _saved_dynamics(owner_sessions, account_user_id) - assert saved_dynamic.dynamic_id == split.dynamic.id - - -def test_a_mapping_s_dynamic_on_another_catalog_version_refuses_the_copy( - owner_sessions: sessionmaker[Session], - split_role_sessions: sessionmaker[Session], - uk_scenario: Scenario, -) -> None: - scenario = uk_scenario - old_copy_id = _store_policy( - owner_sessions, - scenario, - scenario.parameter_value(UK_TAX_RATE, value=0.21), - scenario.parameter_value(UK_OBR_SWITCH, value=False), - ) - other_version = _store_other_version( - owner_sessions, scenario, [UK_INCOME_ELASTICITY] - ) - earlier_dynamic_id = _store_dynamic( - owner_sessions, - other_version, - other_version.parameter_value(UK_INCOME_ELASTICITY, value=0.1), - ) - legacy_policy_id = _store_mapping( - owner_sessions, scenario, policy_id=old_copy_id, dynamic_id=earlier_dynamic_id - ) - - split = _result_for( - list(_service(split_role_sessions).split_policy_copies()), old_copy_id - ) - - assert split.outcome is PolicyCopyOutcome.REFUSED - assert split.refusal_reason is PolicyCopyRefusalReason.DYNAMIC_ON_ANOTHER_CATALOG - assert _policy_exists(owner_sessions, old_copy_id) - mapping = _mapping(owner_sessions, scenario, legacy_policy_id) - assert (mapping.policy_id, mapping.dynamic_id) == (old_copy_id, earlier_dynamic_id) - - -def test_the_listing_reports_a_mapping_s_merged_dynamic_as_applying_does( - owner_sessions: sessionmaker[Session], - split_role_sessions: sessionmaker[Session], - listing_sessions: sessionmaker[Session], - uk_scenario: Scenario, -) -> None: - scenario = uk_scenario - old_copy_id = _store_policy( - owner_sessions, - scenario, - scenario.parameter_value(UK_TAX_RATE, value=0.21), - scenario.parameter_value(UK_OBR_SWITCH, value=False), - ) - earlier_dynamic_id = _store_dynamic( - owner_sessions, - scenario, - scenario.parameter_value(UK_INCOME_ELASTICITY, value=0.1), - ) - _store_mapping( - owner_sessions, scenario, policy_id=old_copy_id, dynamic_id=earlier_dynamic_id - ) - - listed = _result_for( - _listing_service(listing_sessions).list_policy_copy_splits(), old_copy_id - ) - applied = _result_for( - list(_service(split_role_sessions).split_policy_copies()), old_copy_id - ) - - [listed_mapping] = listed.mappings - [applied_mapping] = applied.mappings - assert listed_mapping.previous_dynamic_id == earlier_dynamic_id - assert (listed_mapping.dynamic.id, listed_mapping.dynamic.created) == (None, True) - assert listed_mapping.dynamic.content_hash == applied_mapping.dynamic.content_hash - assert listed_mapping.dynamic.content_hash != listed.dynamic.content_hash - assert applied_mapping.dynamic.created - - -def test_a_copy_a_household_calculation_names_is_kept( - owner_sessions: sessionmaker[Session], - split_role_sessions: sessionmaker[Session], - us_scenario: Scenario, -) -> None: - scenario = us_scenario - old_copy_id = _store_policy( - owner_sessions, - scenario, - scenario.parameter_value(US_TAX_RATE, value=0.3), - scenario.parameter_value(US_INCOME_ELASTICITY, value=0.25), - ) - with owner_sessions() as session: - household = Household( - household_data={"people": {"you": {}}}, - country_id="us", - canonicalization_version=1, - content_hash=uuid4().hex * 2, - ) - session.add(household) - session.flush() - household_job = HouseholdJob( - country="us", - household_id=household.id, - year=2026, - request_data={}, - policy_id=old_copy_id, - tax_benefit_model_version_id=scenario.version_id, - country_package_version="1.0.0", - policyengine_version=CATALOG_VERSION, - ) - session.add(household_job) - session.commit() - scenario.household_ids.append(household.id) - - split = _result_for( - list(_service(split_role_sessions).split_policy_copies()), old_copy_id - ) - - assert split.outcome is PolicyCopyOutcome.KEPT - assert ( - split.references.simulations, - split.references.reports, - split.references.household_jobs, - ) == (0, 0, 1) - assert _policy_exists(owner_sessions, old_copy_id) diff --git a/tests/unit/test_split_v2_policy_copies_script.py b/tests/unit/test_split_v2_policy_copies_script.py deleted file mode 100644 index 2385b342d..000000000 --- a/tests/unit/test_split_v2_policy_copies_script.py +++ /dev/null @@ -1,363 +0,0 @@ -"""Tests for the command that splits stored policy copies holding model assumptions. - -The command only reads unless given ``--apply``. Each copy's report names the -old copy, its policy and dynamic, every legacy mapping and saved policy it -re-points and every saved dynamic it adds, so C1 · 49's operator can compare -the run with a backup. -""" - -from __future__ import annotations - -import subprocess -import sys -from contextlib import contextmanager -from typing import TYPE_CHECKING -from uuid import UUID - -import pytest -from sqlalchemy.orm import sessionmaker - -from policyengine_api.constants import REPO -from policyengine_api.data.v2.settings import ( - V2_POLICY_COPY_SPLIT_DATABASE_URL, - V2_SUPABASE_ENVIRONMENT, - V2_SUPABASE_PROJECT_REF, - V2ConfigurationError, -) -from policyengine_api.services.v2.policy_copy_split.types import ( - CopyReferences, - PolicyCopyOutcome, - PolicyCopyRefusalReason, - PolicyCopySplit, - RepointedMapping, - RepointedSavedPolicy, - SplitContent, -) -from scripts import split_v2_policy_copies - -if TYPE_CHECKING: - from collections.abc import Iterator - -OLD_COPY_ID = UUID("00000000-0000-0000-0000-0000000c0001") -SPLIT_POLICY_ID = UUID("00000000-0000-0000-0000-0000000c0002") -SPLIT_DYNAMIC_ID = UUID("00000000-0000-0000-0000-0000000c0003") -EARLIER_DYNAMIC_ID = UUID("00000000-0000-0000-0000-0000000c0004") -MERGED_DYNAMIC_ID = UUID("00000000-0000-0000-0000-0000000c0005") -SAVED_POLICY_ID = UUID("00000000-0000-0000-0000-0000000c0006") -SAVED_DYNAMIC_ID = UUID("00000000-0000-0000-0000-0000000c0007") -POLICY_HASH = "1" * 64 -DYNAMIC_HASH = "2" * 64 -MERGED_HASH = "3" * 64 -NO_REFERENCES = CopyReferences(simulations=0, reports=0, household_jobs=0) - - -def _split( - *, - applied: bool, - outcome: PolicyCopyOutcome = PolicyCopyOutcome.DELETED, - references: CopyReferences = NO_REFERENCES, - refusal_reason: PolicyCopyRefusalReason | None = None, -) -> PolicyCopySplit: - """One UK copy: a mapping that already named a dynamic, and one saved policy.""" - if refusal_reason is not None: - return PolicyCopySplit( - old_policy_id=OLD_COPY_ID, - country_id="uk", - policyengine_version="2.174.1", - applied=applied, - outcome=PolicyCopyOutcome.REFUSED, - policy=None, - dynamic=None, - mappings=(), - saved_policies=(), - references=references, - refusal_reason=refusal_reason, - ) - merged = SplitContent( - id=MERGED_DYNAMIC_ID if applied else None, - content_hash=MERGED_HASH, - created=True, - ) - return PolicyCopySplit( - old_policy_id=OLD_COPY_ID, - country_id="uk", - policyengine_version="2.174.1", - applied=applied, - outcome=outcome, - policy=SplitContent( - id=SPLIT_POLICY_ID, content_hash=POLICY_HASH, created=False - ), - dynamic=SplitContent( - id=SPLIT_DYNAMIC_ID if applied else None, - content_hash=DYNAMIC_HASH, - created=True, - ), - mappings=( - RepointedMapping( - country_id="uk", - legacy_policy_id=1234, - previous_dynamic_id=EARLIER_DYNAMIC_ID, - dynamic=merged, - ), - ), - saved_policies=( - RepointedSavedPolicy( - user_policy_id=SAVED_POLICY_ID, - dynamic=merged, - saved_dynamic_id=SAVED_DYNAMIC_ID if applied else None, - saved_dynamic_created=True, - ), - ), - references=references, - refusal_reason=None, - ) - - -class FakeSplitter: - """Return the given splits and remaining count, recording each call.""" - - def __init__( - self, splits: tuple[PolicyCopySplit, ...], *, remaining_copies: int = 0 - ) -> None: - self.splits = splits - self.remaining_copies = remaining_copies - self.calls: list[str] = [] - - def list_policy_copy_splits(self) -> tuple[PolicyCopySplit, ...]: - self.calls.append("list") - return self.splits - - def split_policy_copies(self) -> Iterator[PolicyCopySplit]: - self.calls.append("split") - yield from self.splits - - def count_policy_copies(self) -> int: - self.calls.append("count") - return self.remaining_copies - - -class RecordingFactory: - """Build the fake splitter, recording whether the command asked to write.""" - - def __init__(self, splitter: FakeSplitter) -> None: - self.splitter = splitter - self.writable: list[bool] = [] - - @contextmanager - def __call__(self, *, writable: bool) -> Iterator[FakeSplitter]: - self.writable.append(writable) - yield self.splitter - - -def test_the_command_only_lists_without_apply(capsys) -> None: - factory = RecordingFactory(FakeSplitter((_split(applied=False),))) - - exit_status = split_v2_policy_copies.main([], splitter_factory=factory) - - output = capsys.readouterr().out - assert exit_status == 0 - assert factory.writable == [False] - assert factory.splitter.calls == ["list"] - assert "Read-only listing: nothing was changed." in output - assert f"Policy copy {OLD_COPY_ID} (uk, catalog version 2.174.1)" in output - assert "would be deleted" in output - assert f"policy {SPLIT_POLICY_ID} (already stored)" in output - assert f"dynamic: would be created (content hash {DYNAMIC_HASH[:12]})" in output - assert "legacy policy uk 1234" in output - assert f"was dynamic {EARLIER_DYNAMIC_ID}" in output - assert f"saved policy {SAVED_POLICY_ID}" in output - assert "1 policy copy sets a model assumption: 1 would be deleted" in output - - -def test_the_command_applies_and_names_every_row_it_changes(capsys) -> None: - factory = RecordingFactory(FakeSplitter((_split(applied=True),))) - - exit_status = split_v2_policy_copies.main(["--apply"], splitter_factory=factory) - - output = capsys.readouterr().out - assert exit_status == 0 - assert factory.writable == [True] - assert factory.splitter.calls == ["split", "count"] - assert f"Policy copy {OLD_COPY_ID} (uk, catalog version 2.174.1): deleted" in ( - output - ) - assert f"policy {SPLIT_POLICY_ID} (already stored)" in output - assert f"dynamic {SPLIT_DYNAMIC_ID} (created)" in output - assert ( - f"legacy policy uk 1234: now policy {SPLIT_POLICY_ID} and dynamic " - f"{MERGED_DYNAMIC_ID} (was dynamic {EARLIER_DYNAMIC_ID})" - ) in output - assert ( - f"saved policy {SAVED_POLICY_ID}: now policy {SPLIT_POLICY_ID}; " - f"saved dynamic {SAVED_DYNAMIC_ID} (created) for dynamic {MERGED_DYNAMIC_ID}" - ) in output - assert "0 stored policies still set a model assumption." in output - - -def test_a_kept_copy_is_reported_and_fails_the_run(capsys) -> None: - references = CopyReferences(simulations=1, reports=2, household_jobs=0) - factory = RecordingFactory( - FakeSplitter( - ( - _split( - applied=True, - outcome=PolicyCopyOutcome.KEPT, - references=references, - ), - ), - remaining_copies=1, - ) - ) - - exit_status = split_v2_policy_copies.main(["--apply"], splitter_factory=factory) - - output = capsys.readouterr().out - assert exit_status == 1 - assert ( - "kept: named by 1 simulation, 2 reports and 0 household calculations" - ) in output - assert "1 stored policy still sets a model assumption." in output - - -def test_a_listing_with_a_refused_copy_fails(capsys) -> None: - factory = RecordingFactory( - FakeSplitter( - ( - _split( - applied=False, - refusal_reason=PolicyCopyRefusalReason.CONFLICTING_DYNAMIC_VALUES, - ), - ) - ) - ) - - exit_status = split_v2_policy_copies.main([], splitter_factory=factory) - - output = capsys.readouterr().out - assert exit_status == 1 - assert f"Policy copy {OLD_COPY_ID}" in output - assert "would be refused" in output - assert "conflicting_dynamic_values" in output - - -def test_a_listing_with_a_copy_to_keep_fails(capsys) -> None: - factory = RecordingFactory( - FakeSplitter( - ( - _split( - applied=False, - outcome=PolicyCopyOutcome.KEPT, - references=CopyReferences( - simulations=1, reports=0, household_jobs=0 - ), - ), - ) - ) - ) - - assert split_v2_policy_copies.main([], splitter_factory=factory) == 1 - assert "would be kept" in capsys.readouterr().out - - -def test_the_command_says_when_no_policy_sets_a_model_assumption(capsys) -> None: - factory = RecordingFactory(FakeSplitter(())) - - exit_status = split_v2_policy_copies.main([], splitter_factory=factory) - - assert exit_status == 0 - assert "No stored policy sets a model assumption." in capsys.readouterr().out - - -def test_the_command_needs_its_own_database_url(monkeypatch) -> None: - monkeypatch.delenv(V2_POLICY_COPY_SPLIT_DATABASE_URL, raising=False) - - with ( - pytest.raises(V2ConfigurationError, match=V2_POLICY_COPY_SPLIT_DATABASE_URL), - split_v2_policy_copies.splitter_on_temporary_role(writable=False), - ): - pass - - -@pytest.mark.parametrize( - ("run", "expected_opener"), - [("listing", "unpooled_v2_read_only_sessions"), ("apply", "unpooled_v2_sessions")], -) -def test_the_command_lists_read_only_and_bounds_its_waits( - monkeypatch, run: str, expected_opener: str -) -> None: - """The listing's transactions are READ ONLY, and no wait lasts indefinitely. - - The URL gains a connection timeout, and a lock and statement timeout, so - a lock wait can't hold the copy's row lock indefinitely. - """ - from policyengine_api.data.v2 import database - - project_ref = "abcdefghijklmnopqrst" - monkeypatch.setenv( - V2_POLICY_COPY_SPLIT_DATABASE_URL, - f"postgresql+psycopg://policy-copy-split:password@db.{project_ref}." - "supabase.co:5432/postgres?sslmode=require", - ) - monkeypatch.setenv(V2_SUPABASE_PROJECT_REF, project_ref) - monkeypatch.setenv(V2_SUPABASE_ENVIRONMENT, "staging") - opened: list[tuple[str, object]] = [] - - def recording_opener(name: str): - @contextmanager - def open_sessions(url): - opened.append((name, url)) - yield sessionmaker() - - return open_sessions - - for name in ("unpooled_v2_read_only_sessions", "unpooled_v2_sessions"): - monkeypatch.setattr(database, name, recording_opener(name)) - - with split_v2_policy_copies.splitter_on_temporary_role( - writable=run == "apply" - ) as splitter: - assert hasattr(splitter, "split_policy_copies") - - [(opener, url)] = opened - assert opener == expected_opener - assert url.query["connect_timeout"] == "10" - # Shorter than PostgreSQL's default one-second deadlock_timeout, so in a - # lock cycle with a live write the split's wait ends first. - assert url.query["options"] == "-c lock_timeout=500 -c statement_timeout=60000" - assert url.query["sslmode"] == "require" - - -def test_the_command_refuses_unknown_arguments() -> None: - with pytest.raises(SystemExit) as exit_info: - split_v2_policy_copies.main( - ["--dry-run"], splitter_factory=RecordingFactory(FakeSplitter(())) - ) - - assert exit_info.value.code == 2 - - -def test_loading_the_command_leaves_the_observability_runtime_unbuilt() -> None: - """The command and what its splitter factory loads mustn't build the runtime. - - Importing ``policyengine_api.observability`` builds the process-wide - runtime, which adds a root log handler and writes to the command's output. - """ - import_check = ( - "import sys\n" - "import scripts.split_v2_policy_copies\n" - "import policyengine_api.data.v2.database\n" - "import policyengine_api.services.v2.policy_copy_split.database_session\n" - "import policyengine_api.services.v2.policy_copy_split.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 c61cba46b..88f2dd866 100644 --- a/tests/unit/test_v2_integration_workflow.py +++ b/tests/unit/test_v2_integration_workflow.py @@ -89,13 +89,3 @@ def test_the_job_publishes_selected_folders_of_the_installed_models() -> None: "uv run --frozen --extra dev python scripts/reconcile_v2_privileges.py verify" ) < commands.index(step["run"]) assert (REPO / INSTALLED_FOLDERS_TEST).exists() - - -def test_the_job_runs_the_policy_copy_split_as_its_temporary_role() -> None: - """The split command's Postgres tests run, as the role C1 · 49 creates.""" - commands = _step_commands(_runtime_job()) - - assert any( - "tests/integration/test_v2_policy_copy_splits.py" in command - for command in commands - ) diff --git a/tests/unit/v2/test_policy_copy_split_retries.py b/tests/unit/v2/test_policy_copy_split_retries.py deleted file mode 100644 index 168e6531c..000000000 --- a/tests/unit/v2/test_policy_copy_split_retries.py +++ /dev/null @@ -1,116 +0,0 @@ -"""The split gives way to API v1's live writes: a copy that waits too long is retried. - -The command's lock timeout (500 ms) is shorter than PostgreSQL's default -one-second deadlock_timeout, so in a lock cycle with a live write the -split's wait ends first. The service then rolls back that copy's -transaction and tries it again, so the live write goes ahead. -""" - -from __future__ import annotations - -from contextlib import contextmanager -from typing import TYPE_CHECKING -from uuid import UUID - -import psycopg.errors -import pytest -from sqlalchemy.exc import OperationalError - -from policyengine_api.services.v2.policy_copy_split import services -from policyengine_api.services.v2.policy_copy_split.services import ( - V2PolicyCopySplitService, -) - -if TYPE_CHECKING: - from collections.abc import Iterator - -COPY_ID = UUID("00000000-0000-0000-0000-0000000d0001") -SPLIT_RESULT = object() - - -class RecordingDatabaseSession: - """Count the transactions the service opens; each yields a stand-in session.""" - - def __init__(self) -> None: - self.transactions = 0 - - @contextmanager - def read(self) -> Iterator[object]: - yield object() - - @contextmanager - def transaction(self) -> Iterator[object]: - self.transactions += 1 - yield object() - - -def _lock_error(error_type: type[Exception]) -> OperationalError: - return OperationalError("SELECT 1", {}, error_type("waited too long")) - - -@pytest.fixture -def one_copy(monkeypatch) -> None: - monkeypatch.setattr(services, "read_policy_copy_ids", lambda _session: (COPY_ID,)) - - -def _split_failing(monkeypatch, *errors: Exception) -> list[UUID]: - """Make each copy's split raise ``errors`` in turn, then succeed.""" - remaining_errors = list(errors) - attempts: list[UUID] = [] - - def split(_session: object, policy_id: UUID) -> object: - attempts.append(policy_id) - if remaining_errors: - raise remaining_errors.pop(0) - return SPLIT_RESULT - - monkeypatch.setattr(services, "split_policy_copy_in_session", split) - return attempts - - -@pytest.mark.usefixtures("one_copy") -@pytest.mark.parametrize( - "error_type", - [psycopg.errors.LockNotAvailable, psycopg.errors.DeadlockDetected], -) -def test_a_copy_that_meets_a_lock_conflict_is_tried_again( - monkeypatch, error_type: type[Exception] -) -> None: - attempts = _split_failing(monkeypatch, _lock_error(error_type)) - database_session = RecordingDatabaseSession() - waits: list[float] = [] - service = V2PolicyCopySplitService( - database_session, retry_delay_seconds=0.25, sleep=waits.append - ) - - assert list(service.split_policy_copies()) == [SPLIT_RESULT] - assert attempts == [COPY_ID, COPY_ID] - assert database_session.transactions == 2 - assert waits == [0.25] - - -@pytest.mark.usefixtures("one_copy") -def test_a_copy_still_in_conflict_after_every_attempt_fails_the_run( - monkeypatch, -) -> None: - lock_errors = [_lock_error(psycopg.errors.LockNotAvailable) for _ in range(3)] - attempts = _split_failing(monkeypatch, *lock_errors) - service = V2PolicyCopySplitService( - RecordingDatabaseSession(), attempts=3, sleep=lambda _seconds: None - ) - - with pytest.raises(OperationalError, match="waited too long"): - list(service.split_policy_copies()) - assert attempts == [COPY_ID] * 3 - - -@pytest.mark.usefixtures("one_copy") -def test_another_database_error_is_not_retried(monkeypatch) -> None: - attempts = _split_failing(monkeypatch, _lock_error(psycopg.errors.UndefinedTable)) - service = V2PolicyCopySplitService( - RecordingDatabaseSession(), sleep=lambda _seconds: None - ) - - with pytest.raises(OperationalError): - list(service.split_policy_copies()) - assert attempts == [COPY_ID] diff --git a/tests/unit/v2/test_policy_copy_split_rules.py b/tests/unit/v2/test_policy_copy_split_rules.py deleted file mode 100644 index 1fa066473..000000000 --- a/tests/unit/v2/test_policy_copy_split_rules.py +++ /dev/null @@ -1,314 +0,0 @@ -"""Splitting a stored policy copy, and merging a mapping's dynamic, without a database. - -C1 · 48's command splits each stored policy that sets a model assumption into -a policy and a dynamic on the copy's own catalog version. When a legacy -mapping already names a dynamic, the split-off values join it (the user's -decision 4 of 2026-11-25). -""" - -from __future__ import annotations - -from datetime import UTC, datetime -from uuid import UUID - -import pytest - -from policyengine_api.data.v2.models import ( - Dynamic, - ParameterValue, - Policy, - TaxBenefitModelVersion, -) -from policyengine_api.services.v2.dynamics.types import ResolvedDynamicCreationInput -from policyengine_api.services.v2.policies.transformations import ( - stored_policy_creation_input, -) -from policyengine_api.services.v2.policies.validators import ( - MAXIMUM_POLICY_PARAMETER_VALUES, -) -from policyengine_api.services.v2.policy_copy_split.transformations import ( - split_stored_policy, -) -from policyengine_api.services.v2.policy_copy_split.types import ( - PolicyCopyRefusalReason, -) -from policyengine_api.services.v2.policy_copy_split.validators import ( - PolicyCopySplitRefusedError, - merge_dynamic_content, -) - -MODEL_ID = UUID("00000000-0000-0000-0000-00000000a001") -MODEL_VERSION_ID = UUID("00000000-0000-0000-0000-00000000a002") -OTHER_MODEL_VERSION_ID = UUID("00000000-0000-0000-0000-00000000a003") -POLICY_ID = UUID("00000000-0000-0000-0000-00000000a004") -DYNAMIC_ID = UUID("00000000-0000-0000-0000-00000000a005") -TAX_RATE_ID = UUID("00000000-0000-0000-0000-00000000b001") -OBR_SWITCH_ID = UUID("00000000-0000-0000-0000-00000000b002") -INCOME_ELASTICITY_ID = UUID("00000000-0000-0000-0000-00000000b003") -TAX_RATE = "gov.hmrc.income_tax.rates.uk[0].rate" -OBR_SWITCH = "gov.dynamic.obr_labour_supply_assumptions" -INCOME_ELASTICITY = "gov.simulation.labour_supply_responses.income_elasticity" -START_2026 = datetime(2026, 1, 1, tzinfo=UTC) -END_2026 = datetime(2026, 12, 31, tzinfo=UTC) -CATALOG_VERSION = "2.174.1" - - -def _model_version(model_version_id: UUID = MODEL_VERSION_ID) -> TaxBenefitModelVersion: - return TaxBenefitModelVersion( - id=model_version_id, - model_id=MODEL_ID, - version=CATALOG_VERSION, - current_law_id=1, - metadata_time_periods=[2026], - ) - - -def _stored_policy(country_id: str = "uk") -> Policy: - return Policy( - id=POLICY_ID, - country_id=country_id, - tax_benefit_model_id=MODEL_ID, - tax_benefit_model_version_id=MODEL_VERSION_ID, - canonicalization_version=1, - content_hash="a" * 64, - ) - - -def _stored_value( - parameter_id: UUID, - *, - value: object, - start_date: datetime = START_2026, - end_date: datetime | None = END_2026, - dynamic_id: UUID | None = None, -) -> ParameterValue: - """Return a stored value of the old copy, or of the dynamic `dynamic_id` names.""" - return ParameterValue( - parameter_id=parameter_id, - value_json=value, - start_date=start_date, - end_date=end_date, - policy_id=None if dynamic_id is not None else POLICY_ID, - dynamic_id=dynamic_id, - ) - - -def _stored_dynamic(model_version_id: UUID = MODEL_VERSION_ID) -> Dynamic: - return Dynamic( - id=DYNAMIC_ID, - country_id="uk", - tax_benefit_model_id=MODEL_ID, - tax_benefit_model_version_id=model_version_id, - canonicalization_version=1, - content_hash="b" * 64, - ) - - -def _existing_dynamic( - *values: ParameterValue, model_version_id: UUID = MODEL_VERSION_ID -) -> object: - return stored_policy_creation_input( - _stored_dynamic(model_version_id), - _model_version(model_version_id), - list(values), - ) - - -def _uk_split_off_dynamic(*values: ParameterValue) -> ResolvedDynamicCreationInput: - split = split_stored_policy( - _stored_policy(), - _model_version(), - [(value, OBR_SWITCH) for value in values], - ) - assert split is not None - return split.dynamic - - -def _value_triples(content: object) -> set[tuple[UUID, object, datetime | None]]: - return { - (value.parameter_id, value.value, value.end_date) - for value in content.parameter_values - } - - -def test_a_copy_is_split_on_its_own_catalog_version_keeping_its_values() -> None: - split = split_stored_policy( - _stored_policy(), - _model_version(), - [ - (_stored_value(TAX_RATE_ID, value=0.21), TAX_RATE), - (_stored_value(OBR_SWITCH_ID, value=False), OBR_SWITCH), - ( - _stored_value(INCOME_ELASTICITY_ID, value=0.1, end_date=None), - INCOME_ELASTICITY, - ), - ], - ) - - assert split is not None - for content in (split.policy, split.dynamic): - assert content.country_id == "uk" - assert content.tax_benefit_model_id == MODEL_ID - assert content.tax_benefit_model_version_id == MODEL_VERSION_ID - assert content.policyengine_version == CATALOG_VERSION - assert _value_triples(split.policy) == {(TAX_RATE_ID, 0.21, END_2026)} - assert isinstance(split.dynamic, ResolvedDynamicCreationInput) - assert _value_triples(split.dynamic) == { - (OBR_SWITCH_ID, False, END_2026), - (INCOME_ELASTICITY_ID, 0.1, None), - } - assert {value.start_date for value in split.dynamic.parameter_values} == { - START_2026 - } - - -def test_a_copy_holding_only_model_assumptions_splits_into_an_empty_policy() -> None: - split = split_stored_policy( - _stored_policy(), - _model_version(), - [(_stored_value(OBR_SWITCH_ID, value=False), OBR_SWITCH)], - ) - - assert split is not None - assert split.policy.parameter_values == [] - assert _value_triples(split.dynamic) == {(OBR_SWITCH_ID, False, END_2026)} - - -def test_a_copy_setting_no_model_assumption_is_not_split() -> None: - assert ( - split_stored_policy( - _stored_policy(), - _model_version(), - [(_stored_value(TAX_RATE_ID, value=0.21), TAX_RATE)], - ) - is None - ) - - -SPLIT_OFF_SWITCH = {(OBR_SWITCH_ID, 1, END_2026)} - - -@pytest.mark.parametrize( - ("country_id", "parameter_name", "expected_dynamic_values"), - [ - ("us", "simulation.marginal_tax_rate_delta", SPLIT_OFF_SWITCH), - ( - "us", - "gov.simulation.labor_supply_responses.elasticities.income", - SPLIT_OFF_SWITCH, - ), - ("us", OBR_SWITCH, None), - ("uk", OBR_SWITCH, SPLIT_OFF_SWITCH), - ("uk", "simulation.marginal_tax_rate_delta", None), - ], -) -def test_each_country_s_prefixes_decide_what_is_split_off( - country_id: str, - parameter_name: str, - expected_dynamic_values: set[tuple[UUID, object, datetime]] | None, -) -> None: - split = split_stored_policy( - _stored_policy(country_id), - _model_version(), - [ - (_stored_value(TAX_RATE_ID, value=0.21), TAX_RATE), - (_stored_value(OBR_SWITCH_ID, value=1), parameter_name), - ], - ) - - if expected_dynamic_values is None: - assert split is None - else: - assert split is not None - assert _value_triples(split.dynamic) == expected_dynamic_values - - -def test_a_mapping_s_dynamic_and_the_split_off_values_merge_into_one() -> None: - merged = merge_dynamic_content( - _existing_dynamic( - _stored_value(INCOME_ELASTICITY_ID, value=0.1, dynamic_id=DYNAMIC_ID) - ), - _uk_split_off_dynamic(_stored_value(OBR_SWITCH_ID, value=False)), - ) - - assert isinstance(merged, ResolvedDynamicCreationInput) - assert merged.tax_benefit_model_version_id == MODEL_VERSION_ID - assert merged.policyengine_version == CATALOG_VERSION - assert _value_triples(merged) == { - (INCOME_ELASTICITY_ID, 0.1, END_2026), - (OBR_SWITCH_ID, False, END_2026), - } - - -def test_a_value_both_dynamics_set_identically_is_kept_once() -> None: - merged = merge_dynamic_content( - _existing_dynamic( - _stored_value(OBR_SWITCH_ID, value=False, dynamic_id=DYNAMIC_ID) - ), - _uk_split_off_dynamic(_stored_value(OBR_SWITCH_ID, value=False)), - ) - - assert _value_triples(merged) == {(OBR_SWITCH_ID, False, END_2026)} - - -@pytest.mark.parametrize( - ("existing_value", "existing_end_date"), - [ - pytest.param(True, END_2026, id="different-value"), - # JSON true and 0 or 1 are different values, though Python compares - # True equal to 1. - pytest.param(0, END_2026, id="integer-for-boolean"), - pytest.param(False, None, id="different-end-date"), - ], -) -def test_a_value_the_two_dynamics_set_differently_refuses_the_copy( - existing_value: object, existing_end_date: datetime | None -) -> None: - with pytest.raises(PolicyCopySplitRefusedError) as refusal: - merge_dynamic_content( - _existing_dynamic( - _stored_value( - OBR_SWITCH_ID, - value=existing_value, - end_date=existing_end_date, - dynamic_id=DYNAMIC_ID, - ) - ), - _uk_split_off_dynamic(_stored_value(OBR_SWITCH_ID, value=False)), - ) - - assert refusal.value.reason is PolicyCopyRefusalReason.CONFLICTING_DYNAMIC_VALUES - - -def test_a_mapping_s_dynamic_on_another_catalog_version_refuses_the_copy() -> None: - with pytest.raises(PolicyCopySplitRefusedError) as refusal: - merge_dynamic_content( - _existing_dynamic( - _stored_value(INCOME_ELASTICITY_ID, value=0.1, dynamic_id=DYNAMIC_ID), - model_version_id=OTHER_MODEL_VERSION_ID, - ), - _uk_split_off_dynamic(_stored_value(OBR_SWITCH_ID, value=False)), - ) - - assert refusal.value.reason is PolicyCopyRefusalReason.DYNAMIC_ON_ANOTHER_CATALOG - - -def test_a_merged_dynamic_over_the_value_limit_refuses_the_copy() -> None: - existing_values = [ - _stored_value( - INCOME_ELASTICITY_ID, - value=0.1, - start_date=datetime(2026, 1, 1, tzinfo=UTC).replace(year=1000 + index), - end_date=None, - dynamic_id=DYNAMIC_ID, - ) - for index in range(MAXIMUM_POLICY_PARAMETER_VALUES) - ] - - with pytest.raises(PolicyCopySplitRefusedError) as refusal: - merge_dynamic_content( - _existing_dynamic(*existing_values), - _uk_split_off_dynamic(_stored_value(OBR_SWITCH_ID, value=False)), - ) - - assert refusal.value.reason is PolicyCopyRefusalReason.TOO_MANY_VALUES diff --git a/tests/unit/v2/test_policy_copy_split_runbook.py b/tests/unit/v2/test_policy_copy_split_runbook.py deleted file mode 100644 index 64c2db503..000000000 --- a/tests/unit/v2/test_policy_copy_split_runbook.py +++ /dev/null @@ -1,92 +0,0 @@ -"""The split command's runbook creates the role the command's grants declare. - -C1 · 49's operator creates a temporary role from the runbook's SQL in -``docs/migration/stage-10-v2-policies.md``, so its GRANTs must be exactly the -ones ``POLICY_COPY_SPLIT_PRIVILEGES`` declares. -""" - -from __future__ import annotations - -import re -from pathlib import Path - -from policyengine_api.data.v2.privilege_plans import ( - GrantedPrivileges, - grant_statements, - plan_reconciliation, -) -from policyengine_api.data.v2.privileges import ( - POLICY_COPY_SPLIT_PRIVILEGES, - POLICY_COPY_SPLIT_ROLE, -) - -RUNBOOK = Path(__file__).parents[3] / "docs/migration/stage-10-v2-policies.md" -SQL_BLOCK = re.compile(r"```sql\n(.*?)```", re.DOTALL) -TABLE_GRANT = re.compile(r"^\s*(GRANT .+ ON TABLE .+?);?\s*$") - - -def _runbook_sql_blocks() -> list[str]: - return SQL_BLOCK.findall(RUNBOOK.read_text(encoding="utf-8")) - - -def _block_containing(text: str) -> str: - [block] = [block for block in _runbook_sql_blocks() if text in block] - return block - - -def _declared_grants() -> list[str]: - plan = plan_reconciliation( - {POLICY_COPY_SPLIT_ROLE: POLICY_COPY_SPLIT_PRIVILEGES}, - GrantedPrivileges(tables={}, columns={}), - existing_roles={POLICY_COPY_SPLIT_ROLE}, - existing_tables=set(POLICY_COPY_SPLIT_PRIVILEGES), - ) - return sorted(grant_statements(plan, lambda identifier: identifier)) - - -def test_the_runbook_grants_the_role_exactly_its_declared_privileges() -> None: - creation = _block_containing(f"CREATE ROLE {POLICY_COPY_SPLIT_ROLE}") - - runbook_grants = sorted( - match.group(1) - for statement in creation.splitlines() - if (match := TABLE_GRANT.match(statement)) - ) - - assert runbook_grants == _declared_grants() - - -def test_the_runbook_creates_a_login_role_with_no_other_powers() -> None: - creation = _block_containing(f"CREATE ROLE {POLICY_COPY_SPLIT_ROLE}") - - assert ( - f"CREATE ROLE {POLICY_COPY_SPLIT_ROLE} LOGIN NOSUPERUSER NOCREATEDB " - "NOCREATEROLE NOREPLICATION NOBYPASSRLS NOINHERIT PASSWORD" - ) in creation - assert f"GRANT USAGE ON SCHEMA public TO {POLICY_COPY_SPLIT_ROLE};" in creation - assert creation.lstrip().startswith("DO $$") - - -def test_the_runbook_revokes_every_grant_then_drops_the_role() -> None: - """A login that isn't a superuser can run it. - - ``DROP OWNED BY`` needs the target role's own privileges, which the - CREATEROLE login that created the role lacks on PostgreSQL 16 and later, - so the role's grants are revoked one by one before ``DROP ROLE``. - """ - removal = _block_containing(f"DROP ROLE {POLICY_COPY_SPLIT_ROLE}") - - table_revoke = re.compile( - rf"^\s*REVOKE ALL ON TABLE public\.(\w+) FROM {POLICY_COPY_SPLIT_ROLE};$" - ) - revoked_tables = sorted( - match.group(1) - for statement in removal.splitlines() - if (match := table_revoke.match(statement)) - ) - - assert revoked_tables == sorted(POLICY_COPY_SPLIT_PRIVILEGES) - assert f"REVOKE USAGE ON SCHEMA public FROM {POLICY_COPY_SPLIT_ROLE};" in removal - assert "DROP OWNED BY" not in removal - assert removal.rindex("REVOKE") < removal.index("DROP ROLE") - assert removal.lstrip().startswith("DO $$") diff --git a/tests/unit/v2/test_privilege_manifest.py b/tests/unit/v2/test_privilege_manifest.py index 6d3e52113..25adbf971 100644 --- a/tests/unit/v2/test_privilege_manifest.py +++ b/tests/unit/v2/test_privilege_manifest.py @@ -23,8 +23,6 @@ CATALOG_WRITER_ROLE, MODAL_WORKER_ROLE, NO_ACCESS, - POLICY_COPY_SPLIT_PRIVILEGES, - POLICY_COPY_SPLIT_ROLE, READ, READ_INSERT, READ_INSERT_DELETE, @@ -47,9 +45,6 @@ SERVICES_ROOT = PROJECT_ROOT / "policyengine_api" / "services" / "v2" PROOF_FIXTURES = PROJECT_ROOT / "rules/fixtures/api.v2.runtime-privileges-declared" STAGE12_PACKAGES = frozenset({"comparison_runs"}) -# Run once, by hand, as a temporary role the operator creates with -# POLICY_COPY_SPLIT_PRIVILEGES (C1 · 48 and C1 · 49), never as a managed role. -POLICY_COPY_SPLIT_PACKAGES = frozenset({"policy_copy_split"}) TEST_ENVIRONMENT = "staging" # The rows the simulation service creates, and the run tables among them. A # simulation run's cliff calculation is started and finished like a run. @@ -207,24 +202,12 @@ def _connector_modules(*, stage12: bool) -> list[str]: path.relative_to(SERVICES_ROOT).as_posix() for path in SERVICES_ROOT.glob("*/database_connectors/*.py") if path.name != "__init__.py" - and path.parts[-3] not in POLICY_COPY_SPLIT_PACKAGES and (path.parts[-3] in STAGE12_PACKAGES) is stage12 ) assert paths, "no connector modules found" return paths -def _policy_copy_split_connector_modules() -> list[str]: - paths = sorted( - path.relative_to(SERVICES_ROOT).as_posix() - for package in POLICY_COPY_SPLIT_PACKAGES - for path in (SERVICES_ROOT / package / "database_connectors").glob("*.py") - if path.name != "__init__.py" - ) - assert paths, "no policy copy split connector modules found" - return paths - - def _missing(relative_path: str, role: str) -> list[str]: requirements = required_privileges( SERVICES_ROOT / relative_path, _table_by_model(), connector=relative_path @@ -286,72 +269,6 @@ def test_stage12_connectors_need_only_declared_stage12_privileges( assert _missing(relative_path, stage12_role(TEST_ENVIRONMENT)) == [] -@pytest.mark.parametrize("relative_path", _policy_copy_split_connector_modules()) -def test_policy_copy_split_connectors_need_only_the_temporary_role_s_privileges( - relative_path: str, -) -> None: - requirements = required_privileges( - SERVICES_ROOT / relative_path, _table_by_model(), connector=relative_path - ) - - assert requirements, "the analysis found no table this connector uses" - assert [ - f"{missing.connector}: {missing.privilege} on {missing.table_name} " - f"({missing.reason})" - for missing in undeclared_requirements( - requirements, POLICY_COPY_SPLIT_PRIVILEGES - ) - ] == [] - - -def test_the_policy_copy_split_role_deletes_only_policies_and_is_not_managed() -> None: - """The split command's temporary role changes only what the split must change. - - It deletes old policy copies (their values go with them by the foreign - key's cascade), locks them, re-points legacy mappings and saved policies, - and inserts policies, dynamics, their values and saved dynamics. It reads - the catalog and the simulations, reports and household calculations that - may name a copy. No deploy grants it anything: the operator creates it for - C1 · 49 and drops it afterwards. - """ - write_privileges = { - table: privileges & WRITE_PRIVILEGES - for table, privileges in POLICY_COPY_SPLIT_PRIVILEGES.items() - if privileges & WRITE_PRIVILEGES - } - - assert write_privileges == { - "dynamics": {TablePrivilege.INSERT}, - "legacy_policy_mappings": {TablePrivilege.UPDATE}, - "parameter_values": {TablePrivilege.INSERT}, - "policies": { - TablePrivilege.INSERT, - TablePrivilege.UPDATE, - TablePrivilege.DELETE, - }, - "user_dynamics": {TablePrivilege.INSERT}, - "user_policies": {TablePrivilege.UPDATE}, - } - assert { - table - for table, privileges in POLICY_COPY_SPLIT_PRIVILEGES.items() - if privileges == READ - } == { - "household_jobs", - "parameters", - "reports", - "simulations", - "tax_benefit_model_versions", - } - assert set(POLICY_COPY_SPLIT_PRIVILEGES) <= set(TABLE_ACCESS) - assert all( - TablePrivilege.SELECT in privileges - for privileges in POLICY_COPY_SPLIT_PRIVILEGES.values() - ) - assert POLICY_COPY_SPLIT_ROLE == "policyengine_v2_policy_copy_split" - assert POLICY_COPY_SPLIT_ROLE not in declared_privileges(TEST_ENVIRONMENT) - - def test_stage12_role_name_follows_the_deployment_environment() -> None: assert stage12_role("staging") == "policyengine_stage12_staging" assert stage12_role("production") == "policyengine_stage12_production" diff --git a/tests/unit/v2/test_settings.py b/tests/unit/v2/test_settings.py index 0d24cad36..8a0f03bb8 100644 --- a/tests/unit/v2/test_settings.py +++ b/tests/unit/v2/test_settings.py @@ -5,7 +5,6 @@ from policyengine_api.data.v2.settings import ( V2_DATA_WRITE_DATABASE_URL, V2_MIGRATION_DATABASE_URL, - V2_POLICY_COPY_SPLIT_DATABASE_URL, V2_RUNTIME_DATABASE_URL, V2_RUNTIME_DATABASE_URL_SECRET_RESOURCE, V2_SUPABASE_ENVIRONMENT, @@ -13,7 +12,6 @@ V2ConfigurationError, load_v2_data_write_database_settings, load_v2_migration_database_settings, - load_v2_policy_copy_split_database_settings, load_v2_runtime_database_settings, ) @@ -57,27 +55,6 @@ def test_runtime_migration_and_data_write_urls_are_explicit_and_separate() -> No assert runtime.target == migration.target == data_write.target -def test_the_policy_copy_split_url_is_its_own_setting() -> None: - """The split command connects as C1 · 49's temporary role, by its own URL.""" - split_url = ( - f"postgresql+psycopg://policy-copy-split:test-split-password@db.{PROJECT_REF}." - "supabase.co:5432/postgres?sslmode=require" - ) - environment = { - **TARGET_ENVIRONMENT, - V2_MIGRATION_DATABASE_URL: MIGRATION_URL, - V2_POLICY_COPY_SPLIT_DATABASE_URL: split_url, - } - - settings = load_v2_policy_copy_split_database_settings(environment) - - assert settings.connection.url.username == "policy-copy-split" - with pytest.raises(V2ConfigurationError, match=V2_POLICY_COPY_SPLIT_DATABASE_URL): - load_v2_policy_copy_split_database_settings( - {**TARGET_ENVIRONMENT, V2_MIGRATION_DATABASE_URL: MIGRATION_URL} - ) - - def test_postgres_password_is_hidden_from_string_and_repr() -> None: settings = load_v2_runtime_database_settings( {**TARGET_ENVIRONMENT, V2_RUNTIME_DATABASE_URL: RUNTIME_URL} @@ -197,10 +174,6 @@ def test_runtime_rejects_non_persistent_postgres_targets(url: str) -> None: (V2_RUNTIME_DATABASE_URL, load_v2_runtime_database_settings), (V2_MIGRATION_DATABASE_URL, load_v2_migration_database_settings), (V2_DATA_WRITE_DATABASE_URL, load_v2_data_write_database_settings), - ( - V2_POLICY_COPY_SPLIT_DATABASE_URL, - load_v2_policy_copy_split_database_settings, - ), ], ) def test_every_database_url_must_identify_the_configured_supabase_project( @@ -248,21 +221,6 @@ def test_runtime_rejects_transaction_pooling_without_session_timeouts() -> None: ) -def test_the_policy_copy_split_url_refuses_transaction_pooling() -> None: - """Transaction pooling drops the command's lock and statement timeouts.""" - with pytest.raises(V2ConfigurationError, match="session mode on port 5432"): - load_v2_policy_copy_split_database_settings( - { - **TARGET_ENVIRONMENT, - V2_POLICY_COPY_SPLIT_DATABASE_URL: ( - f"postgresql+psycopg://policy-copy-split.{PROJECT_REF}:password@" - "aws-0-us-east-2.pooler.supabase.com:6543/" - "postgres?sslmode=require" - ), - } - ) - - def test_supabase_database_name_must_be_postgres() -> None: with pytest.raises(V2ConfigurationError, match="configured Supabase database"): load_v2_runtime_database_settings( From 682dc090549e927e8817511b30b208c9ccf3a66f Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:22:31 +0400 Subject: [PATCH 02/10] =?UTF-8?q?C1=20=C2=B7=2050:=20tests=20for=20dynamic?= =?UTF-8?q?=20parameters=20in=20their=20own=20tables=20(failing)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Failing tests for tracker task C1 · 50 (API v1): - Revision 7f7335f0eb31 creates dynamic_parameters and dynamic_parameter_values, then moves every stored version's dynamic parameters (US gov.simulation. and simulation., UK gov.simulation. and gov.dynamic.), their current-law values and every dynamic's values there with their IDs, deletes the policy tree's rows under those folders and lowers their parents' child counts, and deletes the originals. It refuses while a policy value names a parameter it would move, keeps its own copy of the prefixes, and its downgrade moves the rows back and leaves the trees (the user's decisions: C1 · 46, Q2, and C1 · 50's decision 1). - A read-only step in seed-v2-database.yml counts the same policy values and stops the deploy first. - Publication writes, compares, restores and prunes both tables, and leaves model assumptions and their folders out of the policy tree and the search file, whose format becomes 2. - Dynamics, the v1-to-v2 copy and the 422s on /v2/policies and /v2/dynamics read the new tables, and the grants cover them. Co-Authored-By: Claude Opus 5.5 --- tests/fixtures/v2_catalog.py | 78 ++ ...est_alembic_v2_dynamic_parameter_tables.py | 937 ++++++++++++++++++ .../test_v2_catalog_publication.py | 4 +- ..._catalog_publication_dynamic_parameters.py | 562 +++++++++++ .../test_v2_catalog_publication_pruning.py | 8 +- .../test_v2_dynamic_persistence.py | 53 +- tests/unit/test_alembic_workflows.py | 1 + tests/unit/test_dynamic_parameters.py | 64 ++ tests/unit/test_v2_integration_workflow.py | 10 + tests/unit/v2/test_alembic_v2_revisions.py | 92 +- tests/unit/v2/test_catalog_publication.py | 49 +- tests/unit/v2/test_dynamic_catalog.py | 144 ++- ...st_dynamic_parameter_move_qualification.py | 127 +++ .../v2/test_dynamic_parameter_table_models.py | 231 +++++ tests/unit/v2/test_import_side_effects.py | 6 +- tests/unit/v2/test_metadata_deployment.py | 23 + .../v2/test_metadata_search_file_routes.py | 6 +- tests/unit/v2/test_metadata_service.py | 4 +- .../test_metadata_service_pruned_versions.py | 2 +- tests/unit/v2/test_parameter_search_file.py | 51 +- tests/unit/v2/test_policy_legacy_copy.py | 56 +- tests/unit/v2/test_privilege_manifest.py | 64 +- 22 files changed, 2522 insertions(+), 50 deletions(-) create mode 100644 tests/integration/test_alembic_v2_dynamic_parameter_tables.py create mode 100644 tests/integration/test_v2_catalog_publication_dynamic_parameters.py create mode 100644 tests/unit/v2/test_dynamic_parameter_move_qualification.py create mode 100644 tests/unit/v2/test_dynamic_parameter_table_models.py diff --git a/tests/fixtures/v2_catalog.py b/tests/fixtures/v2_catalog.py index 05bbf00e1..0e96ccdac 100644 --- a/tests/fixtures/v2_catalog.py +++ b/tests/fixtures/v2_catalog.py @@ -396,3 +396,81 @@ def add_format_2_variable_records(model: SimpleNamespace) -> None: for variable in variables: model.variables.append(variable) model.variables_by_name[variable.name] = variable + + +# Each country's model assumptions (policyengine_api.dynamic_parameters): +# parameter names with their current-law value, and the folders above them, +# with their labels. The US has top-level ``simulation`` and the UK +# ``gov.dynamic``. +DYNAMIC_PARAMETER_RECORDS = { + "us": { + "gov.simulation.labor_supply_responses.elasticities.income": 0.1, + "simulation.marginal_tax_rate_delta": 1_000, + }, + "uk": { + "gov.simulation.labour_supply_responses.income_elasticity": 0.05, + "gov.dynamic.obr_labour_supply_assumptions": True, + }, +} +DYNAMIC_PARAMETER_FOLDERS = { + "us": { + "gov.simulation": "Simulation", + "gov.simulation.labor_supply_responses": "Labor supply responses", + "gov.simulation.labor_supply_responses.elasticities": "Elasticities", + "simulation": "Simulation settings", + }, + "uk": { + "gov.simulation": "Simulation", + "gov.simulation.labour_supply_responses": "Labour supply responses", + "gov.dynamic": "Dynamic", + }, +} + + +def add_dynamic_parameter_records(model: SimpleNamespace, country_id: str) -> None: + """Add the country's model assumptions and their folders to a model fixture. + + Each parameter has one current-law value from 2025 on and both flags set, + as .py gives a parameter whose package sets neither (UK + ``gov.dynamic.obr_labour_supply_assumptions``). + """ + for name, label in DYNAMIC_PARAMETER_FOLDERS[country_id].items(): + node = SimpleNamespace(name=name, label=label, description=None) + model.parameter_nodes.append(node) + model.parameter_nodes_by_name[name] = node + for name, value in DYNAMIC_PARAMETER_RECORDS[country_id].items(): + parameter = SimpleNamespace( + name=name, + label=f"{name.rsplit('.', 1)[-1].replace('_', ' ').capitalize()}", + description=f"The model assumption {name}", + data_type=type(value), + unit=None, + economy=True, + household=True, + parameter_values=[ + SimpleNamespace( + value=value, + start_date=datetime(2025, 1, 1, tzinfo=UTC), + end_date=None, + ) + ], + ) + model.parameters.append(parameter) + model.parameters_by_name[name] = parameter + + +def catalog_with_dynamic_parameters( + *, + policyengine_version: str = POLICYENGINE_VERSION, +) -> NormalizedCatalog: + """Return the normalized fixture with each country's model assumptions.""" + models = source_models(policyengine_version=policyengine_version) + for country_id, model in models.items(): + add_dynamic_parameter_records(model, country_id) + return extract_catalog( + bundle=bundle(policyengine_version=policyengine_version), + policyengine_version=policyengine_version, + models=models, + installed_version=installed_version, + region_references=region_references(), + ) diff --git a/tests/integration/test_alembic_v2_dynamic_parameter_tables.py b/tests/integration/test_alembic_v2_dynamic_parameter_tables.py new file mode 100644 index 000000000..a97d1cec4 --- /dev/null +++ b/tests/integration/test_alembic_v2_dynamic_parameter_tables.py @@ -0,0 +1,937 @@ +"""Check the revision that moves dynamic parameters into their own tables. + +Revision 7f7335f0eb31 creates ``dynamic_parameters`` and +``dynamic_parameter_values``, then moves every stored version's dynamic +parameters (US ``gov.simulation.`` and ``simulation.``, UK ``gov.simulation.`` +and ``gov.dynamic.``), their current-law values and every dynamic's values +there with their IDs, deletes the policy tree's rows under those folders, +lowering their parents' child counts, and deletes the originals. It refuses +to run while a policy value names a parameter it would move. Its downgrade +moves the rows back and leaves the trees as they are (C1 · 46, Q2; C1 · 50's +decision 1). + +The rows are written as the disposable database's owner. A country's +parameters are those of model ``policyengine-``, so the tests store +their own versions of those models, and look only at those versions' rows. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import UTC, datetime +from typing import TYPE_CHECKING, Any +from uuid import UUID, uuid4 + +import pytest +from alembic import command +from policyengine_api.data.v2.dynamic_parameter_move_qualification import ( + count_policy_values_naming_dynamic_parameters, + dynamic_parameter_move_is_pending, +) +from sqlalchemy import delete, select, update +from sqlmodel import col + +from policyengine_api.data.v2.models import ( + Dynamic, + DynamicParameter, + DynamicParameterValue, + Parameter, + ParameterTreeChild, + ParameterValue, + Policy, + TaxBenefitModel, + TaxBenefitModelVersion, +) +from tests.fixtures.database_sessions import schema_inspector +from tests.fixtures.integration.alembic_v2 import alembic_v2_config +from tests.integration.alembic_version_rows import current_revision +from tests.integration.simulation_rows import add_row, refused + +if TYPE_CHECKING: + from collections.abc import Iterator + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + +PARENT_REVISION = "d417fe8b1b17" +DYNAMIC_PARAMETER_TABLES_REVISION = "7f7335f0eb31" +NEW_TABLES = frozenset({"dynamic_parameters", "dynamic_parameter_values"}) +START_2026 = datetime(2026, 1, 1, tzinfo=UTC) +START_2027 = datetime(2027, 1, 1, tzinfo=UTC) + +US_POLICY_PARAMETER = "gov.irs.rate" +# Not a US prefix: only the UK's gov.dynamic. holds model assumptions. +US_GOV_DYNAMIC_POLICY_PARAMETER = "gov.dynamic.example" +US_ELASTICITY = "gov.simulation.labor_supply_responses.elasticity" +US_MTR_DELTA = "simulation.marginal_tax_rate_delta" +UK_POLICY_PARAMETER = "gov.hmrc.rate" +# Not a UK prefix: only the US's top-level simulation. holds model assumptions. +UK_SIMULATION_POLICY_PARAMETER = "simulation.example" +UK_ELASTICITY = "gov.simulation.income_elasticity" +UK_OBR_SWITCH = "gov.dynamic.obr_labour_supply_assumptions" + +POLICY_PARAMETERS = { + "us": (US_POLICY_PARAMETER, US_GOV_DYNAMIC_POLICY_PARAMETER), + "uk": (UK_POLICY_PARAMETER, UK_SIMULATION_POLICY_PARAMETER), +} +DYNAMIC_PARAMETERS = { + "us": (US_ELASTICITY, US_MTR_DELTA), + "uk": (UK_ELASTICITY, UK_OBR_SWITCH), +} + + +@dataclass(frozen=True) +class TreeRow: + """One ``parameter_tree_children`` row a test writes, by its path.""" + + parent_path: str + path: str + position: int + child_count: int | None = None + reform_position: int | None = None + reform_child_count: int | None = None + + @property + def is_parameter(self) -> bool: + return self.child_count is None + + +# Each country's tree before the revision. "gov" has three folders; the US +# top-level "simulation" folder has no parent row. The UK's gov.dynamic is not +# reform-changeable (no reform position), so the UK's "gov" loses one of its +# two reform children. +TREES = { + "us": ( + TreeRow("", "gov", 0, child_count=3, reform_position=0, reform_child_count=3), + TreeRow("", "simulation", 1, child_count=1, reform_child_count=0), + TreeRow( + "gov", + "gov.dynamic", + 0, + child_count=1, + reform_position=0, + reform_child_count=1, + ), + TreeRow("gov.dynamic", US_GOV_DYNAMIC_POLICY_PARAMETER, 0, reform_position=0), + TreeRow( + "gov", "gov.irs", 1, child_count=1, reform_position=1, reform_child_count=1 + ), + TreeRow("gov.irs", US_POLICY_PARAMETER, 0, reform_position=0), + TreeRow( + "gov", + "gov.simulation", + 2, + child_count=1, + reform_position=2, + reform_child_count=1, + ), + TreeRow( + "gov.simulation", + "gov.simulation.labor_supply_responses", + 0, + child_count=1, + reform_position=0, + reform_child_count=1, + ), + TreeRow( + "gov.simulation.labor_supply_responses", US_ELASTICITY, 0, reform_position=0 + ), + TreeRow("simulation", US_MTR_DELTA, 0), + ), + "uk": ( + TreeRow("", "gov", 0, child_count=3, reform_position=0, reform_child_count=2), + TreeRow("", "simulation", 1, child_count=1, reform_child_count=0), + TreeRow("gov", "gov.dynamic", 0, child_count=1, reform_child_count=0), + TreeRow("gov.dynamic", UK_OBR_SWITCH, 0), + TreeRow( + "gov", "gov.hmrc", 1, child_count=1, reform_position=0, reform_child_count=1 + ), + TreeRow("gov.hmrc", UK_POLICY_PARAMETER, 0, reform_position=0), + TreeRow( + "gov", + "gov.simulation", + 2, + child_count=1, + reform_position=1, + reform_child_count=1, + ), + TreeRow("gov.simulation", UK_ELASTICITY, 0, reform_position=0), + TreeRow("simulation", UK_SIMULATION_POLICY_PARAMETER, 0), + ), +} +# What the revision leaves of each tree: no dynamic folder, and "gov" counts +# only the folders it keeps. +TREES_AFTER_THE_MOVE = { + "us": { + "gov": (2, 2), + "gov.dynamic": (1, 1), + US_GOV_DYNAMIC_POLICY_PARAMETER: (None, None), + "gov.irs": (1, 1), + US_POLICY_PARAMETER: (None, None), + }, + "uk": { + "gov": (1, 1), + "gov.hmrc": (1, 1), + UK_POLICY_PARAMETER: (None, None), + "simulation": (1, 0), + UK_SIMULATION_POLICY_PARAMETER: (None, None), + }, +} + + +@dataclass +class StoredCountry: + """One country's catalog version the test stored, and what names it.""" + + country_id: str + model_id: UUID + model_created: bool + version_id: UUID + parameter_ids: dict[str, UUID] = field(default_factory=dict) + dynamic_id: UUID | None = None + policy_ids: list[UUID] = field(default_factory=list) + + +@pytest.fixture +def sessions( + v2_owner_sessions: sessionmaker[Session], +) -> Iterator[sessionmaker[Session]]: + """Yield the owner's Session factories on a database at head; leave it at head. + + ``v2_owner_sessions`` checks that the target is the disposable database + before this migrates it. + """ + command.upgrade(alembic_v2_config(), "head") + try: + yield v2_owner_sessions + finally: + command.upgrade(alembic_v2_config(), "head") + + +def _model_id(session: Session, country_id: str) -> tuple[UUID, bool]: + """Return the country's model, storing it first if it isn't stored.""" + name = f"policyengine-{country_id}" + stored = session.scalars( + select(col(TaxBenefitModel.id)).where(col(TaxBenefitModel.name) == name) + ).one_or_none() + if stored is not None: + return stored, False + model_id = uuid4() + add_row(session, TaxBenefitModel, id=model_id, name=name) + return model_id, True + + +def _store_country(session: Session, country_id: str) -> StoredCountry: + """Store a catalog version with policy and dynamic parameters and a tree. + + Every parameter has one current-law value from 2026; a dynamic sets each + dynamic parameter from 2027, and a policy sets each policy parameter. + """ + model_id, model_created = _model_id(session, country_id) + stored = StoredCountry( + country_id=country_id, + model_id=model_id, + model_created=model_created, + version_id=uuid4(), + ) + add_row( + session, + TaxBenefitModelVersion, + id=stored.version_id, + model_id=model_id, + version=f"c1-50-{stored.version_id.hex[:12]}", + current_law_id=1, + metadata_time_periods=[2026], + catalog_format=2, + ) + for name in (*POLICY_PARAMETERS[country_id], *DYNAMIC_PARAMETERS[country_id]): + parameter_id = uuid4() + stored.parameter_ids[name] = parameter_id + add_row( + session, + Parameter, + id=parameter_id, + name=name, + label=f"Label of {name}", + description=f"Description of {name}", + data_type="float", + unit="/1", + economy=True, + household=name != UK_OBR_SWITCH, + tax_benefit_model_version_id=stored.version_id, + ) + add_row( + session, + ParameterValue, + id=uuid4(), + parameter_id=parameter_id, + value_json=0.5, + start_date=START_2026, + ) + stored.dynamic_id = uuid4() + add_row( + session, + Dynamic, + id=stored.dynamic_id, + country_id=country_id, + tax_benefit_model_id=model_id, + tax_benefit_model_version_id=stored.version_id, + canonicalization_version=1, + content_hash=uuid4().hex * 2, + ) + for name in DYNAMIC_PARAMETERS[country_id]: + add_row( + session, + ParameterValue, + id=uuid4(), + parameter_id=stored.parameter_ids[name], + dynamic_id=stored.dynamic_id, + value_json={"set": name}, + start_date=START_2027, + end_date=datetime(2027, 12, 31, tzinfo=UTC), + ) + policy_id = _store_policy(session, stored) + for name in POLICY_PARAMETERS[country_id]: + _store_policy_value(session, stored, policy_id, name) + for row in TREES[country_id]: + add_row( + session, + ParameterTreeChild, + id=uuid4(), + tax_benefit_model_version_id=stored.version_id, + parent_path=row.parent_path, + path=row.path, + position=row.position, + label=row.path, + child_type="parameter" if row.is_parameter else "node", + child_count=row.child_count, + reform_position=row.reform_position, + reform_child_count=row.reform_child_count, + parameter_id=stored.parameter_ids[row.path] if row.is_parameter else None, + economy=True if row.is_parameter else None, + household=True if row.is_parameter else None, + ) + return stored + + +def _store_policy(session: Session, stored: StoredCountry) -> UUID: + policy_id = uuid4() + add_row( + session, + Policy, + id=policy_id, + country_id=stored.country_id, + tax_benefit_model_id=stored.model_id, + tax_benefit_model_version_id=stored.version_id, + canonicalization_version=1, + content_hash=uuid4().hex * 2, + ) + stored.policy_ids.append(policy_id) + return policy_id + + +def _store_policy_value( + session: Session, stored: StoredCountry, policy_id: UUID, parameter_name: str +) -> None: + add_row( + session, + ParameterValue, + id=uuid4(), + parameter_id=stored.parameter_ids[parameter_name], + policy_id=policy_id, + value_json=0.25, + start_date=START_2026, + ) + + +def _remove(sessions: sessionmaker[Session], countries: list[StoredCountry]) -> None: + """Delete what the test stored; a version's deletion takes its catalog rows.""" + with sessions.begin() as session: + for stored in countries: + session.execute(delete(Policy).where(col(Policy.id).in_(stored.policy_ids))) + session.execute(delete(Dynamic).where(col(Dynamic.id) == stored.dynamic_id)) + session.execute( + delete(TaxBenefitModelVersion).where( + col(TaxBenefitModelVersion.id) == stored.version_id + ) + ) + if stored.model_created: + session.execute( + delete(TaxBenefitModel).where( + col(TaxBenefitModel.id) == stored.model_id + ) + ) + + +@pytest.fixture +def stored_countries( + sessions: sessionmaker[Session], +) -> Iterator[list[StoredCountry]]: + """Store a US and a UK catalog version at the parent revision; remove them.""" + command.downgrade(alembic_v2_config(), PARENT_REVISION) + countries: list[StoredCountry] = [] + try: + with sessions.begin() as session: + countries.extend( + _store_country(session, country_id) for country_id in ("us", "uk") + ) + yield countries + finally: + command.upgrade(alembic_v2_config(), "head") + _remove(sessions, countries) + + +def _version_ids(countries: list[StoredCountry]) -> list[UUID]: + return [stored.version_id for stored in countries] + + +def _parameter_rows(session: Session, model: Any, version_ids: list[UUID]) -> set: + """Return a parameter table's rows of the given versions, every column.""" + return { + ( + row.id, + row.created_at, + row.name, + row.label, + row.description, + row.data_type, + row.unit, + row.economy, + row.household, + row.tax_benefit_model_version_id, + ) + for row in session.scalars( + select(model).where( + col(model.tax_benefit_model_version_id).in_(version_ids) + ) + ) + } + + +def _parameter_value_rows(session: Session, version_ids: list[UUID]) -> set: + """Return ``parameter_values`` rows of the versions' parameters.""" + return { + ( + row.id, + row.created_at, + row.parameter_id, + repr(row.value_json), + row.start_date, + row.end_date, + row.policy_id, + row.dynamic_id, + ) + for row in session.scalars( + select(ParameterValue) + .join(Parameter, col(Parameter.id) == col(ParameterValue.parameter_id)) + .where(col(Parameter.tax_benefit_model_version_id).in_(version_ids)) + ) + } + + +def _dynamic_parameter_value_rows(session: Session, version_ids: list[UUID]) -> set: + """Return ``dynamic_parameter_values`` rows in ``_parameter_value_rows``' shape. + + The policy column, which the table lacks, is None. + """ + return { + ( + row.id, + row.created_at, + row.dynamic_parameter_id, + repr(row.value_json), + row.start_date, + row.end_date, + None, + row.dynamic_id, + ) + for row in session.scalars( + select(DynamicParameterValue) + .join( + DynamicParameter, + col(DynamicParameter.id) + == col(DynamicParameterValue.dynamic_parameter_id), + ) + .where(col(DynamicParameter.tax_benefit_model_version_id).in_(version_ids)) + ) + } + + +def _tree_rows(session: Session, version_ids: list[UUID]) -> set: + return { + ( + row.id, + row.tax_benefit_model_version_id, + row.parent_path, + row.path, + row.position, + row.label, + row.child_type, + row.child_count, + row.reform_position, + row.reform_child_count, + row.parameter_id, + ) + for row in session.scalars( + select(ParameterTreeChild).where( + col(ParameterTreeChild.tax_benefit_model_version_id).in_(version_ids) + ) + ) + } + + +@dataclass(frozen=True) +class CatalogSnapshot: + """The stored versions' catalog rows, per table. + + The new tables' rows are None when the tables don't exist. + """ + + parameters: set + parameter_values: set + tree: set + dynamic_parameters: set | None + dynamic_parameter_values: set | None + + +def _snapshot( + sessions: sessionmaker[Session], countries: list[StoredCountry] +) -> CatalogSnapshot: + version_ids = _version_ids(countries) + with sessions() as session: + moved = schema_inspector(session).has_table("dynamic_parameters") + return CatalogSnapshot( + parameters=_parameter_rows(session, Parameter, version_ids), + parameter_values=_parameter_value_rows(session, version_ids), + tree=_tree_rows(session, version_ids), + dynamic_parameters=( + _parameter_rows(session, DynamicParameter, version_ids) + if moved + else None + ), + dynamic_parameter_values=( + _dynamic_parameter_value_rows(session, version_ids) if moved else None + ), + ) + + +def _is_dynamic(country: StoredCountry, parameter_id: UUID) -> bool: + return parameter_id in { + country.parameter_ids[name] for name in DYNAMIC_PARAMETERS[country.country_id] + } + + +def _dynamic_parameter_ids(countries: list[StoredCountry]) -> set[UUID]: + return { + stored.parameter_ids[name] + for stored in countries + for name in DYNAMIC_PARAMETERS[stored.country_id] + } + + +def _tree_counts(snapshot: CatalogSnapshot, version_id: UUID) -> dict: + return {row[3]: (row[7], row[9]) for row in snapshot.tree if row[1] == version_id} + + +def test_the_revision_adds_only_the_two_tables( + sessions: sessionmaker[Session], +) -> None: + config = alembic_v2_config() + command.downgrade(config, PARENT_REVISION) + with sessions() as session: + inspector = schema_inspector(session) + before = { + table: (inspector.get_columns(table), inspector.get_indexes(table)) + for table in inspector.get_table_names() + } + command.upgrade(config, DYNAMIC_PARAMETER_TABLES_REVISION) + with sessions() as session: + inspector = schema_inspector(session) + tables = set(inspector.get_table_names()) + assert tables - set(before) == NEW_TABLES + for table, (columns, indexes) in before.items(): + assert inspector.get_columns(table) == columns, table + assert inspector.get_indexes(table) == indexes, table + parameter_columns = { + column["name"]: (str(column["type"]), column["nullable"]) + for column in inspector.get_columns("parameters") + } + assert { + column["name"]: (str(column["type"]), column["nullable"]) + for column in inspector.get_columns("dynamic_parameters") + } == parameter_columns + assert { + column["name"]: (str(column["type"]), column["nullable"]) + for column in inspector.get_columns("dynamic_parameter_values") + } == { + "id": ("UUID", False), + "created_at": ("TIMESTAMP", False), + "dynamic_parameter_id": ("UUID", False), + "value_json": ("JSONB", False), + "start_date": ("TIMESTAMP", False), + "end_date": ("TIMESTAMP", True), + "dynamic_id": ("UUID", True), + } + assert { + ( + tuple(key["constrained_columns"]), + key["referred_table"], + key["options"].get("ondelete"), + ) + for key in inspector.get_foreign_keys("dynamic_parameter_values") + } == { + (("dynamic_parameter_id",), "dynamic_parameters", "CASCADE"), + (("dynamic_id",), "dynamics", "CASCADE"), + } + assert { + ( + tuple(key["constrained_columns"]), + key["referred_table"], + key["options"].get("ondelete"), + ) + for key in inspector.get_foreign_keys("dynamic_parameters") + } == { + ( + ("tax_benefit_model_version_id",), + "tax_benefit_model_versions", + "CASCADE", + ) + } + assert { + ( + index["name"], + tuple(index["column_names"]), + bool(index["unique"]), + str(index.get("dialect_options", {}).get("postgresql_where")), + ) + for index in inspector.get_indexes("dynamic_parameter_values") + } == { + ( + "ix_dynamic_parameter_values_parameter_period", + ("dynamic_parameter_id", "start_date", "end_date"), + False, + "None", + ), + ( + "uq_dynamic_parameter_values_current_law_parameter_start_date", + ("dynamic_parameter_id", "start_date"), + True, + "(dynamic_id IS NULL)", + ), + ( + "uq_dynamic_parameter_values_dynamic_parameter_start_date", + ("dynamic_id", "dynamic_parameter_id", "start_date"), + True, + "(dynamic_id IS NOT NULL)", + ), + } + assert { + constraint["name"]: tuple(constraint["column_names"]) + for constraint in inspector.get_unique_constraints("dynamic_parameters") + } == { + "uq_dynamic_parameters_model_version_name": ( + "tax_benefit_model_version_id", + "name", + ) + } + assert { + check["name"] + for check in inspector.get_check_constraints("dynamic_parameter_values") + } == {"ck_dynamic_parameter_values_effective_period"} + + command.downgrade(config, PARENT_REVISION) + with sessions() as session: + assert set(schema_inspector(session).get_table_names()) == set(before) + command.upgrade(config, "head") + command.check(config) + + +def test_the_upgrade_moves_every_dynamic_parameter_and_value_with_its_id( + sessions: sessionmaker[Session], stored_countries: list[StoredCountry] +) -> None: + config = alembic_v2_config() + before = _snapshot(sessions, stored_countries) + dynamic_ids = _dynamic_parameter_ids(stored_countries) + + command.upgrade(config, DYNAMIC_PARAMETER_TABLES_REVISION) + moved = _snapshot(sessions, stored_countries) + + assert {row[0] for row in before.parameters} - dynamic_ids == { + row[0] for row in moved.parameters + } + assert moved.dynamic_parameters == { + row for row in before.parameters if row[0] in dynamic_ids + } + assert moved.parameters == { + row for row in before.parameters if row[0] not in dynamic_ids + } + # Current-law values and the dynamics' values move, with their IDs and + # creation times; the policies' values and the policy parameters' + # current-law values stay. + assert moved.dynamic_parameter_values == { + row for row in before.parameter_values if row[2] in dynamic_ids + } + assert moved.parameter_values == { + row for row in before.parameter_values if row[2] not in dynamic_ids + } + assert {row[7] for row in moved.dynamic_parameter_values} == { + None, + *(stored.dynamic_id for stored in stored_countries), + } + assert all(row[7] is None for row in moved.parameter_values) + for stored in stored_countries: + assert ( + _tree_counts(moved, stored.version_id) + == (TREES_AFTER_THE_MOVE[stored.country_id]) + ) + # The kept rows are unchanged apart from "gov"'s counts. + assert {row for row in moved.tree if row[3] != "gov"} <= before.tree + + +def test_the_downgrade_moves_them_back_and_leaves_the_trees( + sessions: sessionmaker[Session], stored_countries: list[StoredCountry] +) -> None: + config = alembic_v2_config() + before = _snapshot(sessions, stored_countries) + command.upgrade(config, DYNAMIC_PARAMETER_TABLES_REVISION) + moved = _snapshot(sessions, stored_countries) + # A version published after the upgrade has its dynamic parameters in the + # new table only; the downgrade moves them too. + later = stored_countries[0] + later_parameter_id = uuid4() + later_value_id = uuid4() + with sessions.begin() as session: + add_row( + session, + DynamicParameter, + id=later_parameter_id, + name="gov.simulation.published_after_the_move", + tax_benefit_model_version_id=later.version_id, + ) + add_row( + session, + DynamicParameterValue, + id=later_value_id, + dynamic_parameter_id=later_parameter_id, + value_json=1, + start_date=START_2026, + ) + + command.downgrade(config, PARENT_REVISION) + downgraded = _snapshot(sessions, stored_countries) + + assert downgraded.dynamic_parameters is None + assert downgraded.dynamic_parameter_values is None + assert {row for row in downgraded.parameters if row[0] != later_parameter_id} == ( + before.parameters + ) + assert {row[0] for row in downgraded.parameters} >= {later_parameter_id} + assert { + row for row in downgraded.parameter_values if row[0] != later_value_id + } == before.parameter_values + assert { + (row[2], row[6], row[7]) + for row in downgraded.parameter_values + if row[0] == later_value_id + } == {(later_parameter_id, None, None)} + # Decision 1: the trees stay as the upgrade left them. + assert downgraded.tree == moved.tree + + command.upgrade(config, DYNAMIC_PARAMETER_TABLES_REVISION) + upgraded_again = _snapshot(sessions, stored_countries) + assert upgraded_again.parameters == moved.parameters + assert upgraded_again.parameter_values == moved.parameter_values + assert upgraded_again.tree == moved.tree + assert upgraded_again.dynamic_parameters is not None + assert { + row for row in upgraded_again.dynamic_parameters if row[0] != later_parameter_id + } == moved.dynamic_parameters + assert upgraded_again.dynamic_parameter_values is not None + assert { + row + for row in upgraded_again.dynamic_parameter_values + if row[0] != later_value_id + } == moved.dynamic_parameter_values + + +@pytest.mark.parametrize( + ("country_id", "parameter_name"), + [("us", US_MTR_DELTA), ("us", US_ELASTICITY), ("uk", UK_OBR_SWITCH)], +) +def test_the_upgrade_refuses_while_a_policy_value_names_a_dynamic_parameter( + sessions: sessionmaker[Session], + stored_countries: list[StoredCountry], + country_id: str, + parameter_name: str, +) -> None: + config = alembic_v2_config() + (stored,) = (item for item in stored_countries if item.country_id == country_id) + with sessions.begin() as session: + policy_id = _store_policy(session, stored) + _store_policy_value(session, stored, policy_id, parameter_name) + before = _snapshot(sessions, stored_countries) + + with pytest.raises(RuntimeError, match="policy values name dynamic parameters"): + command.upgrade(config, DYNAMIC_PARAMETER_TABLES_REVISION) + + assert current_revision(sessions) == PARENT_REVISION + assert _snapshot(sessions, stored_countries) == before + with sessions() as session: + assert not NEW_TABLES & set(schema_inspector(session).get_table_names()) + # Once the policy no longer sets it, as after C1 · 49's split, the upgrade runs. + with sessions.begin() as session: + session.execute(delete(Policy).where(col(Policy.id) == policy_id)) + stored.policy_ids.remove(policy_id) + command.upgrade(config, DYNAMIC_PARAMETER_TABLES_REVISION) + assert current_revision(sessions) == DYNAMIC_PARAMETER_TABLES_REVISION + + +def test_policy_values_on_another_country_s_prefix_stay_and_don_t_refuse( + sessions: sessionmaker[Session], stored_countries: list[StoredCountry] +) -> None: + """A US ``gov.dynamic.`` or UK ``simulation.`` parameter is a policy parameter.""" + config = alembic_v2_config() + before = _snapshot(sessions, stored_countries) + + command.upgrade(config, DYNAMIC_PARAMETER_TABLES_REVISION) + + moved = _snapshot(sessions, stored_countries) + kept_names = {row[2] for row in moved.parameters} + assert {US_GOV_DYNAMIC_POLICY_PARAMETER, UK_SIMULATION_POLICY_PARAMETER} <= ( + kept_names + ) + policy_values = {row for row in before.parameter_values if row[6] is not None} + assert policy_values <= moved.parameter_values + + +def test_the_new_tables_keep_one_value_per_owner_parameter_and_date( + sessions: sessionmaker[Session], stored_countries: list[StoredCountry] +) -> None: + command.upgrade(alembic_v2_config(), "head") + stored = stored_countries[0] + elasticity_id = stored.parameter_ids[US_ELASTICITY] + with sessions() as session: + current_law = { + "dynamic_parameter_id": elasticity_id, + "value_json": 0.5, + "start_date": START_2026, + } + with refused( + session, + match="uq_dynamic_parameter_values_current_law_parameter_start_date", + ): + add_row(session, DynamicParameterValue, id=uuid4(), **current_law) + dynamic_value = {**current_law, "dynamic_id": stored.dynamic_id} + add_row(session, DynamicParameterValue, id=uuid4(), **dynamic_value) + with refused( + session, match="uq_dynamic_parameter_values_dynamic_parameter_start_date" + ): + add_row(session, DynamicParameterValue, id=uuid4(), **dynamic_value) + with refused(session, match="ck_dynamic_parameter_values_effective_period"): + add_row( + session, + DynamicParameterValue, + id=uuid4(), + **{**current_law, "start_date": START_2027}, + end_date=START_2026, + ) + with refused(session, match="uq_dynamic_parameters_model_version_name"): + add_row( + session, + DynamicParameter, + id=uuid4(), + name=US_ELASTICITY, + tax_benefit_model_version_id=stored.version_id, + ) + session.rollback() + + +def test_a_dynamic_s_values_go_with_it_and_a_parameter_s_with_the_parameter( + sessions: sessionmaker[Session], stored_countries: list[StoredCountry] +) -> None: + command.upgrade(alembic_v2_config(), "head") + us, uk = stored_countries + with sessions.begin() as session: + session.execute(delete(Dynamic).where(col(Dynamic.id) == us.dynamic_id)) + session.execute( + delete(DynamicParameter).where( + col(DynamicParameter.id) == uk.parameter_ids[UK_OBR_SWITCH] + ) + ) + with sessions() as session: + remaining = { + (row.dynamic_parameter_id, row.dynamic_id) + for row in session.scalars( + select(DynamicParameterValue).where( + col(DynamicParameterValue.dynamic_parameter_id).in_( + _dynamic_parameter_ids(stored_countries) + ) + ) + ) + } + assert remaining == { + (us.parameter_ids[US_ELASTICITY], None), + (us.parameter_ids[US_MTR_DELTA], None), + (uk.parameter_ids[UK_ELASTICITY], None), + (uk.parameter_ids[UK_ELASTICITY], uk.dynamic_id), + } + us.dynamic_id = None + + +def test_tree_counts_lower_only_for_kept_parents( + sessions: sessionmaker[Session], stored_countries: list[StoredCountry] +) -> None: + """A parent row the revision deletes itself has nothing to lower.""" + with sessions.begin() as session: + session.execute( + update(ParameterTreeChild) + .where( + col(ParameterTreeChild.tax_benefit_model_version_id) + == stored_countries[0].version_id, + col(ParameterTreeChild.path) == "gov.simulation", + ) + .values(child_count=7) + ) + command.upgrade(alembic_v2_config(), DYNAMIC_PARAMETER_TABLES_REVISION) + moved = _snapshot(sessions, stored_countries) + assert ( + _tree_counts(moved, stored_countries[0].version_id) + == (TREES_AFTER_THE_MOVE["us"]) + ) + + +def test_the_seed_workflow_s_check_counts_what_the_revision_refuses( + sessions: sessionmaker[Session], stored_countries: list[StoredCountry] +) -> None: + """The read-only step and the revision find the same policy values. + + Values on another country's prefix (a US ``gov.dynamic.`` or UK + ``simulation.`` parameter) count for neither. + """ + with sessions() as session: + assert dynamic_parameter_move_is_pending(session) + before = count_policy_values_naming_dynamic_parameters(session) + us, uk = stored_countries + with sessions.begin() as session: + us_policy = _store_policy(session, us) + _store_policy_value(session, us, us_policy, US_MTR_DELTA) + _store_policy_value(session, us, us_policy, US_ELASTICITY) + uk_policy = _store_policy(session, uk) + _store_policy_value(session, uk, uk_policy, UK_OBR_SWITCH) + + with sessions() as session: + assert count_policy_values_naming_dynamic_parameters(session) == before + 3 + with pytest.raises(RuntimeError, match="policy values name dynamic parameters"): + command.upgrade(alembic_v2_config(), DYNAMIC_PARAMETER_TABLES_REVISION) + + with sessions.begin() as session: + session.execute( + delete(Policy).where(col(Policy.id).in_([us_policy, uk_policy])) + ) + us.policy_ids.remove(us_policy) + uk.policy_ids.remove(uk_policy) + with sessions() as session: + assert count_policy_values_naming_dynamic_parameters(session) == before + command.upgrade(alembic_v2_config(), "head") + with sessions() as session: + assert not dynamic_parameter_move_is_pending(session) diff --git a/tests/integration/test_v2_catalog_publication.py b/tests/integration/test_v2_catalog_publication.py index 55be28327..bcd992b34 100644 --- a/tests/integration/test_v2_catalog_publication.py +++ b/tests/integration/test_v2_catalog_publication.py @@ -1159,7 +1159,7 @@ def _stored_search_file( ) ).one() content = gzip.decompress(row.compressed_content) - assert row.file_format == 1 + assert row.file_format == 2 assert row.content_sha256 == hashlib.sha256(content).hexdigest() assert row.uncompressed_size == len(content) assert row.compressed_size == len(row.compressed_content) @@ -1194,7 +1194,7 @@ def _search_file_count(sessions: sessionmaker[Session], version: str | None) -> def _fixture_search_file(country_id: str, version: str) -> dict: return { - "format": 1, + "format": 2, "country_id": country_id, "policyengine_version": version, "parameters": [ diff --git a/tests/integration/test_v2_catalog_publication_dynamic_parameters.py b/tests/integration/test_v2_catalog_publication_dynamic_parameters.py new file mode 100644 index 000000000..459e31c4c --- /dev/null +++ b/tests/integration/test_v2_catalog_publication_dynamic_parameters.py @@ -0,0 +1,562 @@ +"""Disposable-Postgres coverage: publication keeps dynamic parameters apart (C1 · 50). + +Catalog publication stores each version's model assumptions (US +``gov.simulation.`` and ``simulation.``, UK ``gov.simulation.`` and +``gov.dynamic.``) in ``dynamic_parameters`` and their current-law values in +``dynamic_parameter_values``, with the catalog's IDs, and every other parameter +in ``parameters`` as before. It compares, restores and prunes both, and +leaves dynamic parameters and their folders out of the policy tree and the +search file, whose format becomes 2. Each test publishes as the catalog +writer, which holds only its declared privileges. +""" + +from __future__ import annotations + +import gzip +import json +from dataclasses import replace +from typing import TYPE_CHECKING, Any +from uuid import UUID, uuid4 + +import pytest +import sqlalchemy as sa +from alembic import command +from sqlmodel import col + +from policyengine_api.data.v2.catalog.publication import ( + CatalogPublicationError, + publish_catalog, +) +from policyengine_api.data.v2.catalog.publication_types import PrunedCatalogVersion +from policyengine_api.data.v2.models import ( + Dynamic, + DynamicParameter, + DynamicParameterValue, + Parameter, + ParameterSearchFile, + ParameterTreeChild, + ParameterValue, + TaxBenefitModel, + TaxBenefitModelVersion, +) +from policyengine_api.data.v2.privileges import ( + CATALOG_WRITER_ROLE, + declared_privileges, +) +from policyengine_api.dynamic_parameters import ( + is_dynamic_parameter, + is_dynamic_parameter_path, +) +from tests.fixtures import database_sessions +from tests.fixtures.integration.alembic_v2 import alembic_v2_config +from tests.fixtures.v2_catalog import ( + DYNAMIC_PARAMETER_RECORDS, + catalog_with_dynamic_parameters, +) +from tests.integration.catalog_publication_support import emptied_catalog +from tests.integration.simulation_rows import add_row + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + from policyengine_api.data.v2.catalog.records import CountryCatalog + from tests.integration.conftest import ManagedV2Roles + +OLD_VERSION = "5.0.1" +EARLIER_KEPT_VERSION = "5.0.2" +PREVIOUS_VERSION = "5.0.3" +INSTALLED_VERSION = "5.0.4" +COUNTRY_IDS = ("us", "uk") +# The parent of the revision that moves dynamic parameters into their tables. +PARENT_REVISION = "d417fe8b1b17" + + +@pytest.fixture +def publication_sessions( + v2_owner_sessions: sessionmaker[Session], +) -> Iterator[sessionmaker[Session]]: + with emptied_catalog(v2_owner_sessions) as sessions: + yield sessions + + +@pytest.fixture +def writer_sessions( + publication_sessions: sessionmaker[Session], + managed_v2_roles: ManagedV2Roles, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], +) -> sessionmaker[Session]: + """Session factories of the catalog writer, on the emptied catalog.""" + return v2_sessions_as_role(CATALOG_WRITER_ROLE) + + +def _publish(sessions: sessionmaker[Session], version: str = INSTALLED_VERSION): + return publish_catalog( + sessions, catalog_with_dynamic_parameters(policyengine_version=version) + ) + + +def _version_id(sessions: sessionmaker[Session], country_id: str, version: str) -> UUID: + with sessions() as session: + version_id: UUID = session.execute( + sa.select(col(TaxBenefitModelVersion.id)) + .join( + TaxBenefitModel, + col(TaxBenefitModel.id) == col(TaxBenefitModelVersion.model_id), + ) + .where( + col(TaxBenefitModel.name) == f"policyengine-{country_id}", + col(TaxBenefitModelVersion.version) == version, + ) + ).scalar_one() + return version_id + + +def _parameters_by_name( + sessions: sessionmaker[Session], model: Any, version_id: UUID +) -> dict[str, UUID]: + with sessions() as session: + return { + row.name: row.id + for row in session.execute( + sa.select(col(model.name), col(model.id)).where( + col(model.tax_benefit_model_version_id) == version_id + ) + ) + } + + +def _current_law_values( + sessions: sessionmaker[Session], version_id: UUID +) -> dict[str, set[tuple]]: + """Return each table's current-law values of one version: ID, parameter, value.""" + with sessions() as session: + policy_values = session.execute( + sa.select( + col(ParameterValue.id), + col(ParameterValue.parameter_id), + sa.cast(col(ParameterValue.value_json), sa.Text), + ) + .join(Parameter, col(Parameter.id) == col(ParameterValue.parameter_id)) + .where( + col(Parameter.tax_benefit_model_version_id) == version_id, + col(ParameterValue.policy_id).is_(None), + col(ParameterValue.dynamic_id).is_(None), + ) + ) + dynamic_values = session.execute( + sa.select( + col(DynamicParameterValue.id), + col(DynamicParameterValue.dynamic_parameter_id), + sa.cast(col(DynamicParameterValue.value_json), sa.Text), + ) + .join( + DynamicParameter, + col(DynamicParameter.id) + == col(DynamicParameterValue.dynamic_parameter_id), + ) + .where( + col(DynamicParameter.tax_benefit_model_version_id) == version_id, + col(DynamicParameterValue.dynamic_id).is_(None), + ) + ) + return { + "parameter_values": {tuple(row) for row in policy_values}, + "dynamic_parameter_values": {tuple(row) for row in dynamic_values}, + } + + +def _catalog_country(version: str, country_id: str) -> CountryCatalog: + return catalog_with_dynamic_parameters(policyengine_version=version).country( + country_id + ) + + +def _record_ids(country: CountryCatalog, *, dynamic: bool) -> dict[str, UUID]: + return { + parameter.name: parameter.id + for parameter in country.parameters + if is_dynamic_parameter(country.country_id, parameter.name) == dynamic + } + + +def _record_value_ids(country: CountryCatalog, *, dynamic: bool) -> set[UUID]: + return { + value.id + for parameter in country.parameters + if is_dynamic_parameter(country.country_id, parameter.name) == dynamic + for value in parameter.values + } + + +def _tree_paths(sessions: sessionmaker[Session], version_id: UUID) -> set[str]: + with sessions() as session: + return set( + session.scalars( + sa.select(col(ParameterTreeChild.path)).where( + col(ParameterTreeChild.tax_benefit_model_version_id) == version_id + ) + ) + ) + + +def _search_files( + sessions: sessionmaker[Session], version_id: UUID +) -> dict[int, dict | bytes]: + """Return a version's stored search files by format, decoded when format 2.""" + with sessions() as session: + rows = session.execute( + sa.select( + col(ParameterSearchFile.file_format), + col(ParameterSearchFile.compressed_content), + ).where(col(ParameterSearchFile.tax_benefit_model_version_id) == version_id) + ).all() + return { + row.file_format: ( + json.loads(gzip.decompress(row.compressed_content)) + if row.file_format == 2 + else row.compressed_content + ) + for row in rows + } + + +def test_publication_stores_each_kind_of_parameter_in_its_own_table( + publication_sessions: sessionmaker[Session], + writer_sessions: sessionmaker[Session], +) -> None: + evidence = _publish(writer_sessions) + republished = _publish(writer_sessions) + + for country_id in COUNTRY_IDS: + country = _catalog_country(INSTALLED_VERSION, country_id) + version_id = _version_id(publication_sessions, country_id, INSTALLED_VERSION) + assert _parameters_by_name(publication_sessions, Parameter, version_id) == ( + _record_ids(country, dynamic=False) + ) + assert _parameters_by_name( + publication_sessions, DynamicParameter, version_id + ) == _record_ids(country, dynamic=True) + assert set(_record_ids(country, dynamic=True)) == set( + DYNAMIC_PARAMETER_RECORDS[country_id] + ) + values = _current_law_values(publication_sessions, version_id) + assert {row[0] for row in values["parameter_values"]} == _record_value_ids( + country, dynamic=False + ) + assert {row[0] for row in values["dynamic_parameter_values"]} == ( + _record_value_ids(country, dynamic=True) + ) + counts = evidence.entity_counts + assert counts["dynamic_parameters"] == 4 + assert counts["dynamic_parameter_values"] == 4 + assert counts["parameters"] == 2 + assert counts["parameter_values"] == 4 + assert republished.entity_counts == counts + assert "dynamic_parameters" in republished.catalog_tables_analyzed + assert "dynamic_parameter_values" in republished.catalog_tables_analyzed + + +def test_the_tree_and_search_file_hold_only_policy_parameters( + publication_sessions: sessionmaker[Session], + writer_sessions: sessionmaker[Session], +) -> None: + _publish(writer_sessions) + + for country_id in COUNTRY_IDS: + version_id = _version_id(publication_sessions, country_id, INSTALLED_VERSION) + paths = _tree_paths(publication_sessions, version_id) + assert "gov.example.rate" in paths + assert not [ + path for path in paths if is_dynamic_parameter_path(country_id, path) + ] + files = _search_files(publication_sessions, version_id) + assert set(files) == {2} + search_file = files[2] + assert isinstance(search_file, dict) + assert search_file["format"] == 2 + listed = [ + entry["path"] + for section in ("parameters", "other_parameters", "nodes") + for entry in search_file[section] + ] + assert "gov.example.rate" in listed + assert not [ + path for path in listed if is_dynamic_parameter_path(country_id, path) + ] + + +@pytest.mark.parametrize( + ("change", "table"), + [ + ("label", "dynamic parameters"), + ("value", "dynamic parameter values"), + ], +) +def test_republication_fails_when_a_stored_dynamic_parameter_row_differs( + publication_sessions: sessionmaker[Session], + writer_sessions: sessionmaker[Session], + change: str, + table: str, +) -> None: + _publish(writer_sessions) + catalog = catalog_with_dynamic_parameters(policyengine_version=INSTALLED_VERSION) + us = catalog.country("us") + name = "simulation.marginal_tax_rate_delta" + parameters = tuple( + ( + parameter + if parameter.name != name + else ( + replace(parameter, label="Changed label") + if change == "label" + else replace( + parameter, + values=tuple( + replace(value, value_json=2_000) for value in parameter.values + ), + ) + ) + ) + for parameter in us.parameters + ) + changed = replace( + catalog, + countries=(replace(us, parameters=parameters), catalog.country("uk")), + ) + + with pytest.raises(CatalogPublicationError, match=f"in its {table}$"): + publish_catalog(writer_sessions, changed) + + +def test_a_dynamic_s_own_values_are_not_compared_as_current_law( + publication_sessions: sessionmaker[Session], + writer_sessions: sessionmaker[Session], +) -> None: + _publish(writer_sessions) + version_id = _version_id(publication_sessions, "us", INSTALLED_VERSION) + dynamic_parameter_ids = _parameters_by_name( + publication_sessions, DynamicParameter, version_id + ) + with publication_sessions.begin() as session: + model_id = session.execute( + sa.select(col(TaxBenefitModelVersion.model_id)).where( + col(TaxBenefitModelVersion.id) == version_id + ) + ).scalar_one() + dynamic_id = uuid4() + add_row( + session, + Dynamic, + id=dynamic_id, + country_id="us", + tax_benefit_model_id=model_id, + tax_benefit_model_version_id=version_id, + canonicalization_version=1, + content_hash="d" * 64, + ) + first_record = catalog_with_dynamic_parameters().country("us").parameters + add_row( + session, + DynamicParameterValue, + id=uuid4(), + dynamic_parameter_id=dynamic_parameter_ids[ + "simulation.marginal_tax_rate_delta" + ], + dynamic_id=dynamic_id, + value_json=5, + start_date=next( + value.start_date + for record in first_record + if record.name == "simulation.marginal_tax_rate_delta" + for value in record.values + ), + ) + + republished = _publish(writer_sessions) + + assert republished.restored_catalog_versions == () + with publication_sessions() as session: + owned = session.scalars( + sa.select(col(DynamicParameterValue.value_json)).where( + col(DynamicParameterValue.dynamic_id) == dynamic_id + ) + ).all() + assert owned == [5] + + +def _prunable_counts(sessions: sessionmaker[Session], version_id: UUID) -> dict: + values = _current_law_values(sessions, version_id) + return { + "parameter_values": len(values["parameter_values"]), + "dynamic_parameter_values": len(values["dynamic_parameter_values"]), + "tree": len(_tree_paths(sessions, version_id)), + "search_files": len(_search_files(sessions, version_id)), + } + + +def test_pruning_deletes_both_tables_current_law_values_and_restore_rewrites_them( + publication_sessions: sessionmaker[Session], + writer_sessions: sessionmaker[Session], +) -> None: + """A pruned version loses its current-law values from both tables only. + + Its dynamic parameters, and a dynamic's values on them, stay. Publishing + the version again restores both tables' values with their catalog IDs. + """ + _publish(writer_sessions, OLD_VERSION) + old_ids = { + country_id: _version_id(publication_sessions, country_id, OLD_VERSION) + for country_id in COUNTRY_IDS + } + first_published = { + country_id: _current_law_values(publication_sessions, version_id) + for country_id, version_id in old_ids.items() + } + dynamic_parameters = { + country_id: _parameters_by_name( + publication_sessions, DynamicParameter, version_id + ) + for country_id, version_id in old_ids.items() + } + for version in (EARLIER_KEPT_VERSION, PREVIOUS_VERSION): + _publish(writer_sessions, version) + + installed = _publish(writer_sessions, INSTALLED_VERSION) + + assert installed.pruned_catalog_versions == tuple( + PrunedCatalogVersion( + country_id=country_id, + policyengine_version=OLD_VERSION, + parameter_values=2, + dynamic_parameter_values=2, + parameter_tree_children=3, + parameter_search_files=1, + ) + for country_id in ("uk", "us") + ) + assert installed.as_dict()["pruned_catalog_versions"][0]["deleted_rows"] == { + "parameter_values": 2, + "dynamic_parameter_values": 2, + "parameter_tree_children": 3, + "parameter_search_files": 1, + } + for country_id, version_id in old_ids.items(): + assert _prunable_counts(publication_sessions, version_id) == { + "parameter_values": 0, + "dynamic_parameter_values": 0, + "tree": 0, + "search_files": 0, + } + assert ( + _parameters_by_name(publication_sessions, DynamicParameter, version_id) + == dynamic_parameters[country_id] + ) + + rollback = _publish(writer_sessions, OLD_VERSION) + + assert rollback.restored_catalog_versions == ( + ("us", OLD_VERSION, 2, 2), + ("uk", OLD_VERSION, 2, 2), + ) + assert rollback.as_dict()["restored_catalog_versions"][0] == { + "country_id": "us", + "policyengine_version": OLD_VERSION, + "parameter_values": 2, + "dynamic_parameter_values": 2, + } + for country_id, version_id in old_ids.items(): + assert ( + _current_law_values(publication_sessions, version_id) + == (first_published[country_id]) + ) + + +def test_the_revision_s_round_trip_leaves_a_catalog_publication_accepts( + publication_sessions: sessionmaker[Session], + writer_sessions: sessionmaker[Session], + disposable_v2_database_url: str, + managed_v2_roles: ManagedV2Roles, +) -> None: + """The revision classifies rows exactly as publication does. + + A downgrade moves the published dynamic parameters back into + ``parameters``, and the upgrade moves them out again; publishing the same + catalog then compares every row both ways and finds no difference. The + upgrade creates the two tables again, so their grants are applied again, + as the deploy's reconcile step does after every upgrade. + """ + _publish(writer_sessions) + version_ids = [ + _version_id(publication_sessions, country_id, INSTALLED_VERSION) + for country_id in COUNTRY_IDS + ] + before = { + version_id: ( + _parameters_by_name(publication_sessions, Parameter, version_id), + _parameters_by_name(publication_sessions, DynamicParameter, version_id), + _current_law_values(publication_sessions, version_id), + ) + for version_id in version_ids + } + config = alembic_v2_config() + try: + command.downgrade(config, PARENT_REVISION) + finally: + command.upgrade(config, "head") + database_sessions.grant_declared_v2_privileges( + disposable_v2_database_url, + declared_privileges(managed_v2_roles.deployment_environment), + ) + + _publish(writer_sessions) + + for version_id in version_ids: + assert ( + _parameters_by_name(publication_sessions, Parameter, version_id), + _parameters_by_name(publication_sessions, DynamicParameter, version_id), + _current_law_values(publication_sessions, version_id), + ) == before[version_id] + + +def test_republication_writes_format_2_beside_a_stored_format_1_file( + publication_sessions: sessionmaker[Session], + writer_sessions: sessionmaker[Session], +) -> None: + """The installed version stored by an earlier release keeps its format 1 file. + + A release before C1 · 50 stored a format 1 file that lists the dynamic + parameters, which it still serves after a rollback; publication adds the + format 2 file without changing it. + """ + _publish(writer_sessions) + version_id = _version_id(publication_sessions, "us", INSTALLED_VERSION) + earlier_file = gzip.compress(b'{"format":1}', mtime=0) + with publication_sessions.begin() as session: + session.execute( + sa.delete(ParameterSearchFile).where( + col(ParameterSearchFile.tax_benefit_model_version_id) == version_id + ) + ) + add_row( + session, + ParameterSearchFile, + id=uuid4(), + tax_benefit_model_version_id=version_id, + file_format=1, + compressed_content=earlier_file, + content_sha256="0" * 64, + uncompressed_size=12, + compressed_size=len(earlier_file), + ) + + evidence = _publish(writer_sessions) + + files = _search_files(publication_sessions, version_id) + assert files[1] == earlier_file + assert isinstance(files[2], dict) + assert [model for model, *_sizes in evidence.parameter_search_files_written] == [ + "policyengine-us" + ] diff --git a/tests/integration/test_v2_catalog_publication_pruning.py b/tests/integration/test_v2_catalog_publication_pruning.py index 51106d9ef..fcbbce5bf 100644 --- a/tests/integration/test_v2_catalog_publication_pruning.py +++ b/tests/integration/test_v2_catalog_publication_pruning.py @@ -376,6 +376,7 @@ def _fixture_pruned(country_id: str, version: str) -> PrunedCatalogVersion: country_id=country_id, policyengine_version=version, parameter_values=FIXTURE_PRUNED_ROWS["parameter_values"], + dynamic_parameter_values=0, parameter_tree_children=FIXTURE_PRUNED_ROWS["tree_rows"], parameter_search_files=FIXTURE_PRUNED_ROWS["search_files"], ) @@ -483,8 +484,8 @@ def test_republishing_a_pruned_version_restores_what_its_publication_wrote( for version in (PREVIOUS_VERSION, INSTALLED_VERSION): assert _pruned_at(publication_sessions, model_name, version) is None assert rollback.restored_catalog_versions == ( - ("us", OLD_VERSION, FIXTURE_PRUNED_ROWS["parameter_values"]), - ("uk", OLD_VERSION, FIXTURE_PRUNED_ROWS["parameter_values"]), + ("us", OLD_VERSION, FIXTURE_PRUNED_ROWS["parameter_values"], 0), + ("uk", OLD_VERSION, FIXTURE_PRUNED_ROWS["parameter_values"], 0), ) assert rollback.parameter_trees_written == ( (UK_MODEL, OLD_VERSION, FIXTURE_PRUNED_ROWS["tree_rows"]), @@ -503,11 +504,13 @@ def test_republishing_a_pruned_version_restores_what_its_publication_wrote( "country_id": "us", "policyengine_version": OLD_VERSION, "parameter_values": FIXTURE_PRUNED_ROWS["parameter_values"], + "dynamic_parameter_values": 0, }, { "country_id": "uk", "policyengine_version": OLD_VERSION, "parameter_values": FIXTURE_PRUNED_ROWS["parameter_values"], + "dynamic_parameter_values": 0, }, ] assert again.restored_catalog_versions == () @@ -1016,6 +1019,7 @@ def test_a_version_without_current_law_rows_is_marked_pruned_with_zero_counts( country_id="us", policyengine_version=OLD_VERSION, parameter_values=0, + dynamic_parameter_values=0, parameter_tree_children=0, parameter_search_files=0, ), diff --git a/tests/integration/test_v2_dynamic_persistence.py b/tests/integration/test_v2_dynamic_persistence.py index 379b5db16..a209ef40c 100644 --- a/tests/integration/test_v2_dynamic_persistence.py +++ b/tests/integration/test_v2_dynamic_persistence.py @@ -2,7 +2,9 @@ The services run as API v1's runtime role, which proves its declared privileges cover them (rule ``api.v2.runtime-privileges-tested-as-runtime-role``); -the catalog is written and everything removed as the superuser. +the catalog is written and everything removed as the superuser. Model +assumptions are ``dynamic_parameters`` rows and a dynamic's values +``dynamic_parameter_values`` rows (C1 · 50). """ from __future__ import annotations @@ -16,6 +18,8 @@ from policyengine_api.data.v2.models import ( Dynamic, + DynamicParameter, + DynamicParameterValue, LegacyPolicyMapping, Parameter, ParameterValue, @@ -23,6 +27,7 @@ TaxBenefitModel, TaxBenefitModelVersion, ) +from policyengine_api.dynamic_parameters import is_dynamic_parameter from policyengine_api.services.v2.dynamics.database_session import ( DynamicDatabaseSession, ) @@ -72,7 +77,10 @@ def _store_catalog( metadata_time_periods=[2026], ) parameters = [ - Parameter(name=name, tax_benefit_model_version=version) for name in names + (DynamicParameter if is_dynamic_parameter(country_id, name) else Parameter)( + name=name, tax_benefit_model_version=version + ) + for name in names ] session.add_all(parameters) session.flush() @@ -109,6 +117,11 @@ def _remove_catalog( ) ) ) + session.execute( + delete(DynamicParameterValue).where( + DynamicParameterValue.dynamic_id.in_(dynamic_ids) + ) + ) session.execute( delete(Dynamic).where(Dynamic.tax_benefit_model_id == catalog.model_id) ) @@ -120,6 +133,11 @@ def _remove_catalog( Parameter.tax_benefit_model_version_id == catalog.version_id ) ) + session.execute( + delete(DynamicParameter).where( + DynamicParameter.tax_benefit_model_version_id == catalog.version_id + ) + ) session.execute( delete(TaxBenefitModelVersion).where( TaxBenefitModelVersion.id == catalog.version_id @@ -208,16 +226,33 @@ def _snapshot( def _stored_names(session: Session, *, policy_id=None, dynamic_id=None) -> set[str]: - owner = ( - ParameterValue.policy_id == policy_id - if policy_id is not None - else ParameterValue.dynamic_id == dynamic_id + """Return the names a policy's or a dynamic's stored values set. + + A policy's values are ``parameter_values`` rows; a dynamic's are + ``dynamic_parameter_values`` rows, and it sets no ``parameter_values`` row. + """ + if policy_id is not None: + return set( + session.scalars( + select(Parameter.name) + .join(ParameterValue, ParameterValue.parameter_id == Parameter.id) + .where(ParameterValue.policy_id == policy_id) + ) + ) + assert ( + session.scalars( + select(ParameterValue.id).where(ParameterValue.dynamic_id == dynamic_id) + ).all() + == [] ) return set( session.scalars( - select(Parameter.name) - .join(ParameterValue, ParameterValue.parameter_id == Parameter.id) - .where(owner) + select(DynamicParameter.name) + .join( + DynamicParameterValue, + DynamicParameterValue.dynamic_parameter_id == DynamicParameter.id, + ) + .where(DynamicParameterValue.dynamic_id == dynamic_id) ) ) diff --git a/tests/unit/test_alembic_workflows.py b/tests/unit/test_alembic_workflows.py index fed204191..c1410b614 100644 --- a/tests/unit/test_alembic_workflows.py +++ b/tests/unit/test_alembic_workflows.py @@ -218,6 +218,7 @@ def test_reusable_v2_alembic_check_uses_only_disposable_postgres(): assert "test_alembic_v2_dynamics.py" in lifecycle_script assert "test_alembic_v2_report_column_drops.py" in lifecycle_script assert "test_alembic_v2_user_dynamics.py" in lifecycle_script + assert "test_alembic_v2_dynamic_parameter_tables.py" in lifecycle_script assert "redis:7.2-alpine" not in workflow assert "RUNTIME_CACHE_TEST_URL" not in workflow assert "test_v2_catalog_installed.py" not in workflow diff --git a/tests/unit/test_dynamic_parameters.py b/tests/unit/test_dynamic_parameters.py index 42293f61a..0f32b3469 100644 --- a/tests/unit/test_dynamic_parameters.py +++ b/tests/unit/test_dynamic_parameters.py @@ -9,6 +9,7 @@ ConflictingParameterSpellingsError, canonical_parameter_name, is_dynamic_parameter, + is_dynamic_parameter_path, split_legacy_policy_json, ) from policyengine_api.supported_countries import SupportedCountryId @@ -63,6 +64,69 @@ def test_other_parameters_are_not_dynamic( assert not is_dynamic_parameter(country_id, parameter_name) +@pytest.mark.parametrize( + ("country_id", "path"), + [ + # The folders themselves, which hold only dynamic parameters. + ("us", "gov.simulation"), + ("us", "simulation"), + ("uk", "gov.simulation"), + ("uk", "gov.dynamic"), + # Folders, brackets and parameters below them. + ("us", "gov.simulation.labor_supply_responses"), + ("us", "gov.simulation.labor_supply_responses.elasticities.income"), + ("us", "simulation.marginal_tax_rate_delta"), + ("uk", "gov.simulation.labour_supply_responses"), + ("uk", "gov.simulation.schedule[0]"), + ("uk", "gov.simulation.schedule[0].rate"), + ("uk", UK_OBR_LABOUR_SUPPLY_SWITCH), + ], +) +def test_dynamic_folders_and_everything_below_them_are_dynamic_paths( + country_id: SupportedCountryId, path: str +) -> None: + assert is_dynamic_parameter_path(country_id, path) + + +@pytest.mark.parametrize( + ("country_id", "path"), + [ + # "gov" holds policy parameters too. + ("us", "gov"), + ("uk", "gov"), + ("us", "gov.irs"), + ("us", "gov.simulations_count"), + ("us", "simulationX"), + # Each country's own folders only. + ("us", "gov.dynamic"), + ("uk", "simulation"), + ("uk", "simulation.marginal_tax_rate_delta"), + ("uk", "gov.dynamics"), + ("us", ""), + ], +) +def test_policy_folders_and_parameters_are_not_dynamic_paths( + country_id: SupportedCountryId, path: str +) -> None: + assert not is_dynamic_parameter_path(country_id, path) + + +def test_every_dynamic_parameter_has_a_dynamic_path() -> None: + """A parameter is a dynamic path exactly when it is a dynamic parameter.""" + for country_id in DYNAMIC_PARAMETER_PREFIXES: + for name in ( + US_INCOME_ELASTICITY, + UK_INCOME_ELASTICITY, + UK_OBR_LABOUR_SUPPLY_SWITCH, + "simulation.marginal_tax_rate_delta", + "gov.hmrc.rate", + "gov.dynamics_count", + ): + assert is_dynamic_parameter_path(country_id, name) == ( + is_dynamic_parameter(country_id, name) + ) + + def test_only_the_uk_old_labour_supply_spelling_is_rewritten() -> None: assert canonical_parameter_name("uk", UK_OLD_INCOME_ELASTICITY) == ( UK_INCOME_ELASTICITY diff --git a/tests/unit/test_v2_integration_workflow.py b/tests/unit/test_v2_integration_workflow.py index 88f2dd866..fe30155bc 100644 --- a/tests/unit/test_v2_integration_workflow.py +++ b/tests/unit/test_v2_integration_workflow.py @@ -89,3 +89,13 @@ def test_the_job_publishes_selected_folders_of_the_installed_models() -> None: "uv run --frozen --extra dev python scripts/reconcile_v2_privileges.py verify" ) < commands.index(step["run"]) assert (REPO / INSTALLED_FOLDERS_TEST).exists() + + +def test_the_job_publishes_dynamic_parameters_into_their_own_tables() -> None: + """Publication's Postgres tests for the dynamic parameter tables run (C1 · 50).""" + commands = _step_commands(_runtime_job()) + + assert any( + "tests/integration/test_v2_catalog_publication_dynamic_parameters.py" in command + for command in commands + ) diff --git a/tests/unit/v2/test_alembic_v2_revisions.py b/tests/unit/v2/test_alembic_v2_revisions.py index 2eb55dcc2..5cf4c5474 100644 --- a/tests/unit/v2/test_alembic_v2_revisions.py +++ b/tests/unit/v2/test_alembic_v2_revisions.py @@ -5,6 +5,7 @@ operations each one runs. """ +import importlib.util import re from pathlib import Path @@ -14,12 +15,15 @@ from policyengine_api.constants import REPO from policyengine_api.data.v2.migration_target import V2_ALEMBIC_HEAD_REVISION from policyengine_api.data.v2.models import V2_TABLE_NAMES +from policyengine_api.dynamic_parameters import DYNAMIC_PARAMETER_PREFIXES POST_BASELINE_TABLE_NAMES = frozenset( { "budget_window_runs", "cliff_impacts", "countries", + "dynamic_parameter_values", + "dynamic_parameters", "legacy_household_mappings", "legacy_policy_mappings", "legacy_user_mappings", @@ -77,16 +81,20 @@ # The report column drops revision, on the cliff impacts revision, and # parent of the user dynamics revision. REPORT_COLUMN_DROPS_REVISION = "4e30076d4b9f" -# The user dynamics revision, on the report column drops revision. +# The user dynamics revision, on the report column drops revision, and parent +# of the dynamic parameter tables revision. USER_DYNAMICS_REVISION = "d417fe8b1b17" +# The dynamic parameter tables revision, on the user dynamics revision. +DYNAMIC_PARAMETER_TABLES_REVISION = "7f7335f0eb31" def test_v2_revision_chain_has_generated_policy_and_user_identity_changes() -> None: config = Config(str(REPO / "alembic-v2.ini")) script = ScriptDirectory.from_config(config) assert script.get_heads() == [V2_ALEMBIC_HEAD_REVISION] - assert V2_ALEMBIC_HEAD_REVISION == USER_DYNAMICS_REVISION + assert V2_ALEMBIC_HEAD_REVISION == DYNAMIC_PARAMETER_TABLES_REVISION assert [revision.revision for revision in script.walk_revisions()] == [ + DYNAMIC_PARAMETER_TABLES_REVISION, USER_DYNAMICS_REVISION, REPORT_COLUMN_DROPS_REVISION, CLIFF_IMPACTS_REVISION, @@ -1347,7 +1355,6 @@ def test_user_dynamics_revision_creates_only_the_saved_dynamics_table() -> None: ] downgrade = revision[revision.index("def downgrade()") :] - assert V2_ALEMBIC_HEAD_REVISION == USER_DYNAMICS_REVISION assert ( "Generation: uv run alembic -c alembic-v2.ini revision --autogenerate" in revision @@ -1378,3 +1385,82 @@ def test_user_dynamics_revision_creates_only_the_saved_dynamics_table() -> None: assert upgrade.count('ondelete="CASCADE"') == 1 assert "op.execute(" not in revision assert "op.bulk_insert(" not in revision + + +def _dynamic_parameter_tables_revision_path() -> Path: + (path,) = (REPO / "migrations/v2/versions").glob( + f"{DYNAMIC_PARAMETER_TABLES_REVISION}_*.py" + ) + return path + + +def test_dynamic_parameter_tables_revision_creates_two_tables_and_moves_rows() -> None: + """The revision after user dynamics adds the two tables, then moves rows. + + Its tables and indexes are generated. Its one data step is the user's + migration decision (C1 · 46, Q2), written by hand: after the generated + tables are created it moves every stored dynamic parameter and value into + them, and before the generated drops its downgrade moves them back. It has + no other correction. + """ + revision = _dynamic_parameter_tables_revision_path().read_text(encoding="utf-8") + upgrade = revision[ + revision.index("def upgrade()") : revision.index("def downgrade()") + ] + downgrade = revision[revision.index("def downgrade()") :] + parent = USER_DYNAMICS_REVISION + + assert ( + "Generation: uv run alembic -c alembic-v2.ini revision --autogenerate" + in revision + ) + assert re.search( + rf"""down_revision: Union\[str, None\] = ["']{parent}["']""", revision + ) + assert "C1 · 46" in revision + assert "Q2" in revision + assert re.findall(r"""op\.create_table\(\s*["'](\w+)["']""", upgrade) == [ + "dynamic_parameters", + "dynamic_parameter_values", + ] + assert sorted( + re.findall(r"""op\.create_index\(\s*(?:op\.f\()?["'](\w+)["']""", upgrade) + ) == [ + "ix_dynamic_parameter_values_parameter_period", + "ix_dynamic_parameters_tax_benefit_model_version_id", + "uq_dynamic_parameter_values_current_law_parameter_start_date", + "uq_dynamic_parameter_values_dynamic_parameter_start_date", + ] + assert sorted(re.findall(r"""op\.drop_table\(\s*["'](\w+)["']""", downgrade)) == [ + "dynamic_parameter_values", + "dynamic_parameters", + ] + assert revision.count("Approved hand-written data step") == 2 + assert "Post-generation correction" not in revision + assert "op.bulk_insert(" not in revision + move = upgrade.index("_move_dynamic_parameters_into_their_tables()") + assert upgrade.rindex("op.create_index(") < move + move_back = downgrade.index("_move_dynamic_parameters_back()") + assert move_back < downgrade.index("op.drop_index(") + for table in ("parameters", "parameter_values", "parameter_tree_children"): + assert f'op.drop_table("{table}")' not in revision + + +def test_dynamic_parameter_tables_revision_keeps_its_own_copy_of_the_prefixes() -> None: + """The revision classifies with a frozen copy that matches the package's. + + A revision runs once per database, so it never imports application code + that may change; publication compares the installed version's rows with + the package's own classification right after it. + """ + path = _dynamic_parameter_tables_revision_path() + source = path.read_text(encoding="utf-8") + spec = importlib.util.spec_from_file_location("dynamic_parameter_tables", path) + assert spec is not None + assert spec.loader is not None + revision = importlib.util.module_from_spec(spec) + spec.loader.exec_module(revision) + + assert "policyengine_api" not in source + package_prefixes = dict(DYNAMIC_PARAMETER_PREFIXES) + assert package_prefixes == revision.DYNAMIC_PARAMETER_PREFIXES diff --git a/tests/unit/v2/test_catalog_publication.py b/tests/unit/v2/test_catalog_publication.py index b154afab6..fb41c7cec 100644 --- a/tests/unit/v2/test_catalog_publication.py +++ b/tests/unit/v2/test_catalog_publication.py @@ -38,7 +38,14 @@ CatalogPublicationError, ) from policyengine_api.data.v2.migration_target import V2_ALEMBIC_HEAD_REVISION -from tests.fixtures.v2_catalog import normalized_catalog +from policyengine_api.dynamic_parameters import ( + is_dynamic_parameter, + is_dynamic_parameter_path, +) +from tests.fixtures.v2_catalog import ( + catalog_with_dynamic_parameters, + normalized_catalog, +) REPO = Path(__file__).parents[3] @@ -287,12 +294,13 @@ def test_completion_evidence_contains_only_reviewed_non_secret_fields() -> None: time_period_updates=(("us", "6.7.5", (2035, 2034, 2023, 2022), (2035, 2034)),), parameter_trees_written=(("policyengine-uk", "6.7.5", 2_430),), parameter_search_files_written=(("policyengine-uk", "6.7.5", 412_000, 61_000),), - restored_catalog_versions=(("uk", "6.7.4", 1_172_130),), + restored_catalog_versions=(("uk", "6.7.4", 1_172_130, 218),), pruned_catalog_versions=( publication_types.PrunedCatalogVersion( country_id="us", policyengine_version="6.6.0", parameter_values=1_172_130, + dynamic_parameter_values=218, parameter_tree_children=101_000, parameter_search_files=1, ), @@ -364,6 +372,7 @@ def test_completion_evidence_contains_only_reviewed_non_secret_fields() -> None: "country_id": "uk", "policyengine_version": "6.7.4", "parameter_values": 1_172_130, + "dynamic_parameter_values": 218, } ], "pruned_catalog_versions": [ @@ -372,6 +381,7 @@ def test_completion_evidence_contains_only_reviewed_non_secret_fields() -> None: "policyengine_version": "6.6.0", "deleted_rows": { "parameter_values": 1_172_130, + "dynamic_parameter_values": 218, "parameter_tree_children": 101_000, "parameter_search_files": 1, }, @@ -458,6 +468,41 @@ def test_a_catalog_tree_needs_a_stored_row_for_every_parameter() -> None: catalog_parameter_tree(country, {}) +@pytest.mark.parametrize("country_id", ["us", "uk"]) +def test_a_catalog_tree_leaves_out_model_assumptions_and_their_folders( + country_id: str, +) -> None: + """The policy tree holds only policy parameters, from catalog format 2 on. + + Model assumptions are stored in ``dynamic_parameters``, so the tree needs + stored rows only for the other parameters, and neither the assumptions nor + their folders (``gov.simulation``, US ``simulation``, UK ``gov.dynamic``) + are rows of it, although the nodes table holds those folders. + """ + country = catalog_with_dynamic_parameters().country(country_id) + policy_parameter_ids = { + parameter.name: uuid4() + for parameter in country.parameters + if not is_dynamic_parameter(country_id, parameter.name) + } + assert any( + is_dynamic_parameter_path(country_id, node.name) + for node in country.parameter_nodes + ) + + rows = catalog_parameter_tree(country, policy_parameter_ids) + + assert {row.path for row in rows if row.child_type == "parameter"} == set( + policy_parameter_ids + ) + assert not [ + row.path for row in rows if is_dynamic_parameter_path(country_id, row.path) + ] + assert {row.path for row in rows if row.parent_path == ""} == {"gov"} + (gov,) = (row for row in rows if row.path == "gov") + assert gov.child_count == 1 + + def _kept_region_records( monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, diff --git a/tests/unit/v2/test_dynamic_catalog.py b/tests/unit/v2/test_dynamic_catalog.py index bce593759..fdab57462 100644 --- a/tests/unit/v2/test_dynamic_catalog.py +++ b/tests/unit/v2/test_dynamic_catalog.py @@ -1,8 +1,10 @@ """Binding dynamics and policies to a catalog, and keeping their parameters apart. A dynamic holds only parameters under ``gov.simulation.`` (plus the US's -``simulation.`` and the UK's ``gov.dynamic.``), and a policy holds none of -them; each is refused with the parameter names it may not set. +``simulation.`` and the UK's ``gov.dynamic.``), which are stored in +``dynamic_parameters`` (C1 · 50), and a policy holds none of them; each is +refused with the parameter names it may not set, found in the other table. +A dynamic's values are stored in ``dynamic_parameter_values``. """ from __future__ import annotations @@ -13,6 +15,7 @@ import pytest from pydantic import ValidationError from sqlalchemy.exc import OperationalError, SQLAlchemyError +from sqlmodel import select from policyengine_api.data.v2.catalog.catalog_selection_validation import ( MetadataCatalogUnavailableError, @@ -20,10 +23,14 @@ from policyengine_api.data.v2.models import ( V2_REGISTRY, Dynamic, + DynamicParameter, + DynamicParameterValue, Parameter, + ParameterValue, TaxBenefitModel, TaxBenefitModelVersion, ) +from policyengine_api.dynamic_parameters import is_dynamic_parameter from policyengine_api.services.v2.dynamics.database_session import ( DynamicDatabaseSession, ) @@ -66,6 +73,25 @@ RUNNING_VERSION = "5.2.0" +def _store_parameters( + session: Session, + version: TaxBenefitModelVersion, + country_id: str, + names: tuple[str, ...], +) -> dict[str, UUID]: + """Store each parameter in its own table, as catalog publication does.""" + parameter_ids: dict[str, UUID] = {} + for name in names: + parameter_class = ( + DynamicParameter if is_dynamic_parameter(country_id, name) else Parameter + ) + parameter = parameter_class(name=name, tax_benefit_model_version=version) + session.add(parameter) + parameter_ids[name] = parameter.id + session.commit() + return parameter_ids + + class Catalog: """A US catalog version with two dynamic parameters and one policy parameter.""" @@ -77,12 +103,12 @@ def __init__(self, session: Session) -> None: current_law_id=1, metadata_time_periods=[2026], ) - self.parameter_ids = {} - for name in (INCOME_ELASTICITY, MARGINAL_TAX_RATE_DELTA, TAX_RATE): - parameter = Parameter(name=name, tax_benefit_model_version=self.version) - session.add(parameter) - self.parameter_ids[name] = parameter.id - session.commit() + self.parameter_ids = _store_parameters( + session, + self.version, + "us", + (INCOME_ELASTICITY, MARGINAL_TAX_RATE_DELTA, TAX_RATE), + ) @pytest.fixture @@ -305,12 +331,12 @@ def __init__(self, session: Session) -> None: current_law_id=1, metadata_time_periods=[2026], ) - self.parameter_ids = {} - for name in (UK_OBR_LABOUR_SUPPLY_SWITCH, UK_INCOME_ELASTICITY, UK_TAX_RATE): - parameter = Parameter(name=name, tax_benefit_model_version=self.version) - session.add(parameter) - self.parameter_ids[name] = parameter.id - session.commit() + self.parameter_ids = _store_parameters( + session, + self.version, + "uk", + (UK_OBR_LABOUR_SUPPLY_SWITCH, UK_INCOME_ELASTICITY, UK_TAX_RATE), + ) @pytest.fixture @@ -389,3 +415,93 @@ def test_a_uk_dynamic_setting_a_policy_parameter_names_gov_dynamic_as_allowed( assert refusal.value.parameter_names == (UK_TAX_RATE,) assert "gov.dynamic" in str(refusal.value) + + +def _service(sessions: sessionmaker[Session]) -> V2DynamicService: + return V2DynamicService( + DynamicDatabaseSession(sessions), + running_policyengine_version=RUNNING_VERSION, + ) + + +def test_a_created_dynamic_keeps_its_values_in_their_own_table( + sessions: sessionmaker[Session], catalog: Catalog +) -> None: + created = _service(sessions).create_dynamic( + NativeDynamicCreationInput( + **_dynamic_input( + catalog, INCOME_ELASTICITY, MARGINAL_TAX_RATE_DELTA + ).model_dump() + ) + ) + + assert created.created + with sessions() as session: + stored = session.exec(select(DynamicParameterValue)).all() + assert { + (value.dynamic_parameter_id, value.dynamic_id, value.value_json) + for value in stored + } == { + (catalog.parameter_ids[INCOME_ELASTICITY], created.item.id, 0.25), + (catalog.parameter_ids[MARGINAL_TAX_RATE_DELTA], created.item.id, 0.25), + } + assert session.exec(select(ParameterValue)).all() == [] + read = _service(sessions).get_dynamic(country_id="us", dynamic_id=created.item.id) + assert [ + (value.parameter_id, value.parameter_name) for value in read.parameter_values + ] == [ + (catalog.parameter_ids[INCOME_ELASTICITY], INCOME_ELASTICITY), + (catalog.parameter_ids[MARGINAL_TAX_RATE_DELTA], MARGINAL_TAX_RATE_DELTA), + ] + assert read.missing_parameters == () + + +def test_identical_dynamic_content_is_found_from_its_stored_values( + sessions: sessionmaker[Session], catalog: Catalog +) -> None: + content = NativeDynamicCreationInput( + **_dynamic_input(catalog, INCOME_ELASTICITY).model_dump() + ) + first = _service(sessions).create_dynamic(content) + + again = _service(sessions).create_dynamic(content) + + assert not again.created + assert again.item.id == first.item.id + with sessions() as session: + assert len(session.exec(select(DynamicParameterValue)).all()) == 1 + + +def test_a_dynamic_lists_the_assumptions_the_running_catalog_lacks( + sessions: sessionmaker[Session], session: Session, catalog: Catalog +) -> None: + """``missing_parameters`` looks the names up among dynamic parameters.""" + older = TaxBenefitModelVersion( + model=catalog.model, + version="5.1.0", + current_law_id=1, + metadata_time_periods=[2026], + ) + older_ids = _store_parameters( + session, + older, + "us", + (INCOME_ELASTICITY, "gov.simulation.retired_assumption"), + ) + created = _service(sessions).create_dynamic( + NativeDynamicCreationInput( + country_id="us", + tax_benefit_model_id=catalog.model.id, + policyengine_version="5.1.0", + parameter_values=[ + { + "parameter_id": parameter_id, + "value": 0.25, + "start_date": "2026-01-01T00:00:00Z", + } + for parameter_id in older_ids.values() + ], + ) + ) + + assert created.item.missing_parameters == ("gov.simulation.retired_assumption",) diff --git a/tests/unit/v2/test_dynamic_parameter_move_qualification.py b/tests/unit/v2/test_dynamic_parameter_move_qualification.py new file mode 100644 index 000000000..08d7708f6 --- /dev/null +++ b/tests/unit/v2/test_dynamic_parameter_move_qualification.py @@ -0,0 +1,127 @@ +"""The read-only check that runs before C1 · 50's revision moves dynamic parameters. + +While revision 7f7335f0eb31 is pending, the seed workflow counts the policy +values that name a dynamic parameter, in one READ ONLY transaction, and stops +before the schema upgrade while there are any. The revision refuses the same +rows itself; this step stops the deploy before Alembic runs at all. +""" + +from __future__ import annotations + +import json + +import pytest + +from policyengine_api.data.v2 import dynamic_parameter_move_qualification as move +from policyengine_api.data.v2.settings import ( + V2_MIGRATION_DATABASE_URL, + V2_SUPABASE_ENVIRONMENT, + V2_SUPABASE_PROJECT_REF, + load_v2_migration_database_settings, +) +from tests.unit.v2.qualification_sessions import ( + CountingSession, + QualificationSessions, + serve_read_only_sessions, +) + +ENVIRONMENT = { + V2_MIGRATION_DATABASE_URL: ( + "postgresql+psycopg://migration:test-password@db." + "abcdefghijklmnopqrst.supabase.co/postgres?sslmode=require" + ), + V2_SUPABASE_PROJECT_REF: "abcdefghijklmnopqrst", + V2_SUPABASE_ENVIRONMENT: "staging", +} + + +def test_the_check_belongs_to_the_dynamic_parameter_tables_revision() -> None: + assert move.DYNAMIC_PARAMETER_TABLES_REVISION == "7f7335f0eb31" + + +def test_a_pending_move_with_no_such_value_is_qualified_read_only( + monkeypatch: pytest.MonkeyPatch, +) -> None: + session = CountingSession((0,)) + sessions = QualificationSessions(session) + read_only_urls = serve_read_only_sessions(monkeypatch, sessions) + + evidence = move.qualify_dynamic_parameter_move_if_pending( + ENVIRONMENT, pending_checker=lambda _session: True + ) + + assert evidence.as_dict() == { + "outcome": "ok", + "qualification": "performed", + "environment": "staging", + "project_ref": "abcdefghijklmnopqrst", + "counts": {"policy_values_naming_dynamic_parameters": 0}, + } + assert read_only_urls == [ + load_v2_migration_database_settings(ENVIRONMENT).connection.url + ] + assert len(session.statements) == 1 + assert "starts_with" in session.statements[0] + assert session.rolled_back + assert sessions.closed + + +def test_an_applied_move_reads_no_rows(monkeypatch: pytest.MonkeyPatch) -> None: + session = CountingSession((5,)) + sessions = QualificationSessions(session) + serve_read_only_sessions(monkeypatch, sessions) + + evidence = move.qualify_dynamic_parameter_move_if_pending( + ENVIRONMENT, pending_checker=lambda _session: False + ) + + assert evidence.as_dict()["qualification"] == "not-required" + assert evidence.as_dict()["counts"] == { + "policy_values_naming_dynamic_parameters": 0 + } + assert session.statements == [] + assert session.rolled_back + + +@pytest.mark.parametrize("count", [1, 13]) +def test_policy_values_naming_dynamic_parameters_stop_the_deploy(count: int) -> None: + session = CountingSession((count,)) + sessions = QualificationSessions(session) + + with pytest.raises( + move.PolicyValuesNameDynamicParametersError, + match=f"{count} policy values? names? (a )?dynamic parameters?", + ) as raised: + move.qualify_dynamic_parameter_move_if_pending( + ENVIRONMENT, + session_factories=sessions, + pending_checker=lambda _session: True, + ) + + assert raised.value.count == count + assert "C1 · 49" in str(raised.value) + assert session.rolled_back + + +def test_main_prints_the_refusal_and_redacts_unexpected_errors( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + def refuse() -> None: + raise move.PolicyValuesNameDynamicParametersError(2) + + monkeypatch.setattr(move, "qualify_dynamic_parameter_move_if_pending", refuse) + assert move.main() == 1 + refusal = json.loads(capsys.readouterr().err) + assert refusal["error"]["type"] == "PolicyValuesNameDynamicParametersError" + assert "2 policy values" in refusal["error"]["message"] + + def fail() -> None: + msg = "postgresql://user:secret@private-host/database" + raise RuntimeError(msg) + + monkeypatch.setattr(move, "qualify_dynamic_parameter_move_if_pending", fail) + assert move.main() == 1 + captured = capsys.readouterr() + assert "qualification failed unexpectedly" in captured.err + assert "secret" not in captured.err + assert "private-host" not in captured.err diff --git a/tests/unit/v2/test_dynamic_parameter_table_models.py b/tests/unit/v2/test_dynamic_parameter_table_models.py new file mode 100644 index 000000000..a4658d0e9 --- /dev/null +++ b/tests/unit/v2/test_dynamic_parameter_table_models.py @@ -0,0 +1,231 @@ +"""Dynamic parameters and their values have tables of their own (C1 · 50). + +``dynamic_parameters`` has ``parameters``' columns, IDs and unique name per +catalog version. ``dynamic_parameter_values`` holds their current-law values +(no dynamic) and every dynamic's values, with no policy: one current-law value +per parameter and start date, and one per dynamic, parameter and start date. +""" + +from collections.abc import Iterator +from contextlib import contextmanager +from datetime import UTC, datetime + +import pytest +from sqlalchemy.exc import IntegrityError +from sqlalchemy.orm import sessionmaker +from sqlmodel import Session, select + +from policyengine_api.data.v2.models import ( + Dynamic, + DynamicParameter, + DynamicParameterValue, + Parameter, + TaxBenefitModel, + TaxBenefitModelVersion, +) +from tests.fixtures.database_sessions import sqlite_v2_sessions +from tests.fixtures.v2_countries import add_listed_countries +from tests.unit.v2.v2_schema_reading import ( + declared_index, + model_columns, + stored_v2_table, +) + +START_DATE = datetime(2026, 1, 1, tzinfo=UTC) +ELASTICITY = "gov.simulation.labor_supply_responses.elasticities.income" + + +@contextmanager +def _sqlite_sessions_with_foreign_keys() -> Iterator[sessionmaker[Session]]: + with sqlite_v2_sessions(foreign_keys=True) as sessions: + with sessions(expire_on_commit=True) as session: + add_listed_countries(session) + yield sessions + + +def _catalog( + session: Session, +) -> tuple[TaxBenefitModel, TaxBenefitModelVersion, DynamicParameter]: + model = TaxBenefitModel(name="policyengine-us") + version = TaxBenefitModelVersion( + model=model, version="2.2.2", current_law_id=1, metadata_time_periods=[2026] + ) + parameter = DynamicParameter(name=ELASTICITY, tax_benefit_model_version=version) + session.add_all([model, version, parameter]) + session.commit() + return model, version, parameter + + +def _dynamic( + session: Session, model: TaxBenefitModel, version: TaxBenefitModelVersion +) -> Dynamic: + dynamic = Dynamic( + country_id="us", + tax_benefit_model_id=model.id, + tax_benefit_model_version_id=version.id, + canonicalization_version=1, + content_hash="d" * 64, + ) + session.add(dynamic) + session.commit() + return dynamic + + +def test_dynamic_parameters_have_policy_parameters_columns_and_name_rule() -> None: + dynamic_parameters = stored_v2_table("dynamic_parameters") + + assert { + name: (str(column.type), column.nullable) + for name, column in dynamic_parameters.columns.items() + } == { + name: (str(column.type), column.nullable) + for name, column in stored_v2_table("parameters").columns.items() + } + assert dynamic_parameters.unique_constraints == { + "uq_dynamic_parameters_model_version_name": ( + "tax_benefit_model_version_id", + "name", + ) + } + assert dynamic_parameters.references_by_column == { + "tax_benefit_model_version_id": ("tax_benefit_model_versions", "CASCADE"), + } + + +def test_dynamic_parameter_values_name_a_dynamic_parameter_and_no_policy() -> None: + values = stored_v2_table("dynamic_parameter_values") + columns = model_columns("dynamic_parameter_values") + + assert set(values.columns) == { + "id", + "created_at", + "dynamic_parameter_id", + "value_json", + "start_date", + "end_date", + "dynamic_id", + } + assert not columns.dynamic_parameter_id.nullable + assert columns.dynamic_id.nullable + assert columns.end_date.nullable + assert values.references_by_column == { + "dynamic_parameter_id": ("dynamic_parameters", "CASCADE"), + "dynamic_id": ("dynamics", "CASCADE"), + } + assert set(values.checks) == {"ck_dynamic_parameter_values_effective_period"} + assert values.index_columns["ix_dynamic_parameter_values_parameter_period"] == ( + "dynamic_parameter_id", + "start_date", + "end_date", + ) + + +@pytest.mark.parametrize( + ("index_name", "columns", "condition"), + [ + ( + "uq_dynamic_parameter_values_current_law_parameter_start_date", + ("dynamic_parameter_id", "start_date"), + "dynamic_id IS NULL", + ), + ( + "uq_dynamic_parameter_values_dynamic_parameter_start_date", + ("dynamic_id", "dynamic_parameter_id", "start_date"), + "dynamic_id IS NOT NULL", + ), + ], +) +def test_values_are_unique_per_owner_parameter_and_start_date_in_both_dialects( + index_name: str, columns: tuple[str, ...], condition: str +) -> None: + index = declared_index(DynamicParameterValue, index_name) + + assert index.unique + assert tuple(column.name for column in index.columns) == columns + assert str(index.dialect_options["postgresql"]["where"]) == condition + assert str(index.dialect_options["sqlite"]["where"]) == condition + + +def test_a_dynamic_s_value_must_name_a_dynamic_parameter() -> None: + with ( + _sqlite_sessions_with_foreign_keys() as sessions, + sessions(expire_on_commit=True) as session, + ): + model, version, _parameter = _catalog(session) + policy_parameter = Parameter( + name="gov.irs.rate", tax_benefit_model_version=version + ) + session.add(policy_parameter) + session.commit() + dynamic = _dynamic(session, model, version) + session.add( + DynamicParameterValue( + dynamic_parameter_id=policy_parameter.id, + dynamic_id=dynamic.id, + value_json=0.1, + start_date=START_DATE, + ) + ) + with pytest.raises(IntegrityError, match="FOREIGN KEY constraint failed"): + session.commit() + + +def test_one_current_law_value_and_one_value_per_dynamic_for_each_start_date() -> None: + with ( + _sqlite_sessions_with_foreign_keys() as sessions, + sessions(expire_on_commit=True) as session, + ): + model, version, parameter = _catalog(session) + dynamic = _dynamic(session, model, version) + session.add_all( + [ + DynamicParameterValue( + dynamic_parameter_id=parameter.id, + value_json=0.1, + start_date=START_DATE, + ), + DynamicParameterValue( + dynamic_parameter_id=parameter.id, + dynamic_id=dynamic.id, + value_json=0.2, + start_date=START_DATE, + ), + ] + ) + session.commit() + for owner in (None, dynamic.id): + session.add( + DynamicParameterValue( + dynamic_parameter_id=parameter.id, + dynamic_id=owner, + value_json=0.3, + start_date=START_DATE, + ) + ) + with pytest.raises(IntegrityError, match="UNIQUE constraint failed"): + session.commit() + session.rollback() + + +def test_a_dynamic_lists_its_values_and_deleting_it_deletes_them() -> None: + with ( + _sqlite_sessions_with_foreign_keys() as sessions, + sessions(expire_on_commit=True) as session, + ): + model, version, parameter = _catalog(session) + dynamic = _dynamic(session, model, version) + value = DynamicParameterValue( + dynamic_parameter_id=parameter.id, + dynamic_id=dynamic.id, + value_json=0.2, + start_date=START_DATE, + ) + session.add(value) + session.commit() + + assert [stored.id for stored in dynamic.parameter_values] == [value.id] + assert [stored.id for stored in parameter.values] == [value.id] + session.delete(dynamic) + session.commit() + assert session.exec(select(DynamicParameterValue)).all() == [] + assert session.get(DynamicParameter, parameter.id) is not None diff --git a/tests/unit/v2/test_import_side_effects.py b/tests/unit/v2/test_import_side_effects.py index 0922b5caf..a43b87b5a 100644 --- a/tests/unit/v2/test_import_side_effects.py +++ b/tests/unit/v2/test_import_side_effects.py @@ -69,9 +69,13 @@ def reject_ddl(*args, **kwargs): import sys after = set(pathlib.Path.cwd().iterdir()) assert before == after -assert len(V2_METADATA.tables) == 52 +assert len(V2_METADATA.tables) == 54 assert "policyengine_api.data.v2.catalog.initialization" not in sys.modules assert "policyengine_api.data.v2.policy_migration_qualification" not in sys.modules +assert ( + "policyengine_api.data.v2.dynamic_parameter_move_qualification" + not in sys.modules +) assert "policyengine_api.data.v2.household_migration_qualification" not in sys.modules assert ( "policyengine_api.data.v2.user_association_migration_qualification" diff --git a/tests/unit/v2/test_metadata_deployment.py b/tests/unit/v2/test_metadata_deployment.py index 12388568d..9baff31c2 100644 --- a/tests/unit/v2/test_metadata_deployment.py +++ b/tests/unit/v2/test_metadata_deployment.py @@ -131,6 +131,29 @@ def test_user_association_qualification_precedes_schema_upgrade() -> None: assert household_qualification < user_association_qualification < upgrade +def test_dynamic_parameter_move_qualification_precedes_schema_upgrade() -> None: + """The read-only check before C1 · 50's revision runs last, as the migrator.""" + workflow = _read(".github/workflows/seed-v2-database.yml") + + user_association_qualification = workflow.index( + "scripts/qualify_v2_user_association_migration.py" + ) + move_qualification = workflow.index("scripts/qualify_v2_dynamic_parameter_move.py") + upgrade = workflow.index("migrate_v2_metadata_schema.sh") + step = _step( + workflow, + "Qualify the pending dynamic parameter move", + "Upgrade and verify the v2 schema", + ) + + assert user_association_qualification < move_qualification < upgrade + assert "uv run --frozen python scripts/qualify_v2_dynamic_parameter_move.py" in ( + step + ) + assert "V2_MIGRATION_DATABASE_URL: ${{ secrets.V2_MIGRATION_DATABASE_URL }}" in step + assert "V2_DATA_WRITE_DATABASE_URL" not in step + + def test_declared_privileges_are_granted_and_verified_before_catalog_seeding() -> None: workflow = _read(".github/workflows/seed-v2-database.yml") diff --git a/tests/unit/v2/test_metadata_search_file_routes.py b/tests/unit/v2/test_metadata_search_file_routes.py index 778c4aee1..0eeefcccd 100644 --- a/tests/unit/v2/test_metadata_search_file_routes.py +++ b/tests/unit/v2/test_metadata_search_file_routes.py @@ -44,7 +44,7 @@ SEARCH_FILE_CONTENT: ParameterSearchFileDocument = { - "format": 1, + "format": 2, "country_id": "us", "policyengine_version": "4.20.3", "parameters": [ @@ -65,7 +65,7 @@ def _search_file_reader(*, error: Exception | None = None) -> ResourceReader: encoded = encode_parameter_search_file(SEARCH_FILE_CONTENT) stored = MetadataParameterSearchFile( policyengine_version="4.20.3", - file_format=1, + file_format=2, compressed_content=encoded.compressed_content, content_sha256=encoded.content_sha256, uncompressed_size=encoded.uncompressed_size, @@ -137,7 +137,7 @@ def test_a_large_uncompressed_search_file_names_accept_encoding_once_in_vary() - encoded = encode_parameter_search_file(content) stored = MetadataParameterSearchFile( policyengine_version="4.20.3", - file_format=1, + file_format=2, compressed_content=encoded.compressed_content, content_sha256=encoded.content_sha256, uncompressed_size=encoded.uncompressed_size, diff --git a/tests/unit/v2/test_metadata_service.py b/tests/unit/v2/test_metadata_service.py index 9632e5612..5f4779a70 100644 --- a/tests/unit/v2/test_metadata_service.py +++ b/tests/unit/v2/test_metadata_service.py @@ -657,7 +657,7 @@ def test_the_selected_version_search_file_is_returned_as_stored( catalog_session.add( ParameterSearchFile( tax_benefit_model_version_id=model_version.id, - file_format=1, + file_format=2, compressed_content=encoded.compressed_content, content_sha256=encoded.content_sha256, uncompressed_size=encoded.uncompressed_size, @@ -673,7 +673,7 @@ def test_the_selected_version_search_file_is_returned_as_stored( assert content_sha256 == encoded.content_sha256 assert search_file.policyengine_version == POLICYENGINE_VERSION - assert search_file.file_format == 1 + assert search_file.file_format == 2 assert search_file.compressed_content == encoded.compressed_content assert search_file.content_sha256 == encoded.content_sha256 assert search_file.uncompressed_size == encoded.uncompressed_size diff --git a/tests/unit/v2/test_metadata_service_pruned_versions.py b/tests/unit/v2/test_metadata_service_pruned_versions.py index 965cf38b3..8f42df5cc 100644 --- a/tests/unit/v2/test_metadata_service_pruned_versions.py +++ b/tests/unit/v2/test_metadata_service_pruned_versions.py @@ -98,7 +98,7 @@ def _add_us_tree_row_and_search_file(session: Session) -> None: session.add( ParameterSearchFile( tax_benefit_model_version_id=model_version.id, - file_format=1, + file_format=2, compressed_content=encoded.compressed_content, content_sha256=encoded.content_sha256, uncompressed_size=encoded.uncompressed_size, diff --git a/tests/unit/v2/test_parameter_search_file.py b/tests/unit/v2/test_parameter_search_file.py index 5a70e7b56..6835574a8 100644 --- a/tests/unit/v2/test_parameter_search_file.py +++ b/tests/unit/v2/test_parameter_search_file.py @@ -77,7 +77,7 @@ def _file( def test_the_file_names_its_format_country_and_version() -> None: search_file = _file([]) - assert search_file["format"] == PARAMETER_SEARCH_FILE_FORMAT == 1 + assert search_file["format"] == PARAMETER_SEARCH_FILE_FORMAT == 2 assert search_file["country_id"] == "uk" assert search_file["policyengine_version"] == "6.10.0" assert search_file["parameters"] == [] @@ -85,6 +85,55 @@ def test_the_file_names_its_format_country_and_version() -> None: assert search_file["nodes"] == [] +def test_model_assumptions_and_their_folders_are_left_out() -> None: + """From format 2, a file lists only policy parameters (C1 · 50). + + A UK model assumption is under ``gov.simulation.`` or ``gov.dynamic.``; + neither it nor those folders are listed, changeable or not. + """ + search_file = _file( + [ + _parameter("gov.hmrc.rate"), + _parameter("gov.hmrc.hidden", flags=(False, False)), + _parameter("gov.simulation.labour_supply_responses.income_elasticity"), + _parameter("gov.simulation.unflagged", flags=(None, None)), + _parameter("gov.dynamic.obr_labour_supply_assumptions"), + ], + nodes=[ + TreeNodeSource(name="gov", label="Government"), + TreeNodeSource(name="gov.hmrc", label="HMRC"), + TreeNodeSource(name="gov.simulation", label="Simulation"), + TreeNodeSource( + name="gov.simulation.labour_supply_responses", + label="Labour supply responses", + ), + TreeNodeSource(name="gov.dynamic", label="Dynamic"), + ], + ) + + assert [entry["path"] for entry in search_file["parameters"]] == ["gov.hmrc.rate"] + assert search_file["other_parameters"] == [ + {"path": "gov.hmrc.hidden", "label": None} + ] + assert [node["path"] for node in search_file["nodes"]] == ["gov", "gov.hmrc"] + + +def test_another_country_s_assumption_folder_is_a_policy_folder() -> None: + """Only the UK keeps model assumptions under ``gov.dynamic.``.""" + search_file = build_parameter_search_file( + country_id="us", + policyengine_version="6.10.0", + parameters=[_parameter("gov.dynamic.example"), _parameter("gov.simulation.x")], + nodes=[TreeNodeSource(name="gov.dynamic", label="Dynamic scoring")], + editability=_always_editable("gov.dynamic.example", "gov.simulation.x"), + ) + + assert [entry["path"] for entry in search_file["parameters"]] == [ + "gov.dynamic.example" + ] + assert [node["path"] for node in search_file["nodes"]] == ["gov.dynamic"] + + def test_each_changeable_parameter_has_what_v3_search_indexes() -> None: search_file = _file( [ diff --git a/tests/unit/v2/test_policy_legacy_copy.py b/tests/unit/v2/test_policy_legacy_copy.py index b0b0d9fa2..b13f0bf2d 100644 --- a/tests/unit/v2/test_policy_legacy_copy.py +++ b/tests/unit/v2/test_policy_legacy_copy.py @@ -14,11 +14,13 @@ import pytest from policyengine_api.data.v2.models import ( + DynamicParameter, LegacyPolicyMapping, Parameter, TaxBenefitModel, TaxBenefitModelVersion, ) +from policyengine_api.dynamic_parameters import is_dynamic_parameter from policyengine_api.services.v2.dynamics import services as dynamic_services from policyengine_api.services.v2.dynamics.types import ( DynamicCreationResult, @@ -90,7 +92,12 @@ def catalog_session(): def _add_running_catalog( session: Session, *, country_id: str, parameter_names: list[str] -) -> tuple[TaxBenefitModelVersion, dict[str, Parameter]]: +) -> tuple[TaxBenefitModelVersion, dict[str, Parameter | DynamicParameter]]: + """Store the running catalog, each parameter in its own table (C1 · 50). + + Model assumptions are ``dynamic_parameters`` rows, the rest ``parameters`` + rows, as catalog publication stores them. + """ model = TaxBenefitModel(name=f"policyengine-{country_id}") version = TaxBenefitModelVersion( model=model, @@ -98,8 +105,10 @@ def _add_running_catalog( current_law_id=1, metadata_time_periods=[2026], ) - parameters = { - name: Parameter(name=name, tax_benefit_model_version=version) + parameters: dict[str, Parameter | DynamicParameter] = { + name: ( + DynamicParameter if is_dynamic_parameter(country_id, name) else Parameter + )(name=name, tax_benefit_model_version=version) for name in parameter_names } session.add(version) @@ -559,3 +568,44 @@ def test_a_copy_that_loses_the_mapping_race_reports_the_mapped_dynamic( dynamic_id=None, dynamic_created=False, ) + + +def test_a_policy_parameter_and_an_assumption_of_the_same_name_stay_apart( + catalog_session: Session, recorded_writes: RecordedCopyWrites +) -> None: + """The copy looks each part's names up in its own table. + + A model assumption found only among policy parameters is missing from the + running catalog, as it would be after C1 · 50's revision moved it, and the + copy fails before anything is written. + """ + model = TaxBenefitModel(name="policyengine-us") + version = TaxBenefitModelVersion( + model=model, + version=RUNNING_POLICYENGINE_VERSION, + current_law_id=1, + metadata_time_periods=[2026], + ) + catalog_session.add_all( + [ + version, + Parameter(name="gov.dol.minimum_wage", tax_benefit_model_version=version), + Parameter(name=US_INCOME_ELASTICITY, tax_benefit_model_version=version), + ] + ) + catalog_session.commit() + snapshot = _snapshot( + country_id="us", + legacy_policy_id=502, + api_version="1.600.0", + policy_json={ + "gov.dol.minimum_wage": {"2026": 9}, + US_INCOME_ELASTICITY: {"2026": 0.25}, + }, + ) + + with pytest.raises(LegacyPolicyTranslationError) as failure: + _copy(catalog_session, snapshot) + + assert failure.value.reason is LegacyPolicyTranslationReason.MISSING_PARAMETERS + assert recorded_writes == RecordedCopyWrites() diff --git a/tests/unit/v2/test_privilege_manifest.py b/tests/unit/v2/test_privilege_manifest.py index 25adbf971..f40112f51 100644 --- a/tests/unit/v2/test_privilege_manifest.py +++ b/tests/unit/v2/test_privilege_manifest.py @@ -165,6 +165,8 @@ "datasets", "parameters", "parameter_values", + "dynamic_parameters", + "dynamic_parameter_values", } ) RESULT_TABLES = frozenset( @@ -418,16 +420,19 @@ def test_the_catalog_writer_may_analyze_the_tables_publication_refreshes() -> No for table, privileges in writer_tables.items() if TablePrivilege.MAINTAIN in privileges } == set(CATALOG_STATISTICS_TABLES) + assert {"dynamic_parameters", "dynamic_parameter_values"} <= set( + CATALOG_STATISTICS_TABLES + ) def test_the_catalog_writer_deletes_only_the_rows_catalog_pruning_removes() -> None: - """Catalog pruning deletes from three tables and marks the pruned version. + """Catalog pruning deletes from four tables and marks the pruned version. - It removes an older version's current-law parameter values, parameter tree - rows and parameter search file, and records the pruning on the version's - row, so the catalog writer holds DELETE on those three tables only and - UPDATE on the model versions. It never deletes parameters, model versions - or anything a policy or dynamic owns. + It removes an older version's current-law values of policy and dynamic + parameters, its parameter tree rows and its parameter search file, and + records the pruning on the version's row, so the catalog writer holds + DELETE on those four tables only and UPDATE on the model versions. It never + deletes parameters, model versions or anything a policy or dynamic owns. """ catalog_writer = declared_privileges(TEST_ENVIRONMENT)[CATALOG_WRITER_ROLE] @@ -435,7 +440,12 @@ def test_the_catalog_writer_deletes_only_the_rows_catalog_pruning_removes() -> N table for table, privileges in catalog_writer.items() if TablePrivilege.DELETE in privileges - } == {"parameter_values", "parameter_tree_children", "parameter_search_files"} + } == { + "parameter_values", + "dynamic_parameter_values", + "parameter_tree_children", + "parameter_search_files", + } assert TablePrivilege.UPDATE in catalog_writer["tax_benefit_model_versions"] # MAINTAIN is for ANALYZE after publication, not for deleting. assert catalog_writer["parameter_tree_children"] == frozenset( @@ -450,6 +460,15 @@ def test_the_catalog_writer_deletes_only_the_rows_catalog_pruning_removes() -> N {TablePrivilege.SELECT, TablePrivilege.INSERT, TablePrivilege.DELETE} ) assert catalog_writer["parameter_values"] == READ_WRITE | {TablePrivilege.MAINTAIN} + # Nothing in publication updates a value, so the new table has no UPDATE. + assert catalog_writer["dynamic_parameter_values"] == frozenset( + { + TablePrivilege.SELECT, + TablePrivilege.INSERT, + TablePrivilege.DELETE, + TablePrivilege.MAINTAIN, + } + ) def test_the_public_api_records_user_type_changes_but_never_rewrites_them() -> None: @@ -529,6 +548,37 @@ def test_api_v1_creates_and_reads_dynamics_but_never_changes_them() -> None: assert declared[CATALOG_WRITER_ROLE]["dynamics"] == NO_ACCESS +def test_dynamic_parameters_are_granted_as_policy_parameters_are() -> None: + """The two dynamic parameter tables take the policy parameter tables' grants. + + Catalog publication writes and analyzes both, and catalog pruning deletes + current-law values from the values table. API v1 reads both and inserts a + dynamic's values, which a run of the simulation service and its Modal + workers reads. Comparison runs never read them. + """ + declared = declared_privileges(TEST_ENVIRONMENT) + + for policy_table, dynamic_table in ( + ("parameters", "dynamic_parameters"), + ("parameter_values", "dynamic_parameter_values"), + ): + for role in ( + RUNTIME_ROLE, + SIMULATION_SERVICE_ROLE, + MODAL_WORKER_ROLE, + stage12_role(TEST_ENVIRONMENT), + ): + assert declared[role][dynamic_table] == declared[role][policy_table], ( + role, + dynamic_table, + ) + assert declared[RUNTIME_ROLE]["dynamic_parameter_values"] == READ_INSERT + assert ( + declared[CATALOG_WRITER_ROLE]["dynamic_parameters"] + == (declared[CATALOG_WRITER_ROLE]["parameters"]) + ) + + def test_api_v1_saves_users_dynamics_as_it_saves_their_policies() -> None: """Users' saved dynamics are written as saved policies are, by API v1 alone. From f03af9f40d830c80856b8c86be669a30e4fcc1d0 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:55:21 +0400 Subject: [PATCH 03/10] =?UTF-8?q?C1=20=C2=B7=2050:=20keep=20dynamic=20para?= =?UTF-8?q?meters=20and=20their=20values=20in=20their=20own=20tables?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit API v1 now stores model assumptions (gov.simulation., US simulation. and UK gov.dynamic.) in dynamic_parameters and their current-law values and every dynamic's values in dynamic_parameter_values (tracker task C1 · 50): - Revision 7f7335f0eb31 creates the two tables (generated) and, in its hand-written data step (the user's migration decision, C1 · 46, Q2), locks and moves every stored version's rows with their IDs, refuses while a policy value names a moved parameter, deletes the policy tree's rows under the dynamic folders after lowering their parents' child counts, and checks it deleted what it copied. Its downgrade moves the rows back and leaves the trees (decision 1). It keeps its own copy of the prefixes. - seed-v2-database.yml's new read-only step counts the same policy values before the upgrade (scripts/qualify_v2_dynamic_parameter_move.py). - Publication stages each parameter's kind, inserts, compares, restores and prunes both tables, analyzes them, counts them apart in its evidence, and builds the policy tree and the search file (now format 2) without model assumptions or their folders. - Dynamics read and write the new tables; /v2/policies and /v2/dynamics name the IDs they find in the other table in their 422s; the v1-to-v2 copy looks the assumptions up among dynamic parameters. - Every role has an entry for both tables. - alembic-migrations.md documents the revision, the decisions, the deploy order and the deploy window as the second accepted exception (decision 2); the stage 9 and stage 10 runbooks follow. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/test_alembic_v2_lifecycle.sh | 3 +- .github/workflows/seed-v2-database.yml | 4 + .github/workflows/v2-integration-check.yml | 2 +- .../v2-dynamic-parameter-tables.changed.md | 1 + docs/engineering/skills/alembic-migrations.md | 175 ++++++- docs/migration/stage-10-v2-policies.md | 16 +- docs/migration/stage-9-v2-metadata.md | 50 +- ...move_dynamic_parameters_into_their_own_.py | 474 ++++++++++++++++++ .../v2/catalog/dynamic_parameter_records.py | 70 +++ .../data/v2/catalog/parameter_search_file.py | 24 +- .../data/v2/catalog/publication.py | 28 +- .../data/v2/catalog/publication_inserts.py | 133 +++-- .../v2/catalog/publication_parameter_tree.py | 23 +- .../data/v2/catalog/publication_pruning.py | 67 ++- .../v2/catalog/publication_reconciliation.py | 156 ++++-- .../data/v2/catalog/publication_staging.py | 6 +- .../v2/catalog/publication_staging_base.py | 8 +- .../data/v2/catalog/publication_statistics.py | 2 + .../data/v2/catalog/publication_types.py | 18 +- .../dynamic_parameter_move_qualification.py | 214 ++++++++ policyengine_api/data/v2/migration_target.py | 2 +- policyengine_api/data/v2/models/__init__.py | 4 + policyengine_api/data/v2/models/metadata.py | 144 +++++- policyengine_api/data/v2/models/policies.py | 3 +- policyengine_api/data/v2/privileges.py | 22 +- policyengine_api/dynamic_parameters.py | 30 +- .../dynamics/database_connectors/creates.py | 13 +- .../v2/dynamics/database_connectors/reads.py | 77 ++- .../services/v2/dynamics/services.py | 31 +- .../services/v2/dynamics/transformations.py | 45 +- .../services/v2/dynamics/validators.py | 27 +- .../services/v2/policies/services.py | 41 +- .../services/v2/policies/transformations.py | 21 +- .../services/v2/policies/validators.py | 23 +- scripts/qualify_v2_dynamic_parameter_move.py | 7 + ...est_alembic_v2_dynamic_parameter_tables.py | 23 +- tests/unit/v2/test_dynamic_catalog.py | 16 - ...t_simulation_submission_database_routes.py | 22 +- 38 files changed, 1763 insertions(+), 262 deletions(-) create mode 100644 changelog.d/v2-dynamic-parameter-tables.changed.md create mode 100644 migrations/v2/versions/7f7335f0eb31_move_dynamic_parameters_into_their_own_.py create mode 100644 policyengine_api/data/v2/catalog/dynamic_parameter_records.py create mode 100644 policyengine_api/data/v2/dynamic_parameter_move_qualification.py create mode 100755 scripts/qualify_v2_dynamic_parameter_move.py diff --git a/.github/scripts/test_alembic_v2_lifecycle.sh b/.github/scripts/test_alembic_v2_lifecycle.sh index 0e213016b..1bea685eb 100755 --- a/.github/scripts/test_alembic_v2_lifecycle.sh +++ b/.github/scripts/test_alembic_v2_lifecycle.sh @@ -15,4 +15,5 @@ uv run --frozen --extra dev pytest -q \ tests/integration/test_alembic_v2_cliff_impacts.py \ tests/integration/test_alembic_v2_dynamics.py \ tests/integration/test_alembic_v2_report_column_drops.py \ - tests/integration/test_alembic_v2_user_dynamics.py + tests/integration/test_alembic_v2_user_dynamics.py \ + tests/integration/test_alembic_v2_dynamic_parameter_tables.py diff --git a/.github/workflows/seed-v2-database.yml b/.github/workflows/seed-v2-database.yml index 8c622a079..e9894859e 100644 --- a/.github/workflows/seed-v2-database.yml +++ b/.github/workflows/seed-v2-database.yml @@ -54,6 +54,10 @@ jobs: run: uv run --frozen python scripts/qualify_v2_user_association_migration.py env: V2_MIGRATION_DATABASE_URL: ${{ secrets.V2_MIGRATION_DATABASE_URL }} + - name: Qualify the pending dynamic parameter move + run: uv run --frozen python scripts/qualify_v2_dynamic_parameter_move.py + env: + V2_MIGRATION_DATABASE_URL: ${{ secrets.V2_MIGRATION_DATABASE_URL }} - name: Upgrade and verify the v2 schema run: bash .github/scripts/migrate_v2_metadata_schema.sh env: diff --git a/.github/workflows/v2-integration-check.yml b/.github/workflows/v2-integration-check.yml index 7ddd676db..12952ba35 100644 --- a/.github/workflows/v2-integration-check.yml +++ b/.github/workflows/v2-integration-check.yml @@ -74,7 +74,7 @@ jobs: - name: Verify the managed v2 roles hold their declared privileges 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 + 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_country_routes.py tests/integration/test_v2_report_reads.py tests/integration/test_v2_report_creation.py tests/integration/test_v2_budget_window_report_reads.py tests/integration/test_v2_budget_window_report_creation.py tests/integration/test_v2_report_runs.py tests/integration/test_v2_report_reads_by_run.py tests/integration/test_v2_user_report_runs.py tests/integration/test_v2_user_report_run_requesters.py tests/integration/test_v2_user_budget_window_runs.py tests/integration/test_v2_forced_report_reruns.py tests/integration/test_v2_user_report_views.py - name: Test v2 policy and dynamic persistence and immediate v1 mirroring run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_policy_persistence.py tests/integration/test_v2_dynamic_persistence.py tests/integration/test_v1_policy_dual_write.py tests/integration/test_mysql_policy_dual_write.py tests/integration/test_v2_user_policy_mirroring.py tests/integration/test_v1_user_policy_dual_write.py - name: Test signed-in identity provisioning, user associations, saved detailed-save records and user types diff --git a/changelog.d/v2-dynamic-parameter-tables.changed.md b/changelog.d/v2-dynamic-parameter-tables.changed.md new file mode 100644 index 000000000..8a847bc64 --- /dev/null +++ b/changelog.d/v2-dynamic-parameter-tables.changed.md @@ -0,0 +1 @@ +Model assumptions (`gov.simulation.`, US `simulation.` and UK `gov.dynamic.`) and their values are kept in their own tables, `dynamic_parameters` and `dynamic_parameter_values`. Revision `7f7335f0eb31` moves every stored version's rows there with their IDs, together with every dynamic's values, and refuses to run while a policy value names one, and a read-only step in the v2 seed workflow checks the same first. Catalog publication writes, compares, restores and prunes both tables. The parameter tree and the parameter search file, now format 2, no longer list model assumptions. Dynamics, the v1-to-v2 policy copy and the named 422s on `/v2/policies` and `/v2/dynamics` read the new tables, and every role's grants cover them. The one-time `scripts/split_v2_policy_copies.py` is removed: once its run has split the stored policy copies, it has nothing left to split. diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 5a1a64feb..2278bef46 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -546,7 +546,7 @@ and a revision runs once per database, so it can't repair drift. | Role | Used by | | --- | --- | | `policyengine_v2_runtime` | The Public API on Cloud Run | -| `policyengine_v2_catalog_writer` | `scripts/publish_v2_metadata_catalog.py`, which also runs `ANALYZE` on seven catalog tables after every publication, with `MAINTAIN` (PostgreSQL 17) | +| `policyengine_v2_catalog_writer` | `scripts/publish_v2_metadata_catalog.py`, which also runs `ANALYZE` on nine catalog tables after every publication, with `MAINTAIN` (PostgreSQL 17) | | `policyengine_stage12_` | The simulation API and its Modal worker, on the temporary comparison-run tables | | `policyengine_v2_simulation_service` | The simulation API on Cloud Run: creates simulations, reports, their runs, budget-window runs, household jobs and simulation runs' cliff calculations, and reads the policy, dynamic, household and catalog rows a run needs. It updates only the status, Modal call ID, error and completion columns of the runs, household jobs and cliff calculations whose Modal calls it starts, and the status, error and completion columns of a budget-window run, which it fails at once when Modal refuses the calls of the window's first years | | `policyengine_v2_modal_worker` | The simulation API's Modal workers: write their runs', household jobs' and cliff calculations' status and results, and budget-window runs' status, and read the rows a run needs. It updates only a run's or cliff calculation's status, Modal call ID, error, time and result columns, and a budget-window run's status, error and time columns: each year's coordinator starts the window's next unstarted year when its own year finishes, the last year to finish marks the window succeeded, and a failed year fails it. The workers' code, not the database, keeps a worker to its own run | @@ -713,23 +713,29 @@ version if the rule no longer chooses it, and otherwise deletes exactly: - the version's current-law `parameter_values`: rows of the version's parameters whose `policy_id` and `dynamic_id` are both null; +- the version's current-law `dynamic_parameter_values`: rows of the version's + dynamic parameters whose `dynamic_id` is null (since revision + `7f7335f0eb31`, by the user's decision C1 · 46, Q3); - the version's `parameter_tree_children` rows; - the version's `parameter_search_files` rows; and sets the version's `catalog_values_pruned_at` to the current time. It -never deletes or changes any other row: not `parameters` (deleting one -cascades to every value of it, saved reforms' included), not the -`tax_benefit_model_versions` row apart from that column, and not -`parameter_nodes`, `variables`, `regions`, `datasets`, `policies`, -`dynamics` or any `parameter_values` row with a `policy_id` or `dynamic_id`. +never deletes or changes any other row: not `parameters` or +`dynamic_parameters` (deleting one cascades to every value of it, saved +reforms' and dynamics' included), not the `tax_benefit_model_versions` row +apart from that column, and not `parameter_nodes`, `variables`, `regions`, +`datasets`, `policies`, `dynamics`, any `parameter_values` row with a +`policy_id` or `dynamic_id`, or any `dynamic_parameter_values` row with a +`dynamic_id`. A transaction that raises an exception, of any kind, rolls back that version alone; the failure is reported in the command's evidence and on stderr, the command still succeeds, and the next publication tries again. The deleted rows are rebuilt from the packages, not lost: when publication runs for a version whose `catalog_values_pruned_at` is set (a release that -installs it again), it inserts the version's current-law values from the -installed packages and clears the column inside the publication transaction, +installs it again), it inserts the version's current-law values of both +tables from the installed packages and clears the column inside the +publication transaction, before the usual exact comparison of the stored version, and writes the version's parameter tree and search file as it does for a version that has none. The rows it writes equal those a first publication of the version @@ -737,7 +743,7 @@ writes, with the same value IDs. Until then the metadata routes that serve the deleted rows answer 404 for that version, with `Cache-Control: no-store`, or 503 when it is the version the serving revision runs. -The catalog writer holds `DELETE` on the three tables and `UPDATE` on +The catalog writer holds `DELETE` on the four tables and `UPDATE` on `tax_benefit_model_versions` for this (`privileges.py`). Pruning runs no DDL; revision `334859ef4fec` added the nullable `catalog_last_published_at` and `catalog_values_pruned_at` columns, autogenerated with no post-generation @@ -750,6 +756,9 @@ it publishes that version, with nothing to restore it. Downgrading past the revision is therefore safe only while no version is pruned (no `tax_benefit_model_versions` row has `catalog_values_pruned_at` set). From the head, such a downgrade first runs the later revisions' downgrades: +`7f7335f0eb31`'s moves the dynamic parameters and their values back into +`parameters` and `parameter_values` and drops their tables (see "API v2 +dynamic parameters in their own tables"), `d417fe8b1b17`'s drops `user_dynamics` with every saved dynamic (see "API v2 users' saved dynamics"), `4e30076d4b9f`'s adds the dropped report columns back empty (see "API v2 report @@ -773,7 +782,9 @@ publishing each with this revision's code, as the Stage 9 runbook's rollback section describes. Production downgrades are never automatic in any case. The rule that the serving revision must work with the database changed on -its own (see "CI/CD behavior") has one accepted exception here. During the +its own (see "CI/CD behavior") has two accepted exceptions: this one, and +revision `7f7335f0eb31`'s (see "API v2 dynamic parameters in their own +tables"). During the first release that includes pruning, the seed job prunes while the previous revision, whose code doesn't read `catalog_values_pruned_at`, still serves. Until that release is promoted, and until the next successful release if @@ -790,7 +801,10 @@ before issue #4243). The Stage The maintainers' approval of this exception is the review of the pull request that added it. Deleting from another table, deleting another kind of row, or deleting rows that publication can't rebuild from the installed packages -needs the same human migration decision. +needs the same human migration decision. The user took it for +`dynamic_parameter_values`' current-law rows when model assumptions moved +there (C1 · 46, Q3), which publication rebuilds as it rebuilds +`parameter_values`'. ### Fresh database qualification @@ -826,7 +840,10 @@ shared or deployed database. seeding job only to the v2 database. Each Cloud Run candidate deploy needs both, so a candidate is never built until both databases are upgraded. When one of them fails, the release stops with the other already applied; the - serving revision must work with either database upgraded on its own. + serving revision must work with either database upgraded on its own, apart + from two accepted exceptions: catalog pruning's first release (see "Catalog + pruning: the seeder's one deletion") and revision `7f7335f0eb31` (see "API + v2 dynamic parameters in their own tables"). - Database credentials and derived URLs must never be printed. The application runtime account must not be granted schema-migration privileges. - Production downgrades are never automatic. MySQL DDL is non-transactional, so @@ -1557,3 +1574,137 @@ its unauthenticated user. The downgrade drops the table with every saved dynamic, and the dynamics they named stay. `tests/integration/test_alembic_v2_user_dynamics.py` checks that nothing else changes, the keys, deletion with the user and the downgrade. + +### API v2 dynamic parameters in their own tables + +Revision `7f7335f0eb31` (parent `d417fe8b1b17`) was autogenerated, with its ID +given by `--rev-id`, after the model gained `DynamicParameter` and +`DynamicParameterValue`. It has no post-generation correction apart from +`ruff format`, and one hand-written data step: **the user's explicit migration +decision (C1 · 46, Q2, 2026-11-25)** for C1 · 50, which "Mandatory generation +rule" and "V2 application-data migrations" require, as the `countries` +revision's insert and catalog pruning had theirs. + +The generated part creates: + +- `dynamic_parameters`: a model version's model assumptions, every parameter a + dynamic may set (`policyengine_api/dynamic_parameters.py`: `gov.simulation.`, + US `simulation.` and UK `gov.dynamic.`), with `parameters`' columns, its + catalog IDs (`catalog_identifier("parameter", version, name)`) and its + unique name per version (`uq_dynamic_parameters_model_version_name`), + deleted with the version (`CASCADE`); +- `dynamic_parameter_values`: their current-law values (no `dynamic_id`) and + every dynamic's values, with no `policy_id`: `dynamic_parameter_id` + (`CASCADE`), `value_json`, `start_date`, `end_date` and a nullable + `dynamic_id` (`CASCADE`). Like `parameter_values`, it checks that a value + doesn't end before it starts, keeps one current-law value per parameter and + start date and one value per dynamic, parameter and start date (two partial + unique indexes, also declared for SQLite), and has the period index. + +`parameter_nodes` stays shared: `gov` is above both kinds of parameter. + +**The data step** runs after the generated tables are created, in the one +transaction `migrations/v2/env.py` runs every pending revision and the head +schema check in, so a failure anywhere changes nothing: + +1. It locks every stored parameter it moves (`SELECT … FOR UPDATE`), so a + value written meanwhile that names one waits for the migration and then + fails on the deleted parameter, and refuses, raising, while any + `parameter_values` row with a `policy_id` names one: deleting the + parameter would delete that value and silently change its policy, whose + stored hash would stay the same. Operator step C1 · 49 splits such + policies into a policy and a dynamic first (C1 · 48's command, which + C1 · 50 removed afterwards), and the seed workflow's read-only step + "Qualify the pending dynamic parameter move" + (`scripts/qualify_v2_dynamic_parameter_move.py`) counts the same values + while the revision is pending, so a deploy stops before Alembic starts. +2. It copies every stored version's dynamic parameters into + `dynamic_parameters`, and their current-law values and every dynamic's + values into `dynamic_parameter_values`, with their IDs and `created_at`. + Stored dynamics' content hashes (`canonical_policy_document`) cover + parameter IDs, so they stay valid. +3. It lowers the `child_count` of each kept `parameter_tree_children` row + above a dynamic folder (`gov`), and its `reform_child_count` for a folder + with a `reform_position`, then deletes the tree rows of the dynamic folders + (`gov.simulation`, US `simulation`, UK `gov.dynamic`) and everything below + them, so the policy tree shows no empty folder. The kept rows' positions + keep their gaps, which the tree routes' paging (by position, with an + offset) doesn't notice. +4. It deletes the moved values and parameters, and raises unless it deleted + exactly the rows it copied. + +A parameter is a model assumption by its country's prefixes, its country +being that of its version's model `policyengine-`, the name +`select_catalog` reads; a tree row's path is a dynamic folder or below one when +the path followed by `.` starts with a prefix. The revision keeps its own +frozen copy of the prefixes (`DYNAMIC_PARAMETER_PREFIXES` in the revision), +which `test_dynamic_parameter_tables_revision_keeps_its_own_copy_of_the_prefixes` +keeps equal to the package's, and catalog publication compares the installed +version's rows with the package's own classification right after the +upgrade. Publication then writes, compares, restores and prunes both tables +(`policyengine_api/data/v2/catalog/dynamic_parameter_records.py`), builds the +policy tree without dynamic parameters and their folders, and writes the +search file in format 2, which lists none of them; versions stored before keep +their format 1 files, which the previous release serves, and answer 503 from +`/v2/parameters/search-file` until a publication writes their format 2 file. + +**The downgrade** copies both tables back into `parameters` and +`parameter_values` (with a null `policy_id`), with their IDs, versions +published after the upgrade included, then drops them. It leaves the policy +trees as they are, without the dynamic folders (C1 · 50's decision 1, the +user, 2026-11-25): the parent revision's `/v2/policies` refuses those +parameters anyway, and publication never compares a stored tree, so a version +gets its full tree back only once it is pruned and published again. At the +parent revision, search (the format 1 files) still lists the `gov.simulation` +and UK `gov.dynamic` parameters that the tree no longer shows. The downgrade +fails, changing nothing, if a policy parameter of a version has the same name +as one of its dynamic parameters. + +**What must be in production first,** in each environment: + +- C1 · 49 has run there, so no policy value names a dynamic parameter; + otherwise the seed job stops at the check step. +- The simulation service's C1 · 47 (PolicyEngine/policyengine-sim-api#1122): + its current release reads a dynamic's values from `parameter_values`, so + after the move it would read none and run the dynamic as current law, + storing that result. C1 · 47 makes it refuse a dynamic without values + (400 `dynamic_without_values`, which API v1 answers as 503) until C1 · 52 + reads the new tables. + +A merge to `master` releases and runs the revision in staging and production, +so the pull request merges only once both hold in both environments. + +**The deploy window, the second accepted exception** to "the serving +revision must work with the database changed on its own" (the user's +decision 2 for C1 · 50, 2026-11-25; the maintainers' approval is this pull +request's review). From the seed job's upgrade until the new release is +promoted in that environment, or until a later release succeeds if promotion +fails, the previous API v1 release serves on the moved tables: + +- `GET /v2/dynamics/{id}` answers 200 with no values, `POST /v2/dynamics` + answers the generic 422 for every dynamic, and `POST /v2/policies` answers + a dynamic parameter with the generic 422 instead of the named + `dynamic_parameters` one; +- the dual-write v1-to-v2 policy copy fails, with the logged reason + `missing_parameters` and the v1 response unchanged, for each v1 policy that + sets a model assumption, which gets no v2 copy until something writes it + again; +- the metadata routes no longer list dynamic parameters, and search serves + the stored format 1 files. + +Nothing in production calls these v2 routes yet: v3 runs on the v1 routes, +and its `allowList.ts` forwards neither `/v2/dynamics` nor +`/v2/user-dynamics`. + +The runtime role reads both tables and inserts dynamics' values; the catalog +writer inserts both, updates `dynamic_parameters`, deletes only current-law +values (pruning) and analyzes both (`MAINTAIN`); the simulation service and +its Modal workers read both, which C1 · 52 needs; comparison runs have no +access. `parameter_values.dynamic_id`, its single-owner check and its partial +unique index stay until C1 · 53, because older simulation service releases +map the column. `tests/integration/test_alembic_v2_dynamic_parameter_tables.py` +checks that nothing else changes, the move with both kinds of row, the +refusal, the read-only step, the downgrade and the re-upgrade, and +`tests/integration/test_v2_catalog_publication_dynamic_parameters.py` +publication, pruning, restoring and a downgrade round trip as the catalog +writer. diff --git a/docs/migration/stage-10-v2-policies.md b/docs/migration/stage-10-v2-policies.md index a2731566a..505c6cafd 100644 --- a/docs/migration/stage-10-v2-policies.md +++ b/docs/migration/stage-10-v2-policies.md @@ -149,13 +149,23 @@ 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, 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 +assumptions stayed policy values and its mapping names no dynamic, and a UK +copy made before `gov.dynamic.` joined kept those values in its policy too, +until the split command split it (see "Splitting stored policies that held model assumptions" below). Native `POST /v2/policies` refuses such values with 422 instead (code `dynamic_parameters`), and they are created through `POST /v2/dynamics`. +Since revision `7f7335f0eb31` (C1 · 50), model assumptions are +`dynamic_parameters` rows and a dynamic's values `dynamic_parameter_values` +rows, apart from the policy parameters and policies' values. The copy looks +the policy's names up among policy parameters and the assumptions' among +dynamic parameters. `POST /v2/policies` binds its IDs to `parameters` and +names, in its 422 `dynamic_parameters`, those it finds in `dynamic_parameters` +instead; `POST /v2/dynamics` binds its IDs to `dynamic_parameters` and names, +in its 422 `policy_parameters`, those it finds in `parameters`. An ID in +neither answers the generic catalog 422, as before. + A saved-policy mutation commits its source row, incremented revision, and complete event in one Cloud SQL transaction. The same request then processes that source's pending events in diff --git a/docs/migration/stage-9-v2-metadata.md b/docs/migration/stage-9-v2-metadata.md index 7b35069ec..f0087cbb5 100644 --- a/docs/migration/stage-9-v2-metadata.md +++ b/docs/migration/stage-9-v2-metadata.md @@ -192,7 +192,7 @@ Use three separately managed database credentials: | Operation | Configuration | Required database access | | --- | --- | --- | | Alembic schema upgrade | `V2_MIGRATION_DATABASE_URL` | Reviewed v2 schema changes; no application-runtime use | -| Catalog publication | `V2_DATA_WRITE_DATABASE_URL` | Row insertion, update, selection, deletion from `parameter_values`, `parameter_tree_children` and `parameter_search_files` (catalog pruning), `ANALYZE` of the catalog tables (`MAINTAIN`, which also allows `VACUUM`, `CLUSTER`, `REINDEX` and `LOCK TABLE` on them), temporary tables, and transaction-scoped advisory locks; no persistent schema changes | +| Catalog publication | `V2_DATA_WRITE_DATABASE_URL` | Row insertion, update, selection, deletion from `parameter_values`, `dynamic_parameter_values`, `parameter_tree_children` and `parameter_search_files` (catalog pruning), `ANALYZE` of the catalog tables (`MAINTAIN`, which also allows `VACUUM`, `CLUSTER`, `REINDEX` and `LOCK TABLE` on them), temporary tables, and transaction-scoped advisory locks; no persistent schema changes | | Preview GET requests | `V2_RUNTIME_DATABASE_URL` or `V2_RUNTIME_DATABASE_URL_SECRET_RESOURCE` | Catalog selection only during Stage 9; no migration access | Do not place more than one database URL in the environment of either the @@ -403,10 +403,29 @@ the previous release keep the years they already read until they stop, and an HTTP cache can keep a response with the previous years until it expires (five minutes, or a day for a request naming `policyengine_version`). +### Dynamic parameters + +Since revision `7f7335f0eb31` (C1 · 50), publication stores a version's model +assumptions, the parameters a dynamic may set +(`policyengine_api/dynamic_parameters.py`: `gov.simulation.`, US `simulation.` +and UK `gov.dynamic.`), in `dynamic_parameters`, and their current-law values +in `dynamic_parameter_values`, with the same catalog IDs as before. Every other +parameter stays in `parameters`, so the policy routes (`/v2/parameters`, +`/v2/parameter-values`, `/v2/model-catalog/parameters`), the parameter tree +and the search file no longer list them. Publication compares, restores and +prunes both tables as it does `parameters` and `parameter_values`, and the +evidence counts them apart (`entity_counts`' `dynamic_parameters` and +`dynamic_parameter_values`). The revision moved every stored version's rows; +`docs/engineering/skills/alembic-migrations.md` ("API v2 dynamic parameters in +their own tables") describes it and its deploy order. C1 · 51 adds the routes +that serve them. + ### Parameter tree Publication also writes parameter trees into `parameter_tree_children`, which -`/v2/parameters/children` reads one level at a time. A tree is built from a +`/v2/parameters/children` reads one level at a time. A tree holds policy +parameters only: model assumptions, and the folders that hold only them +(`gov.simulation`, US `simulation`, UK `gov.dynamic`), are not rows of it. A tree is built from a catalog version's parameter and node records: every node and parameter is one row under its parent's path, a `[` starts a child as a `.` does (so a bracket schedule is one node whose children are its brackets, labelled "Bracket 1", "Bracket 2" and so on), @@ -465,8 +484,12 @@ version. Publication also writes the parameter search file of each catalog version it publishes into `parameter_search_files`: one gzip-compressed JSON file per -version and file format, with the SHA-256 of the uncompressed JSON. The file -holds what the app's newer interface's parameter search reads: +version and file format, with the SHA-256 of the uncompressed JSON. The current +format is 2 (C1 · 50), which leaves model assumptions and their folders out of +every list, as the tree does; format 1 listed them. Versions stored before +keep their format 1 files, which the previous release serves, and have no +format 2 file until a publication of the version writes one. The file holds +what the app's newer interface's parameter search reads: - every parameter a reform can change (the parameter tree's rule) with its path, stored label, unit, description, and whether a draft can edit its @@ -546,12 +569,14 @@ of a new version took 17 to 20 minutes in production, inside the job's Pruning a version runs one transaction that deletes its current-law `parameter_values` (rows of its parameters with neither a `policy_id` nor a -`dynamic_id`), its `parameter_tree_children` rows and its -`parameter_search_files` rows, and sets its `catalog_values_pruned_at`. It -never deletes `parameters` rows, whose deletion would cascade to saved -reforms' values, and keeps the version's model version row, parameter nodes, +`dynamic_id`), its current-law `dynamic_parameter_values` (rows of its +dynamic parameters with no `dynamic_id`), its `parameter_tree_children` rows +and its `parameter_search_files` rows, and sets its +`catalog_values_pruned_at`. It never deletes `parameters` or +`dynamic_parameters` rows, whose deletion would cascade to saved reforms' and +dynamics' values, and keeps the version's model version row, parameter nodes, variables, regions and datasets, and every policy, dynamic and value a -policy or dynamic owns. This is the one exception to the Alembic skill's rule +policy or dynamic owns. The evidence's `deleted_rows` counts each table. This is the one exception to the Alembic skill's rule that the catalog seeder deletes no retained domain data; its scope is in `docs/engineering/skills/alembic-migrations.md` ("Catalog pruning"). @@ -640,8 +665,9 @@ parameters` it walks `uq_parameters_model_version_name` and takes 4.1 ms (UK: 4.9 ms). Every publication therefore runs one `ANALYZE` over `datasets`, -`parameter_nodes`, `parameter_tree_children`, `parameter_values`, -`parameters`, `regions` and `variables` once it has committed and pruned, and +`dynamic_parameter_values`, `dynamic_parameters`, `parameter_nodes`, +`parameter_tree_children`, `parameter_values`, `parameters`, `regions` and +`variables` once it has committed and pruned, and lists them in the evidence's `catalog_tables_analyzed`. It takes a few seconds and blocks no reads. A failed `ANALYZE` doesn't undo the publication: the evidence lists no tables and names the failure in `catalog_statistics_failure` @@ -652,7 +678,7 @@ analyzes again. `ANALYZE` needs the table's owner or the `MAINTAIN` privilege (PostgreSQL 17), and PostgreSQL skips any other table with only a warning. The migration role owns the tables, so the manifest grants the catalog writer `MAINTAIN` on these -seven, the deploy's `apply` step grants it before publication runs, and +nine, the deploy's `apply` step grants it before publication runs, and publication fails before writing anything if its role lacks it. PostgreSQL 17 has no narrower privilege: `MAINTAIN` also allows `VACUUM` (`FULL` included), `CLUSTER`, `REINDEX`, `REFRESH MATERIALIZED VIEW` and `LOCK TABLE` on those diff --git a/migrations/v2/versions/7f7335f0eb31_move_dynamic_parameters_into_their_own_.py b/migrations/v2/versions/7f7335f0eb31_move_dynamic_parameters_into_their_own_.py new file mode 100644 index 000000000..33e1ebc48 --- /dev/null +++ b/migrations/v2/versions/7f7335f0eb31_move_dynamic_parameters_into_their_own_.py @@ -0,0 +1,474 @@ +"""move dynamic parameters into their own tables + +Revision ID: 7f7335f0eb31 +Revises: d417fe8b1b17 +Create Date: 2026-11-26 00:24:27.129305 +Generation: uv run alembic -c alembic-v2.ini revision --autogenerate + +Creates dynamic_parameters, with parameters' columns and unique name per +catalog version, and dynamic_parameter_values: a dynamic parameter's +current-law values (no dynamic) and every dynamic's values, with a unique +current-law value per parameter and start date, a unique value per dynamic, +parameter and start date, and the period index. Both are generated. + +The data step that follows is hand-written: the user's explicit migration +decision for C1 · 50 (C1 · 46, Q2, 2026-11-25), which the generated-only rule +for revisions requires. Catalog publication can't move rows it already +stored, and dynamics' values aren't catalog data, so the revision moves every +stored version's rows itself, in the one transaction that migrations/v2/env.py +runs every pending revision in: + +1. It locks the parameters it moves, so no value can start naming one, and + refuses, changing nothing, while a policy value names one: deleting the + parameter would delete that value with it and silently change the policy. + Operator step C1 · 49 splits such policies first. +2. It copies every version's dynamic parameters, their current-law values and + every dynamic's values into the new tables, with their IDs and creation + times, so stored dynamics' content hashes, which cover parameter IDs, stay + valid. +3. It lowers the child counts of the policy tree rows above the dynamic + folders and deletes the tree rows of the folders and everything below + them, so the policy tree shows no empty folder. +4. It deletes the moved values and parameters, and checks that it deleted + exactly what it copied. + +A model's parameters are dynamic by the prefixes of its country, the model +being policyengine-: a frozen copy of the package's +dynamic_parameters.DYNAMIC_PARAMETER_PREFIXES, which a unit test keeps equal +to it; catalog publication compares the installed version's rows with the +package's own classification right after the upgrade. + +The downgrade copies both tables back into parameters and parameter_values, +with their IDs, versions published after the upgrade included, then drops +them. It leaves the policy trees as they are, without the dynamic folders +(C1 · 50, decision 1): the parent revision's /v2/policies refuses those +parameters anyway, and publication never compares a stored tree. +""" + +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +import sqlmodel +from sqlalchemy.dialects import postgresql + +revision: str = "7f7335f0eb31" +down_revision: Union[str, None] = "d417fe8b1b17" +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +# The model assumptions' prefixes by country when this revision was written: +# a frozen copy of dynamic_parameters.DYNAMIC_PARAMETER_PREFIXES. +DYNAMIC_PARAMETER_PREFIXES: dict[str, tuple[str, ...]] = { + "uk": ("gov.simulation.", "gov.dynamic."), + "us": ("gov.simulation.", "simulation."), +} + +# The columns the data step reads and writes, as lightweight table constructs. +PARAMETER_COLUMNS = ( + "id", + "created_at", + "name", + "label", + "description", + "data_type", + "unit", + "economy", + "household", + "tax_benefit_model_version_id", +) +_models = sa.table("tax_benefit_models", sa.column("id"), sa.column("name")) +_versions = sa.table( + "tax_benefit_model_versions", sa.column("id"), sa.column("model_id") +) +_parameters = sa.table("parameters", *(sa.column(name) for name in PARAMETER_COLUMNS)) +_dynamic_parameters = sa.table( + "dynamic_parameters", *(sa.column(name) for name in PARAMETER_COLUMNS) +) +_parameter_values = sa.table( + "parameter_values", + sa.column("id"), + sa.column("created_at"), + sa.column("parameter_id"), + sa.column("value_json"), + sa.column("start_date"), + sa.column("end_date"), + sa.column("policy_id"), + sa.column("dynamic_id"), +) +_dynamic_parameter_values = sa.table( + "dynamic_parameter_values", + sa.column("id"), + sa.column("created_at"), + sa.column("dynamic_parameter_id"), + sa.column("value_json"), + sa.column("start_date"), + sa.column("end_date"), + sa.column("dynamic_id"), +) +_tree = sa.table( + "parameter_tree_children", + sa.column("id"), + sa.column("tax_benefit_model_version_id"), + sa.column("parent_path"), + sa.column("path"), + sa.column("child_count"), + sa.column("reform_position"), + sa.column("reform_child_count"), +) + + +def _under_dynamic_prefix( + text: sa.ColumnElement, model_name: sa.ColumnElement +) -> sa.ColumnElement[bool]: + """Whether ``text`` starts with a prefix of the country of ``model_name``.""" + return sa.or_( + *( + sa.and_( + model_name == f"policyengine-{country_id}", + sa.or_(*(sa.func.starts_with(text, prefix) for prefix in prefixes)), + ) + for country_id, prefixes in DYNAMIC_PARAMETER_PREFIXES.items() + ) + ) + + +def _is_dynamic_path( + path: sa.ColumnElement, model_name: sa.ColumnElement +) -> sa.ColumnElement[bool]: + """Whether a tree path is a dynamic folder or below one: path + "." matches.""" + return _under_dynamic_prefix(sa.func.concat(path, "."), model_name) + + +def _moved_parameter_ids() -> sa.Select: + """Select the stored parameters that are model assumptions of their country.""" + return ( + sa.select(_parameters.c.id) + .select_from( + _parameters.join( + _versions, _versions.c.id == _parameters.c.tax_benefit_model_version_id + ).join(_models, _models.c.id == _versions.c.model_id) + ) + .where(_under_dynamic_prefix(_parameters.c.name, _models.c.name)) + ) + + +def _dynamic_tree_rows() -> sa.Select: + """Select the tree rows of dynamic folders and everything below them.""" + return ( + sa.select(_tree.c.id) + .select_from( + _tree.join( + _versions, _versions.c.id == _tree.c.tax_benefit_model_version_id + ).join(_models, _models.c.id == _versions.c.model_id) + ) + .where(_is_dynamic_path(_tree.c.path, _models.c.name)) + ) + + +def _lower_kept_parents_child_counts(bind: sa.Connection) -> None: + """Lower each kept tree row's counts by its dynamic children. + + Those are the dynamic folders right below a row that holds policy + parameters too (``gov``); a top-level folder has no parent row. A child + with a ``reform_position`` was counted in ``reform_child_count`` too. + """ + child = _tree.alias("child") + removed = ( + sa.select( + child.c.tax_benefit_model_version_id, + child.c.parent_path, + sa.func.count().label("children"), + sa.func.count(child.c.reform_position).label("reform_children"), + ) + .select_from( + child.join( + _versions, _versions.c.id == child.c.tax_benefit_model_version_id + ).join(_models, _models.c.id == _versions.c.model_id) + ) + .where( + _is_dynamic_path(child.c.path, _models.c.name), + sa.not_(_is_dynamic_path(child.c.parent_path, _models.c.name)), + ) + .group_by(child.c.tax_benefit_model_version_id, child.c.parent_path) + .subquery("removed") + ) + bind.execute( + sa.update(_tree) + .where( + _tree.c.tax_benefit_model_version_id + == removed.c.tax_benefit_model_version_id, + _tree.c.path == removed.c.parent_path, + ) + .values( + child_count=_tree.c.child_count - removed.c.children, + reform_child_count=_tree.c.reform_child_count - removed.c.reform_children, + ) + ) + + +def _move_dynamic_parameters_into_their_tables() -> None: + """Move every stored dynamic parameter and value, keeping its ID (Q2).""" + bind = op.get_bind() + moved_ids = _moved_parameter_ids() + # Lock the parameters first: inserting a value that names one waits for + # this transaction, then fails on the deleted parameter, rather than + # being deleted with it after the count below. + bind.execute( + sa.select(_parameters.c.id) + .where(_parameters.c.id.in_(moved_ids)) + .with_for_update() + ).all() + policy_values = bind.execute( + sa.select(sa.func.count()) + .select_from(_parameter_values) + .where( + _parameter_values.c.policy_id.is_not(None), + _parameter_values.c.parameter_id.in_(moved_ids), + ) + ).scalar_one() + if policy_values: + msg = ( + "the upgrade to 7f7335f0eb31 stopped, changing nothing: policy values " + f"name dynamic parameters ({policy_values} found), and moving those " + "parameters out of parameters would delete the values and change the " + "policies; split those policies into a policy and a dynamic first " + "(operator step C1 · 49), then upgrade again" + ) + raise RuntimeError(msg) + + # SQLAlchemy keeps an INSERT's row count only when asked to. + copied_parameters = bind.execute( + sa.insert(_dynamic_parameters) + .execution_options(preserve_rowcount=True) + .from_select( + PARAMETER_COLUMNS, + sa.select(*(_parameters.c[name] for name in PARAMETER_COLUMNS)).where( + _parameters.c.id.in_(moved_ids) + ), + ) + ).rowcount + copied_values = bind.execute( + sa.insert(_dynamic_parameter_values) + .execution_options(preserve_rowcount=True) + .from_select( + [ + "id", + "created_at", + "dynamic_parameter_id", + "value_json", + "start_date", + "end_date", + "dynamic_id", + ], + sa.select( + _parameter_values.c.id, + _parameter_values.c.created_at, + _parameter_values.c.parameter_id, + _parameter_values.c.value_json, + _parameter_values.c.start_date, + _parameter_values.c.end_date, + _parameter_values.c.dynamic_id, + ).where(_parameter_values.c.parameter_id.in_(moved_ids)), + ) + ).rowcount + + _lower_kept_parents_child_counts(bind) + bind.execute(sa.delete(_tree).where(_tree.c.id.in_(_dynamic_tree_rows()))) + + deleted_values = bind.execute( + sa.delete(_parameter_values).where( + _parameter_values.c.parameter_id.in_(moved_ids) + ) + ).rowcount + deleted_parameters = bind.execute( + sa.delete(_parameters).where( + _parameters.c.id.in_(sa.select(_dynamic_parameters.c.id)) + ) + ).rowcount + if (deleted_parameters, deleted_values) != (copied_parameters, copied_values): + msg = ( + "the upgrade to 7f7335f0eb31 stopped, changing nothing: it copied " + f"{copied_parameters} dynamic parameters and {copied_values} values " + f"but would delete {deleted_parameters} and {deleted_values}" + ) + raise RuntimeError(msg) + + +def _move_dynamic_parameters_back() -> None: + """Copy both tables back into parameters and parameter_values, with their IDs. + + The tree rows the upgrade deleted stay deleted (C1 · 50, decision 1). + """ + bind = op.get_bind() + bind.execute( + sa.insert(_parameters).from_select( + PARAMETER_COLUMNS, + sa.select(*(_dynamic_parameters.c[name] for name in PARAMETER_COLUMNS)), + ) + ) + bind.execute( + sa.insert(_parameter_values).from_select( + [ + "id", + "created_at", + "parameter_id", + "value_json", + "start_date", + "end_date", + "policy_id", + "dynamic_id", + ], + sa.select( + _dynamic_parameter_values.c.id, + _dynamic_parameter_values.c.created_at, + _dynamic_parameter_values.c.dynamic_parameter_id, + _dynamic_parameter_values.c.value_json, + _dynamic_parameter_values.c.start_date, + _dynamic_parameter_values.c.end_date, + sa.null(), + _dynamic_parameter_values.c.dynamic_id, + ), + ) + ) + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.create_table( + "dynamic_parameters", + sa.Column("id", sa.Uuid(), nullable=False), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column("name", sqlmodel.sql.sqltypes.AutoString(length=512), nullable=False), + sa.Column("label", sqlmodel.sql.sqltypes.AutoString(length=512), nullable=True), + sa.Column("description", sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column( + "data_type", sqlmodel.sql.sqltypes.AutoString(length=128), nullable=True + ), + sa.Column("unit", sqlmodel.sql.sqltypes.AutoString(length=128), nullable=True), + sa.Column("economy", sa.Boolean(), nullable=True), + sa.Column("household", sa.Boolean(), nullable=True), + sa.Column("tax_benefit_model_version_id", sa.Uuid(), nullable=False), + sa.ForeignKeyConstraint( + ["tax_benefit_model_version_id"], + ["tax_benefit_model_versions.id"], + name=op.f( + "fk_dynamic_parameters_tax_benefit_model_version_id_tax_benefit_model_versions" + ), + ondelete="CASCADE", + ), + sa.PrimaryKeyConstraint("id", name=op.f("pk_dynamic_parameters")), + sa.UniqueConstraint( + "tax_benefit_model_version_id", + "name", + name="uq_dynamic_parameters_model_version_name", + ), + ) + op.create_index( + op.f("ix_dynamic_parameters_tax_benefit_model_version_id"), + "dynamic_parameters", + ["tax_benefit_model_version_id"], + unique=False, + ) + op.create_table( + "dynamic_parameter_values", + sa.Column("id", sa.Uuid(), nullable=False), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column("dynamic_parameter_id", sa.Uuid(), nullable=False), + sa.Column( + "value_json", + sa.JSON().with_variant( + postgresql.JSONB(astext_type=sa.Text()), "postgresql" + ), + nullable=False, + ), + sa.Column("start_date", sa.DateTime(timezone=True), nullable=False), + sa.Column("end_date", sa.DateTime(timezone=True), nullable=True), + sa.Column("dynamic_id", sa.Uuid(), nullable=True), + sa.CheckConstraint( + "end_date IS NULL OR end_date >= start_date", + name=op.f("ck_dynamic_parameter_values_effective_period"), + ), + sa.ForeignKeyConstraint( + ["dynamic_id"], + ["dynamics.id"], + name=op.f("fk_dynamic_parameter_values_dynamic_id_dynamics"), + ondelete="CASCADE", + ), + sa.ForeignKeyConstraint( + ["dynamic_parameter_id"], + ["dynamic_parameters.id"], + name=op.f( + "fk_dynamic_parameter_values_dynamic_parameter_id_dynamic_parameters" + ), + ondelete="CASCADE", + ), + sa.PrimaryKeyConstraint("id", name=op.f("pk_dynamic_parameter_values")), + ) + op.create_index( + "ix_dynamic_parameter_values_parameter_period", + "dynamic_parameter_values", + ["dynamic_parameter_id", "start_date", "end_date"], + unique=False, + ) + op.create_index( + "uq_dynamic_parameter_values_current_law_parameter_start_date", + "dynamic_parameter_values", + ["dynamic_parameter_id", "start_date"], + unique=True, + postgresql_where=sa.text("dynamic_id IS NULL"), + sqlite_where=sa.text("dynamic_id IS NULL"), + ) + op.create_index( + "uq_dynamic_parameter_values_dynamic_parameter_start_date", + "dynamic_parameter_values", + ["dynamic_id", "dynamic_parameter_id", "start_date"], + unique=True, + postgresql_where=sa.text("dynamic_id IS NOT NULL"), + sqlite_where=sa.text("dynamic_id IS NOT NULL"), + ) + # ### end Alembic commands ### + # Approved hand-written data step (the user's migration decision, C1 · 46, + # Q2): move every stored dynamic parameter and value into the new tables. + _move_dynamic_parameters_into_their_tables() + + +def downgrade() -> None: + # Approved hand-written data step (the user's migration decision, C1 · 46, + # Q2): move the rows back before the generated drops delete them. + _move_dynamic_parameters_back() + # ### commands auto generated by Alembic - please adjust! ### + op.drop_index( + "uq_dynamic_parameter_values_dynamic_parameter_start_date", + table_name="dynamic_parameter_values", + postgresql_where=sa.text("dynamic_id IS NOT NULL"), + sqlite_where=sa.text("dynamic_id IS NOT NULL"), + ) + op.drop_index( + "uq_dynamic_parameter_values_current_law_parameter_start_date", + table_name="dynamic_parameter_values", + postgresql_where=sa.text("dynamic_id IS NULL"), + sqlite_where=sa.text("dynamic_id IS NULL"), + ) + op.drop_index( + "ix_dynamic_parameter_values_parameter_period", + table_name="dynamic_parameter_values", + ) + op.drop_table("dynamic_parameter_values") + op.drop_index( + op.f("ix_dynamic_parameters_tax_benefit_model_version_id"), + table_name="dynamic_parameters", + ) + op.drop_table("dynamic_parameters") + # ### end Alembic commands ### diff --git a/policyengine_api/data/v2/catalog/dynamic_parameter_records.py b/policyengine_api/data/v2/catalog/dynamic_parameter_records.py new file mode 100644 index 000000000..d1e47a36e --- /dev/null +++ b/policyengine_api/data/v2/catalog/dynamic_parameter_records.py @@ -0,0 +1,70 @@ +"""Which records of a country's catalog are model assumptions (C1 · 50). + +Catalog publication stores a version's model assumptions +(``policyengine_api.dynamic_parameters``) in ``dynamic_parameters`` and their +current-law values in ``dynamic_parameter_values``, and every other parameter +in ``parameters``. The policy tree and the search file hold only the other +parameters and the nodes outside the folders that hold only assumptions. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from policyengine_api.data.v2.catalog.publication_types import ( + CatalogPublicationError, +) +from policyengine_api.dynamic_parameters import ( + is_dynamic_parameter, + is_dynamic_parameter_path, +) +from policyengine_api.supported_countries import SUPPORTED_COUNTRY_IDS + +if TYPE_CHECKING: + from policyengine_api.data.v2.catalog.records import ( + CountryCatalog, + ParameterNodeRecord, + ParameterRecord, + ) + from policyengine_api.supported_countries import SupportedCountryId + + +def supported_country_id(country_id: str) -> SupportedCountryId: + """Return a catalog's country as a supported one, or raise. + + Raise CatalogPublicationError for a country with no model assumption + prefixes, which publication cannot classify. + """ + for supported in SUPPORTED_COUNTRY_IDS: + if supported == country_id: + return supported + msg = f"the catalog country {country_id!r} is not a supported country" + raise CatalogPublicationError(msg) + + +def is_dynamic_record(country_id: str, parameter_name: str) -> bool: + """Return whether the country's parameter is a model assumption.""" + return is_dynamic_parameter(supported_country_id(country_id), parameter_name) + + +def is_dynamic_path(country_id: str, path: str) -> bool: + """Return whether a node or parameter path holds only model assumptions.""" + return is_dynamic_parameter_path(supported_country_id(country_id), path) + + +def policy_parameter_records(country: CountryCatalog) -> tuple[ParameterRecord, ...]: + """Return the country's parameters that are not model assumptions.""" + return tuple( + parameter + for parameter in country.parameters + if not is_dynamic_record(country.country_id, parameter.name) + ) + + +def policy_node_records(country: CountryCatalog) -> tuple[ParameterNodeRecord, ...]: + """Return the country's nodes outside the folders of model assumptions.""" + return tuple( + node + for node in country.parameter_nodes + if not is_dynamic_path(country.country_id, node.name) + ) diff --git a/policyengine_api/data/v2/catalog/parameter_search_file.py b/policyengine_api/data/v2/catalog/parameter_search_file.py index b2bce9ddf..3b2e9f94d 100644 --- a/policyengine_api/data/v2/catalog/parameter_search_file.py +++ b/policyengine_api/data/v2/catalog/parameter_search_file.py @@ -21,6 +21,13 @@ Catalog publication builds the file from the installed packages' catalog (``country_search_file``) for the version it publishes. + +From format 2 (C1 · 50), the file lists only policy parameters: model +assumptions (``policyengine_api.dynamic_parameters``) and the folders that +hold only them are left out of every list, as they are of the policy tree. +A stored file of the current format can't change, so the format changed with +them; versions stored before have format 1 files, which the previous release +serves. """ from __future__ import annotations @@ -32,6 +39,9 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, TypedDict +from policyengine_api.data.v2.catalog.dynamic_parameter_records import ( + is_dynamic_path, +) from policyengine_api.data.v2.catalog.parameter_tree import ( REFORM_TREE_PREFIX, TreeNodeSource, @@ -47,7 +57,7 @@ ParameterRecord, ) -PARAMETER_SEARCH_FILE_FORMAT = 1 +PARAMETER_SEARCH_FILE_FORMAT = 2 # Repeated builds of the same rows must give the same bytes, so the gzip header # carries no timestamp. @@ -194,13 +204,16 @@ def build_parameter_search_file( fields and editability; ``other_parameters`` lists the other parameters under ``gov`` with their labels; ``nodes`` lists ``gov`` and every node under it that has a stored label. A parameter without current-law values cannot be - edited. + edited. The country's model assumptions, and the folders that hold only + them, are in none of the lists. """ editability_by_name = _editability(editability) changeable: list[SearchFileParameterEntry] = [] others: list[SearchFileLabelEntry] = [] for parameter in sorted(parameters, key=lambda parameter: parameter.name): - if not parameter.name.startswith(REFORM_TREE_PREFIX): + if not parameter.name.startswith(REFORM_TREE_PREFIX) or is_dynamic_path( + country_id, parameter.name + ): continue label = _stored_label(parameter.label) if not is_reform_changeable( @@ -222,7 +235,10 @@ def build_parameter_search_file( labelled_nodes: list[SearchFileNodeEntry] = [ {"path": node.name, "label": node.label} for node in sorted(nodes, key=lambda node: node.name) - if _is_gov_node(node.name) and node.label is not None and node.label.strip() + if _is_gov_node(node.name) + and not is_dynamic_path(country_id, node.name) + and node.label is not None + and node.label.strip() ] return { "format": PARAMETER_SEARCH_FILE_FORMAT, diff --git a/policyengine_api/data/v2/catalog/publication.py b/policyengine_api/data/v2/catalog/publication.py index 318ab7980..de96628d7 100644 --- a/policyengine_api/data/v2/catalog/publication.py +++ b/policyengine_api/data/v2/catalog/publication.py @@ -15,6 +15,9 @@ ALEMBIC_REVISION_TABLE, AlembicRevision, ) +from policyengine_api.data.v2.catalog.dynamic_parameter_records import ( + is_dynamic_record, +) from policyengine_api.data.v2.catalog.publication_inserts import publish_new_country from policyengine_api.data.v2.catalog.publication_parameter_search_file import ( assert_parameter_search_files_written, @@ -304,6 +307,7 @@ def _prune_older_versions( country_id=country_id, policyengine_version=stored.version, parameter_values=deleted.parameter_values, + dynamic_parameter_values=deleted.dynamic_parameter_values, parameter_tree_children=deleted.parameter_tree_children, parameter_search_files=deleted.parameter_search_files, ) @@ -461,7 +465,7 @@ def _evidence( """ kept_region_summaries = stored_versions.kept_region_summaries kept_countries = {country_id for country_id, *_counts in kept_region_summaries} - entity_counts = catalog.entity_counts() + entity_counts = _stored_entity_counts(catalog) entity_counts["regions"] += sum( stored - staged for _country, _version, stored, staged in kept_region_summaries ) @@ -491,6 +495,28 @@ def _evidence( ) +def _stored_entity_counts(catalog: NormalizedCatalog) -> dict[str, int]: + """Return the catalog's counts, with model assumptions counted apart. + + ``parameters`` and ``parameter_values`` count the rows stored in those + tables, and ``dynamic_parameters`` and ``dynamic_parameter_values`` the + model assumptions and their current-law values. + """ + counts = catalog.entity_counts() + dynamic_parameters = [ + parameter + for country in catalog.countries + for parameter in country.parameters + if is_dynamic_record(country.country_id, parameter.name) + ] + dynamic_values = sum(len(parameter.values) for parameter in dynamic_parameters) + counts["parameters"] -= len(dynamic_parameters) + counts["parameter_values"] -= dynamic_values + counts["dynamic_parameters"] = len(dynamic_parameters) + counts["dynamic_parameter_values"] = dynamic_values + return counts + + def _kept_region_summary( session: Session, country: CountryCatalog, diff --git a/policyengine_api/data/v2/catalog/publication_inserts.py b/policyengine_api/data/v2/catalog/publication_inserts.py index 984f7a1fd..3935174a0 100644 --- a/policyengine_api/data/v2/catalog/publication_inserts.py +++ b/policyengine_api/data/v2/catalog/publication_inserts.py @@ -19,6 +19,8 @@ ) from policyengine_api.data.v2.models import ( Dataset, + DynamicParameter, + DynamicParameterValue, Parameter, ParameterNode, ParameterValue, @@ -257,36 +259,94 @@ def column_type(model: type[SQLModel], column_name: str) -> TypeEngine[Any]: .where(col(StagedParameterNode.country_id) == COUNTRY_ID), ) -INSERT_PARAMETERS = sa.insert(Parameter).from_select( + +def _parameters_insert( + model: type[Parameter | DynamicParameter], *, dynamic: bool +) -> sa.Insert: + """Insert the staged parameters of one kind into ``model``'s table. + + Model assumptions (``StagedParameter.is_dynamic``) go to + ``dynamic_parameters``, the others to ``parameters``, with the same columns. + """ + return sa.insert(model).from_select( + [ + "id", + "created_at", + "name", + "label", + "description", + "data_type", + "unit", + "economy", + "household", + "tax_benefit_model_version_id", + ], + sa.select( + col(StagedParameter.id), + sa.func.current_timestamp(), + col(StagedParameter.name), + col(StagedParameter.label), + col(StagedParameter.description), + col(StagedParameter.data_type), + col(StagedParameter.unit), + col(StagedParameter.economy), + col(StagedParameter.household), + col(TaxBenefitModelVersion.id), + ) + .select_from( + sa.join( + StagedParameter, + StagedModel, + col(StagedModel.country_id) == col(StagedParameter.country_id), + ) + .join(TaxBenefitModel, col(TaxBenefitModel.name) == col(StagedModel.name)) + .join( + TaxBenefitModelVersion, + sa.and_( + col(TaxBenefitModelVersion.model_id) == col(TaxBenefitModel.id), + col(TaxBenefitModelVersion.version) == col(StagedModel.version), + ), + ) + ) + .where( + col(StagedParameter.country_id) == COUNTRY_ID, + col(StagedParameter.is_dynamic).is_(sa.true() if dynamic else sa.false()), + ), + ) + + +INSERT_PARAMETERS = _parameters_insert(Parameter, dynamic=False) +INSERT_DYNAMIC_PARAMETERS = _parameters_insert(DynamicParameter, dynamic=True) + +INSERT_PARAMETER_VALUES = sa.insert(ParameterValue).from_select( [ "id", "created_at", - "name", - "label", - "description", - "data_type", - "unit", - "economy", - "household", - "tax_benefit_model_version_id", + "parameter_id", + "value_json", + "start_date", + "end_date", + "policy_id", + "dynamic_id", ], sa.select( - col(StagedParameter.id), + col(StagedParameterValue.id), sa.func.current_timestamp(), - col(StagedParameter.name), - col(StagedParameter.label), - col(StagedParameter.description), - col(StagedParameter.data_type), - col(StagedParameter.unit), - col(StagedParameter.economy), - col(StagedParameter.household), - col(TaxBenefitModelVersion.id), + col(Parameter.id), + sa.cast( + col(StagedParameterValue.value_json), + column_type(ParameterValue, "value_json"), + ), + col(StagedParameterValue.start_date), + col(StagedParameterValue.end_date), + sa.cast(sa.null(), column_type(ParameterValue, "policy_id")), + sa.cast(sa.null(), column_type(ParameterValue, "dynamic_id")), ) .select_from( sa.join( - StagedParameter, + StagedParameterValue, StagedModel, - col(StagedModel.country_id) == col(StagedParameter.country_id), + col(StagedModel.country_id) == col(StagedParameterValue.country_id), ) .join(TaxBenefitModel, col(TaxBenefitModel.name) == col(StagedModel.name)) .join( @@ -296,33 +356,42 @@ def column_type(model: type[SQLModel], column_name: str) -> TypeEngine[Any]: col(TaxBenefitModelVersion.version) == col(StagedModel.version), ), ) + .join( + Parameter, + sa.and_( + col(Parameter.tax_benefit_model_version_id) + == col(TaxBenefitModelVersion.id), + col(Parameter.name) == col(StagedParameterValue.parameter_name), + ), + ) ) - .where(col(StagedParameter.country_id) == COUNTRY_ID), + .where(col(StagedParameterValue.country_id) == COUNTRY_ID), ) -INSERT_PARAMETER_VALUES = sa.insert(ParameterValue).from_select( +# A model assumption's current-law values, joined to the stored dynamic +# parameter of the same name, as INSERT_PARAMETER_VALUES joins the others: each +# of the two inserts only the values of its own kind of parameter. +INSERT_DYNAMIC_PARAMETER_VALUES = sa.insert(DynamicParameterValue).from_select( [ "id", "created_at", - "parameter_id", + "dynamic_parameter_id", "value_json", "start_date", "end_date", - "policy_id", "dynamic_id", ], sa.select( col(StagedParameterValue.id), sa.func.current_timestamp(), - col(Parameter.id), + col(DynamicParameter.id), sa.cast( col(StagedParameterValue.value_json), - column_type(ParameterValue, "value_json"), + column_type(DynamicParameterValue, "value_json"), ), col(StagedParameterValue.start_date), col(StagedParameterValue.end_date), - sa.cast(sa.null(), column_type(ParameterValue, "policy_id")), - sa.cast(sa.null(), column_type(ParameterValue, "dynamic_id")), + sa.cast(sa.null(), column_type(DynamicParameterValue, "dynamic_id")), ) .select_from( sa.join( @@ -339,11 +408,11 @@ def column_type(model: type[SQLModel], column_name: str) -> TypeEngine[Any]: ), ) .join( - Parameter, + DynamicParameter, sa.and_( - col(Parameter.tax_benefit_model_version_id) + col(DynamicParameter.tax_benefit_model_version_id) == col(TaxBenefitModelVersion.id), - col(Parameter.name) == col(StagedParameterValue.parameter_name), + col(DynamicParameter.name) == col(StagedParameterValue.parameter_name), ), ) ) @@ -418,7 +487,9 @@ def column_type(model: type[SQLModel], column_name: str) -> TypeEngine[Any]: INSERT_VARIABLES, INSERT_PARAMETER_NODES, INSERT_PARAMETERS, + INSERT_DYNAMIC_PARAMETERS, INSERT_PARAMETER_VALUES, + INSERT_DYNAMIC_PARAMETER_VALUES, INSERT_REGIONS, ) diff --git a/policyengine_api/data/v2/catalog/publication_parameter_tree.py b/policyengine_api/data/v2/catalog/publication_parameter_tree.py index 7b5dc1338..b751d6792 100644 --- a/policyengine_api/data/v2/catalog/publication_parameter_tree.py +++ b/policyengine_api/data/v2/catalog/publication_parameter_tree.py @@ -15,6 +15,10 @@ Other stored versions get no tree here: deriving their rows from what earlier releases stored would be a data migration, which the migration rules leave to a human decision. + +The tree holds policy parameters only (C1 · 50): model assumptions, stored in +``dynamic_parameters``, and the folders that hold only them are not rows of it +(``dynamic_parameter_records``). """ from __future__ import annotations @@ -27,6 +31,10 @@ import sqlalchemy as sa from sqlmodel import col +from policyengine_api.data.v2.catalog.dynamic_parameter_records import ( + policy_node_records, + policy_parameter_records, +) from policyengine_api.data.v2.catalog.parameter_tree import ( ParameterTreeChildRow, TreeNodeSource, @@ -95,14 +103,17 @@ def _stored_parameter_ids(session: Session, version_id: UUID) -> dict[str, UUID] def catalog_parameter_tree( country: CountryCatalog, stored_parameter_ids: dict[str, UUID] ) -> tuple[ParameterTreeChildRow, ...]: - """Build a country version's tree from its catalog records. + """Build a country version's policy tree from its catalog records. - Each parameter row references the stored parameter of the same name; - raise CatalogPublicationError if a catalog parameter has no stored row. + It holds the policy parameters and the nodes outside the folders of model + assumptions. Each parameter row references the stored parameter of the + same name; raise CatalogPublicationError if a policy parameter of the + catalog has no stored row. """ + parameters = policy_parameter_records(country) missing = [ parameter.name - for parameter in country.parameters + for parameter in parameters if parameter.name not in stored_parameter_ids ] if missing: @@ -114,7 +125,7 @@ def catalog_parameter_tree( return build_parameter_tree( nodes=[ TreeNodeSource(name=node.name, label=node.label) - for node in country.parameter_nodes + for node in policy_node_records(country) ], parameters=[ TreeParameterSource( @@ -124,7 +135,7 @@ def catalog_parameter_tree( economy=parameter.economy, household=parameter.household, ) - for parameter in country.parameters + for parameter in parameters ], enum_labels=enum_value_labels(country), ) diff --git a/policyengine_api/data/v2/catalog/publication_pruning.py b/policyengine_api/data/v2/catalog/publication_pruning.py index 4f141b215..4028fd157 100644 --- a/policyengine_api/data/v2/catalog/publication_pruning.py +++ b/policyengine_api/data/v2/catalog/publication_pruning.py @@ -13,14 +13,14 @@ release workflow seeds before it deploys. Pruning a version deletes exactly: - its current-law parameter values: those of its parameters with neither a - policy nor a dynamic; + policy nor a dynamic, and those of its dynamic parameters with no dynamic; - its parameter tree rows; - its parameter search files; and sets its ``catalog_values_pruned_at``, all in one transaction. It never deletes parameters (their values cascade with them, saved reforms' included), -the model version row, its parameter nodes, variables, regions or datasets, or -any value a policy or dynamic owns. +the model version row, its parameter nodes, variables, regions or datasets, its +dynamic parameters, or any value a policy or dynamic owns. These rows are package-derived: publishing a pruned version again, as a rollback that installs it does, restores them from the installed packages @@ -40,6 +40,7 @@ from sqlmodel import col from policyengine_api.data.v2.catalog.publication_inserts import ( + INSERT_DYNAMIC_PARAMETER_VALUES, INSERT_PARAMETER_VALUES, RAW_DML_STRATEGY, ) @@ -47,6 +48,8 @@ CatalogPruningFailure, ) from policyengine_api.data.v2.models import ( + DynamicParameter, + DynamicParameterValue, Parameter, ParameterSearchFile, ParameterTreeChild, @@ -124,6 +127,7 @@ class PrunedRows: """The rows pruning deleted from one catalog version, per table.""" parameter_values: int + dynamic_parameter_values: int parameter_tree_children: int parameter_search_files: int @@ -249,7 +253,7 @@ def record_catalog_publication( def prune_catalog_version(session: Session, version_id: UUID) -> PrunedRows | None: - """Delete one version's current-law values, tree rows and search files. + """Delete one version's current-law values of both tables, tree rows and files. Sets the version's ``catalog_values_pruned_at`` first, only if it is unset, and returns None without deleting anything when it was set already. @@ -283,6 +287,18 @@ def prune_catalog_version(session: Session, version_id: UUID) -> PrunedRows | No col(ParameterValue.dynamic_id).is_(None), ), ) + version_dynamic_parameter_ids = sa.select(col(DynamicParameter.id)).where( + col(DynamicParameter.tax_benefit_model_version_id) == version_id + ) + dynamic_parameter_values = _changed_rows( + session, + sa.delete(DynamicParameterValue).where( + col(DynamicParameterValue.dynamic_parameter_id).in_( + version_dynamic_parameter_ids + ), + col(DynamicParameterValue.dynamic_id).is_(None), + ), + ) tree_rows = _changed_rows( session, sa.delete(ParameterTreeChild).where( @@ -297,6 +313,7 @@ def prune_catalog_version(session: Session, version_id: UUID) -> PrunedRows | No ) return PrunedRows( parameter_values=parameter_values, + dynamic_parameter_values=dynamic_parameter_values, parameter_tree_children=tree_rows, parameter_search_files=search_files, ) @@ -367,28 +384,26 @@ def _pruned_version_id(session: Session, country: CountryCatalog) -> UUID | None def restore_pruned_catalog_versions( session: Session, countries: Sequence[CountryCatalog] -) -> tuple[tuple[str, str, int], ...]: +) -> tuple[tuple[str, str, int, int], ...]: """Write back the current-law values of each staged version that was pruned. Inserts the staged catalog's values, with their catalog IDs, for the - stored parameters of the same names, as publishing a new version does, and - clears the version's marker. Returns the country, version and values - written for each, in catalog order. Runs inside publication's transaction, - after staging and before the stored versions are compared with the staged - catalog, which then checks the restored values like every other table. + stored parameters and dynamic parameters of the same names, as publishing + a new version does, and clears the version's marker. Returns the country, + version and values written to each table for each, in catalog order. Runs + inside publication's transaction, after staging and before the stored + versions are compared with the staged catalog, which then checks the + restored values like every other table. """ restored = [] for country in countries: version_id = _pruned_version_id(session, country) if version_id is None: continue - # SQLAlchemy keeps an INSERT's row count only when asked to. - inserted = session.execute( - INSERT_PARAMETER_VALUES.execution_options(preserve_rowcount=True), - {"country_id": country.country_id}, - execution_options=RAW_DML_STRATEGY, + parameter_values, dynamic_parameter_values = ( + _inserted_rows(session, statement, country) + for statement in (INSERT_PARAMETER_VALUES, INSERT_DYNAMIC_PARAMETER_VALUES) ) - parameter_values = cast("CursorResult[Any]", inserted).rowcount _changed_rows( session, sa.update(TaxBenefitModelVersion) @@ -396,6 +411,24 @@ def restore_pruned_catalog_versions( .values(catalog_values_pruned_at=None), ) restored.append( - (country.country_id, country.model_version.version, parameter_values) + ( + country.country_id, + country.model_version.version, + parameter_values, + dynamic_parameter_values, + ) ) return tuple(restored) + + +def _inserted_rows( + session: Session, statement: sa.Insert, country: CountryCatalog +) -> int: + """Run one staged-values INSERT for the country and return its row count.""" + # SQLAlchemy keeps an INSERT's row count only when asked to. + inserted = session.execute( + statement.execution_options(preserve_rowcount=True), + {"country_id": country.country_id}, + execution_options=RAW_DML_STRATEGY, + ) + return cast("CursorResult[Any]", inserted).rowcount diff --git a/policyengine_api/data/v2/catalog/publication_reconciliation.py b/policyengine_api/data/v2/catalog/publication_reconciliation.py index cad40cb56..4edd09199 100644 --- a/policyengine_api/data/v2/catalog/publication_reconciliation.py +++ b/policyengine_api/data/v2/catalog/publication_reconciliation.py @@ -26,6 +26,8 @@ ) from policyengine_api.data.v2.models import ( Dataset, + DynamicParameter, + DynamicParameterValue, Parameter, ParameterNode, ParameterValue, @@ -43,7 +45,9 @@ from policyengine_api.data.v2.catalog.records import CountryCatalog # The catalog tables whose rows belong to one model version. -VersionedCatalogRow = Variable | ParameterNode | Parameter | Dataset | Region +VersionedCatalogRow = ( + Variable | ParameterNode | Parameter | DynamicParameter | Dataset | Region +) # A selected column: a mapped attribute, or an expression such as a cast. ColumnExpression = sa.ColumnElement[Any] | Mapped[Any] @@ -230,36 +234,91 @@ def format_2(*columns: ColumnExpression) -> tuple[ColumnExpression, ...]: .where(selected_version) ) - staged_parameters = sa.select( - col(StagedParameter.name), - col(StagedParameter.label), - col(StagedParameter.description), - col(StagedParameter.data_type), - col(StagedParameter.unit), - *format_2( - col(StagedParameter.economy), - col(StagedParameter.household), - ), - ).where(col(StagedParameter.country_id) == country.country_id) - actual_parameters = ( + def staged_parameters(*, dynamic: bool) -> Select: + return sa.select( + col(StagedParameter.name), + col(StagedParameter.label), + col(StagedParameter.description), + col(StagedParameter.data_type), + col(StagedParameter.unit), + *format_2( + col(StagedParameter.economy), + col(StagedParameter.household), + ), + ).where( + col(StagedParameter.country_id) == country.country_id, + col(StagedParameter.is_dynamic).is_(sa.true() if dynamic else sa.false()), + ) + + def actual_parameters(model: type[Parameter | DynamicParameter]) -> Select: + return ( + sa.select( + col(model.name), + col(model.label), + col(model.description), + col(model.data_type), + col(model.unit), + *format_2(col(model.economy), col(model.household)), + ) + .select_from(_versioned_from(model)) + .where(selected_version) + ) + + def staged_parameter_values(*, dynamic: bool) -> Select: + """Select one kind of parameter's staged values, by its staged row.""" + return ( + sa.select( + col(StagedParameterValue.parameter_name), + col(StagedParameterValue.value_json), + col(StagedParameterValue.start_date), + col(StagedParameterValue.end_date), + ) + .select_from( + sa.join( + StagedParameterValue, + StagedParameter, + sa.and_( + col(StagedParameter.country_id) + == col(StagedParameterValue.country_id), + col(StagedParameter.name) + == col(StagedParameterValue.parameter_name), + ), + ) + ) + .where( + col(StagedParameterValue.country_id) == country.country_id, + col(StagedParameter.is_dynamic).is_( + sa.true() if dynamic else sa.false() + ), + ) + ) + + actual_dynamic_parameter_values = ( sa.select( - col(Parameter.name), - col(Parameter.label), - col(Parameter.description), - col(Parameter.data_type), - col(Parameter.unit), - *format_2(col(Parameter.economy), col(Parameter.household)), + col(DynamicParameter.name), + sa.cast(col(DynamicParameterValue.value_json), JSONB), + col(DynamicParameterValue.start_date), + col(DynamicParameterValue.end_date), ) - .select_from(_versioned_from(Parameter)) - .where(selected_version) + .select_from( + sa.join( + DynamicParameterValue, + DynamicParameter, + col(DynamicParameter.id) + == col(DynamicParameterValue.dynamic_parameter_id), + ) + .join( + TaxBenefitModelVersion, + col(TaxBenefitModelVersion.id) + == col(DynamicParameter.tax_benefit_model_version_id), + ) + .join( + TaxBenefitModel, + col(TaxBenefitModel.id) == col(TaxBenefitModelVersion.model_id), + ) + ) + .where(selected_version, col(DynamicParameterValue.dynamic_id).is_(None)) ) - - staged_parameter_values = sa.select( - col(StagedParameterValue.parameter_name), - col(StagedParameterValue.value_json), - col(StagedParameterValue.start_date), - col(StagedParameterValue.end_date), - ).where(col(StagedParameterValue.country_id) == country.country_id) actual_parameter_values = ( sa.select( col(Parameter.name), @@ -317,8 +376,26 @@ def format_2(*columns: ColumnExpression) -> tuple[ColumnExpression, ...]: ("model version", staged_model_version, actual_model_version), ("variables", staged_variables, actual_variables), ("parameter nodes", staged_parameter_nodes, actual_parameter_nodes), - ("parameters", staged_parameters, actual_parameters), - ("parameter values", staged_parameter_values, actual_parameter_values), + ( + "parameters", + staged_parameters(dynamic=False), + actual_parameters(Parameter), + ), + ( + "dynamic parameters", + staged_parameters(dynamic=True), + actual_parameters(DynamicParameter), + ), + ( + "parameter values", + staged_parameter_values(dynamic=False), + actual_parameter_values, + ), + ( + "dynamic parameter values", + staged_parameter_values(dynamic=True), + actual_dynamic_parameter_values, + ), ("datasets", staged_datasets, actual_datasets), ) @@ -502,8 +579,8 @@ def count_region_differences( def assert_canonical_value_uniqueness(session: Session) -> None: """Raise CatalogPublicationError if a parameter has duplicate current-law values. - Current-law values are those with neither a policy nor a dynamic; each - parameter may have only one per start date. + Current-law values are those with neither a policy nor a dynamic, in + either table; each parameter may have only one per start date. """ duplicates = ( sa.select(col(ParameterValue.parameter_id)) @@ -518,6 +595,19 @@ def assert_canonical_value_uniqueness(session: Session) -> None: .having(sa.func.count() > 1) .limit(1) ) - if session.execute(duplicates).first() is not None: + dynamic_duplicates = ( + sa.select(col(DynamicParameterValue.dynamic_parameter_id)) + .where(col(DynamicParameterValue.dynamic_id).is_(None)) + .group_by( + col(DynamicParameterValue.dynamic_parameter_id), + col(DynamicParameterValue.start_date), + ) + .having(sa.func.count() > 1) + .limit(1) + ) + if ( + session.execute(duplicates).first() is not None + or session.execute(dynamic_duplicates).first() is not None + ): msg = "canonical parameter-value uniqueness validation failed" raise CatalogPublicationError(msg) diff --git a/policyengine_api/data/v2/catalog/publication_staging.py b/policyengine_api/data/v2/catalog/publication_staging.py index 82a7d8dbf..418334f11 100644 --- a/policyengine_api/data/v2/catalog/publication_staging.py +++ b/policyengine_api/data/v2/catalog/publication_staging.py @@ -12,6 +12,9 @@ from psycopg import sql from psycopg.types.json import Jsonb +from policyengine_api.data.v2.catalog.dynamic_parameter_records import ( + is_dynamic_record, +) from policyengine_api.data.v2.catalog.publication_staging_base import ( STAGING_METADATA, STAGING_MODELS, @@ -131,7 +134,7 @@ def _parameter_node_rows(country: CountryCatalog) -> Iterator[tuple[object, ...] def _parameter_rows(country: CountryCatalog) -> Iterator[tuple[object, ...]]: - """Yield one row per parameter, in bounded batches.""" + """Yield one row per parameter, in bounded batches, marking model assumptions.""" for batch in iter_batches(country.parameters, batch_size=COPY_BATCH_SIZE): for record in batch: yield ( @@ -144,6 +147,7 @@ def _parameter_rows(country: CountryCatalog) -> Iterator[tuple[object, ...]]: record.unit, record.economy, record.household, + is_dynamic_record(country.country_id, record.name), ) diff --git a/policyengine_api/data/v2/catalog/publication_staging_base.py b/policyengine_api/data/v2/catalog/publication_staging_base.py index 5d2e86133..940a5fb4f 100644 --- a/policyengine_api/data/v2/catalog/publication_staging_base.py +++ b/policyengine_api/data/v2/catalog/publication_staging_base.py @@ -102,7 +102,12 @@ class StagedParameterNode(StagingBase, table=True): class StagedParameter(StagingBase, table=True): - """One parameter of a country's catalog.""" + """One parameter of a country's catalog. + + ``is_dynamic`` marks a model assumption, which publication stores in + ``dynamic_parameters`` (``dynamic_parameter_records``); its values follow it + by name. + """ __tablename__ = "stage_catalog_parameters" __table_args__ = TEMPORARY_UNTIL_COMMIT @@ -116,6 +121,7 @@ class StagedParameter(StagingBase, table=True): unit: str | None = Field(default=None, sa_type=sa.Text) economy: bool = Field(sa_type=sa.Boolean) household: bool = Field(sa_type=sa.Boolean) + is_dynamic: bool = Field(sa_type=sa.Boolean) class StagedParameterValue(StagingBase, table=True): diff --git a/policyengine_api/data/v2/catalog/publication_statistics.py b/policyengine_api/data/v2/catalog/publication_statistics.py index d3447fb68..244fa7387 100644 --- a/policyengine_api/data/v2/catalog/publication_statistics.py +++ b/policyengine_api/data/v2/catalog/publication_statistics.py @@ -40,6 +40,8 @@ CATALOG_STATISTICS_TABLES: Final = ( "datasets", + "dynamic_parameter_values", + "dynamic_parameters", "parameter_nodes", "parameter_tree_children", "parameter_values", diff --git a/policyengine_api/data/v2/catalog/publication_types.py b/policyengine_api/data/v2/catalog/publication_types.py index 6bde1ca71..6cd1827c7 100644 --- a/policyengine_api/data/v2/catalog/publication_types.py +++ b/policyengine_api/data/v2/catalog/publication_types.py @@ -14,13 +14,15 @@ class PrunedCatalogVersion: """A stored catalog version that pruning removed current-law data from. The counts are the rows deleted from each table: the version's current-law - parameter values (those no policy or dynamic owns), its parameter tree - rows and its parameter search files. + parameter values (those no policy owns), its dynamic parameters' + current-law values (those no dynamic owns), its parameter tree rows and its + parameter search files. """ country_id: str policyengine_version: str parameter_values: int + dynamic_parameter_values: int parameter_tree_children: int parameter_search_files: int @@ -100,10 +102,10 @@ class PublicationEvidence: # model, version, and the file's uncompressed and compressed sizes in bytes. parameter_search_files_written: tuple[tuple[str, str, int, int], ...] = () # Pruned catalog versions this publication published again, which it - # restored: country, version and the current-law values written back. The - # same publication writes their trees and search files, which the two - # fields above list. - restored_catalog_versions: tuple[tuple[str, str, int], ...] = () + # restored: country, version and the current-law values written back, of + # policy parameters and of dynamic parameters. The same publication writes + # their trees and search files, which the two fields above list. + restored_catalog_versions: tuple[tuple[str, str, int, int], ...] = () # Older catalog versions pruned after the publication committed, and those # whose pruning failed and was rolled back; the next publication retries. pruned_catalog_versions: tuple[PrunedCatalogVersion, ...] = () @@ -180,8 +182,9 @@ def as_dict(self) -> dict[str, object]: "country_id": country_id, "policyengine_version": version, "parameter_values": parameter_values, + "dynamic_parameter_values": dynamic_parameter_values, } - for country_id, version, parameter_values in ( + for country_id, version, parameter_values, dynamic_parameter_values in ( self.restored_catalog_versions ) ], @@ -191,6 +194,7 @@ def as_dict(self) -> dict[str, object]: "policyengine_version": pruned.policyengine_version, "deleted_rows": { "parameter_values": pruned.parameter_values, + "dynamic_parameter_values": pruned.dynamic_parameter_values, "parameter_tree_children": pruned.parameter_tree_children, "parameter_search_files": pruned.parameter_search_files, }, diff --git a/policyengine_api/data/v2/dynamic_parameter_move_qualification.py b/policyengine_api/data/v2/dynamic_parameter_move_qualification.py new file mode 100644 index 000000000..d2e81bac9 --- /dev/null +++ b/policyengine_api/data/v2/dynamic_parameter_move_qualification.py @@ -0,0 +1,214 @@ +"""Read-only check before revision 7f7335f0eb31 moves dynamic parameters. + +The revision moves every stored model assumption (``dynamic_parameters``' +prefixes) out of ``parameters``. Deleting one would delete every +``parameter_values`` row that names it, so a policy value naming one would +silently change its policy: the revision refuses to run while any exists. +This step counts the same values, in one ``READ ONLY`` transaction, while the +revision is pending, and stops the seed workflow before the schema upgrade +when there are any, so a deploy fails with the count before Alembic starts. +Operator step C1 · 49 splits such policies into a policy and a dynamic. + +A parameter is a model assumption of its country, the country of its +catalog version's model ``policyengine-``, as the revision decides. +""" + +from __future__ import annotations + +import json +import sys +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from sqlalchemy import and_, func, or_, select +from sqlmodel import col + +from policyengine_api.data.v2.models import ( + Parameter, + ParameterValue, + TaxBenefitModel, + TaxBenefitModelVersion, +) +from policyengine_api.data.v2.pending_revisions import v2_revision_is_pending +from policyengine_api.data.v2.settings import ( + V2ConfigurationError, + V2DatabaseSettings, + load_v2_migration_database_settings, +) +from policyengine_api.dynamic_parameters import DYNAMIC_PARAMETER_PREFIXES + +if TYPE_CHECKING: + from collections.abc import Callable, Mapping + from contextlib import AbstractContextManager + + from sqlalchemy import ColumnElement + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + +DYNAMIC_PARAMETER_TABLES_REVISION = "7f7335f0eb31" + + +@dataclass(frozen=True) +class DynamicParameterMoveQualification: + """Non-secret evidence that no policy value names a dynamic parameter. + + ``required`` is False when the revision was already applied, and nothing + was counted. + """ + + environment: str + project_ref: str + policy_values_naming_dynamic_parameters: int + required: bool = True + + def as_dict(self) -> dict[str, object]: + """Return the evidence as the JSON object the command prints.""" + return { + "outcome": "ok", + "qualification": "performed" if self.required else "not-required", + "environment": self.environment, + "project_ref": self.project_ref, + "counts": { + "policy_values_naming_dynamic_parameters": ( + self.policy_values_naming_dynamic_parameters + ) + }, + } + + +class PolicyValuesNameDynamicParametersError(RuntimeError): + """Raised while policy values name parameters the revision would move.""" + + def __init__(self, count: int) -> None: + """Keep the count and say in the message how to proceed.""" + self.count = count + values = ( + "policy value names a dynamic parameter" + if count == 1 + else ("policy values name dynamic parameters") + ) + super().__init__( + f"{count} {values} (gov.simulation., US simulation. or UK " + "gov.dynamic.) in the configured Supabase target; the move of " + "dynamic parameters into their own tables (revision " + f"{DYNAMIC_PARAMETER_TABLES_REVISION}) would delete them with their " + "parameters, so it stopped before the schema upgrade without " + "modifying data. Split those policies into a policy and a dynamic " + "first (operator step C1 · 49), then deploy again" + ) + + +def _names_a_dynamic_parameter() -> ColumnElement[bool]: + """Select whether a parameter is a model assumption of its model's country.""" + return or_( + *( + and_( + col(TaxBenefitModel.name) == f"policyengine-{country_id}", + or_( + *( + func.starts_with(col(Parameter.name), prefix) + for prefix in prefixes + ) + ), + ) + for country_id, prefixes in DYNAMIC_PARAMETER_PREFIXES.items() + ) + ) + + +def count_policy_values_naming_dynamic_parameters(session: Session) -> int: + """Count the policy values whose parameter the revision would move.""" + count = session.scalar( + select(func.count()) + .select_from(ParameterValue) + .join(Parameter, col(Parameter.id) == col(ParameterValue.parameter_id)) + .join( + TaxBenefitModelVersion, + col(TaxBenefitModelVersion.id) + == col(Parameter.tax_benefit_model_version_id), + ) + .join( + TaxBenefitModel, + col(TaxBenefitModel.id) == col(TaxBenefitModelVersion.model_id), + ) + .where( + col(ParameterValue.policy_id).is_not(None), + _names_a_dynamic_parameter(), + ) + ) + return int(count or 0) + + +def dynamic_parameter_move_is_pending(session: Session) -> bool: + """Return whether revision 7f7335f0eb31 is in the upgrade path.""" + return v2_revision_is_pending(session, DYNAMIC_PARAMETER_TABLES_REVISION) + + +def open_qualification_sessions( + settings: V2DatabaseSettings, +) -> AbstractContextManager[sessionmaker[Session]]: + """Open Session factories whose every transaction is READ ONLY, with no pool.""" + from policyengine_api.data.v2.database import unpooled_v2_read_only_sessions + + return unpooled_v2_read_only_sessions(settings.connection.url) + + +def qualify_dynamic_parameter_move_if_pending( + environ: Mapping[str, str] | None = None, + *, + session_factories: Callable[ + [V2DatabaseSettings], AbstractContextManager[sessionmaker[Session]] + ] = open_qualification_sessions, + pending_checker: Callable[[Session], bool] = dynamic_parameter_move_is_pending, +) -> DynamicParameterMoveQualification: + """Count the policy values naming dynamic parameters while the move is pending. + + The revision check and the count run in one READ ONLY transaction, rolled + back when the session closes. Raise PolicyValuesNameDynamicParametersError + when there are any. + """ + settings = load_v2_migration_database_settings(environ) + with session_factories(settings) as sessions, sessions() as session: + if not pending_checker(session): + return DynamicParameterMoveQualification( + environment=settings.target.environment, + project_ref=settings.target.project_ref, + policy_values_naming_dynamic_parameters=0, + required=False, + ) + count = count_policy_values_naming_dynamic_parameters(session) + if count: + raise PolicyValuesNameDynamicParametersError(count) + return DynamicParameterMoveQualification( + environment=settings.target.environment, + project_ref=settings.target.project_ref, + policy_values_naming_dynamic_parameters=0, + ) + + +def _error_payload(error: Exception) -> dict[str, object]: + safe_errors = (V2ConfigurationError, PolicyValuesNameDynamicParametersError) + message = ( + str(error) + if isinstance(error, safe_errors) + else "v2 dynamic parameter move qualification failed unexpectedly" + ) + return { + "outcome": "error", + "error": {"type": type(error).__name__, "message": message}, + } + + +def main() -> int: + """Run the check and return a shell-compatible status.""" + try: + evidence = qualify_dynamic_parameter_move_if_pending() + except Exception as error: # noqa: BLE001 # command must emit safe evidence + sys.stderr.write(json.dumps(_error_payload(error), sort_keys=True) + "\n") + return 1 + sys.stdout.write(json.dumps(evidence.as_dict(), sort_keys=True) + "\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/policyengine_api/data/v2/migration_target.py b/policyengine_api/data/v2/migration_target.py index c3d11ea25..bf6858886 100644 --- a/policyengine_api/data/v2/migration_target.py +++ b/policyengine_api/data/v2/migration_target.py @@ -27,7 +27,7 @@ from sqlmodel import Session V2_ALEMBIC_DISPOSABLE_TEST = "V2_ALEMBIC_DISPOSABLE_TEST" -V2_ALEMBIC_HEAD_REVISION = "d417fe8b1b17" +V2_ALEMBIC_HEAD_REVISION = "7f7335f0eb31" DISPOSABLE_DATABASE_NAME = "policyengine_v2_alembic_test" DISPOSABLE_HOSTS = frozenset({"localhost", "127.0.0.1", "::1", "postgres"}) MIGRATION_ROLE = "policyengine_v2_migrator" diff --git a/policyengine_api/data/v2/models/__init__.py b/policyengine_api/data/v2/models/__init__.py index 471d7f8e4..2e0aaa6b2 100644 --- a/policyengine_api/data/v2/models/__init__.py +++ b/policyengine_api/data/v2/models/__init__.py @@ -48,6 +48,8 @@ CatalogEnumValue, Dataset, DatasetVersion, + DynamicParameter, + DynamicParameterValue, Parameter, ParameterNode, ParameterSearchFile, @@ -145,6 +147,8 @@ "DecileImpact", "DecileType", "Dynamic", + "DynamicParameter", + "DynamicParameterValue", "Household", "HouseholdJob", "HouseholdJobStatus", diff --git a/policyengine_api/data/v2/models/metadata.py b/policyengine_api/data/v2/models/metadata.py index 018bb6edb..0ad97659a 100644 --- a/policyengine_api/data/v2/models/metadata.py +++ b/policyengine_api/data/v2/models/metadata.py @@ -87,14 +87,16 @@ class TaxBenefitModel(TimestampedModel, table=True): class TaxBenefitModelVersion(IdentifiedModel, table=True): """One published catalog version of a model, unique per model and version. - Owns its variables, parameters and parameter nodes, which are deleted with it, - and records the country's current-law policy id and the years its metadata - covers. ``catalog_last_published_at`` records when catalog publication last - published the version, which decides the versions catalog pruning keeps. + Owns its variables, parameters, dynamic parameters and parameter nodes, + which are deleted with it, and records the country's current-law policy id + and the years its metadata covers. ``catalog_last_published_at`` records + when catalog publication last published the version, which decides the + versions catalog pruning keeps. ``catalog_values_pruned_at`` records when catalog publication pruned the - version: it deleted the version's current-law parameter values, parameter - tree rows and parameter search file, which publishing the version again - restores from the installed packages, clearing the marker. + version: it deleted the version's current-law values of policy and dynamic + parameters, parameter tree rows and parameter search file, which + publishing the version again restores from the installed packages, + clearing the marker. ``spm_availability`` records whether the version offers SPM settings. """ @@ -147,6 +149,10 @@ class TaxBenefitModelVersion(IdentifiedModel, table=True): back_populates="tax_benefit_model_version", cascade_delete=True, ) + dynamic_parameters: list["DynamicParameter"] = Relationship( + back_populates="tax_benefit_model_version", + cascade_delete=True, + ) parameter_nodes: list["ParameterNode"] = Relationship( back_populates="tax_benefit_model_version", cascade_delete=True, @@ -353,7 +359,8 @@ class Variable(IdentifiedModel, table=True): class ParameterNode(IdentifiedModel, table=True): """A non-leaf node of a version's parameter tree, which groups parameters. - Unique by name within the version, and has no values of its own. + Unique by name within the version, and has no values of its own. Policy + parameters and dynamic parameters share the nodes: ``gov`` is above both. """ __tablename__ = "parameter_nodes" @@ -380,9 +387,10 @@ class ParameterNode(IdentifiedModel, table=True): class Parameter(IdentifiedModel, table=True): - """A leaf parameter of a model version, unique by name within it. + """A leaf policy parameter of a model version, unique by name within it. - Its values include current law and the values each policy or dynamic sets. + Its values are current law and the values each policy sets. The version's + model assumptions are ``DynamicParameter`` rows instead. """ __tablename__ = "parameters" @@ -420,9 +428,12 @@ class Parameter(IdentifiedModel, table=True): class ParameterValue(IdentifiedModel, table=True): """A parameter's value from ``start_date`` until ``end_date``, or indefinitely. - A value owned by a policy or dynamic is deleted with its owner, and each - owner sets at most one per parameter and start date. A value with neither - is current law, and a parameter has at most one per start date. + A value owned by a policy is deleted with it, and a policy sets at most one + per parameter and start date. A value with no policy is current law, and a + parameter has at most one per start date. ``dynamic_id`` is no longer + written: a dynamic's values are ``DynamicParameterValue`` rows since + revision 7f7335f0eb31 moved them, and C1 · 53 drops the column, its check + and its index once no simulation service release maps it. """ __tablename__ = "parameter_values" @@ -497,6 +508,113 @@ class ParameterValue(IdentifiedModel, table=True): parameter: Parameter = Relationship(back_populates="values") policy: Optional["Policy"] = Relationship(back_populates="parameter_values") + + +# The value and date column types of ``DynamicParameterValue``, as +# ``ParameterValue`` declares them. SQLModel's Field annotates sa_type as a type +# class, but these are instances of one. +_VALUE_JSON_TYPE: Any = sa.JSON().with_variant( + sa.dialects.postgresql.JSONB(), "postgresql" +) +_TIMESTAMP_WITH_TIME_ZONE: Any = sa.DateTime(timezone=True) + + +class DynamicParameter(IdentifiedModel, table=True): + """A model assumption of a model version, unique by name within it. + + Every parameter a dynamic may set (``policyengine_api.dynamic_parameters``: + ``gov.simulation.``, US ``simulation.`` and UK ``gov.dynamic.``), with a + policy parameter's columns and catalog ID + (``catalog_identifier("parameter", version, name)``). Its values are its + current law and the values each dynamic sets. + """ + + __tablename__ = "dynamic_parameters" + __table_args__ = ( + sa.UniqueConstraint( + "tax_benefit_model_version_id", + "name", + name="uq_dynamic_parameters_model_version_name", + ), + ) + + name: str = Field(max_length=512) + label: str | None = Field(default=None, max_length=512) + description: str | None = None + data_type: str | None = Field(default=None, max_length=128) + unit: str | None = Field(default=None, max_length=128) + # Catalog format 2 fields; null in versions published before it. + economy: bool | None = None + household: bool | None = None + tax_benefit_model_version_id: UUID = Field( + foreign_key="tax_benefit_model_versions.id", + ondelete="CASCADE", + index=True, + ) + + tax_benefit_model_version: TaxBenefitModelVersion = Relationship( + back_populates="dynamic_parameters" + ) + values: list["DynamicParameterValue"] = Relationship( + back_populates="dynamic_parameter", + cascade_delete=True, + ) + + +class DynamicParameterValue(IdentifiedModel, table=True): + """A dynamic parameter's value from ``start_date`` until ``end_date``, or on. + + A value with a dynamic is one of the values that dynamic sets, deleted with + it, and a dynamic sets at most one per parameter and start date. A value + without one is current law, and a parameter has at most one per start date. + No policy owns one. + """ + + __tablename__ = "dynamic_parameter_values" + __table_args__ = ( + sa.CheckConstraint( + "end_date IS NULL OR end_date >= start_date", + name="ck_dynamic_parameter_values_effective_period", + ), + sa.Index( + "uq_dynamic_parameter_values_dynamic_parameter_start_date", + "dynamic_id", + "dynamic_parameter_id", + "start_date", + unique=True, + postgresql_where=sa.text("dynamic_id IS NOT NULL"), + sqlite_where=sa.text("dynamic_id IS NOT NULL"), + ), + sa.Index( + "ix_dynamic_parameter_values_parameter_period", + "dynamic_parameter_id", + "start_date", + "end_date", + ), + sa.Index( + "uq_dynamic_parameter_values_current_law_parameter_start_date", + "dynamic_parameter_id", + "start_date", + unique=True, + postgresql_where=sa.text("dynamic_id IS NULL"), + sqlite_where=sa.text("dynamic_id IS NULL"), + ), + ) + + dynamic_parameter_id: UUID = Field( + foreign_key="dynamic_parameters.id", + ondelete="CASCADE", + ) + value_json: Any = Field(sa_type=_VALUE_JSON_TYPE) + start_date: datetime = Field(sa_type=_TIMESTAMP_WITH_TIME_ZONE) + end_date: datetime | None = Field(default=None, sa_type=_TIMESTAMP_WITH_TIME_ZONE) + dynamic_id: UUID | None = Field( + default=None, + foreign_key="dynamics.id", + ondelete="CASCADE", + ) + + dynamic_parameter: DynamicParameter = Relationship(back_populates="values") dynamic: Optional["Dynamic"] = Relationship(back_populates="parameter_values") diff --git a/policyengine_api/data/v2/models/policies.py b/policyengine_api/data/v2/models/policies.py index 5b2ecb551..9c2e905a9 100644 --- a/policyengine_api/data/v2/models/policies.py +++ b/policyengine_api/data/v2/models/policies.py @@ -13,6 +13,7 @@ from policyengine_api.data.v2.models.associations import UserDynamic, UserPolicy from policyengine_api.data.v2.models.households import HouseholdJob from policyengine_api.data.v2.models.metadata import ( + DynamicParameterValue, ParameterValue, TaxBenefitModelVersion, ) @@ -152,7 +153,7 @@ class Dynamic(TimestampedModel, table=True): tax_benefit_model_version: "TaxBenefitModelVersion" = Relationship( back_populates="dynamics" ) - parameter_values: list["ParameterValue"] = Relationship( + parameter_values: list["DynamicParameterValue"] = Relationship( back_populates="dynamic", cascade_delete=True, ) diff --git a/policyengine_api/data/v2/privileges.py b/policyengine_api/data/v2/privileges.py index 2a8d00208..85cc272cd 100644 --- a/policyengine_api/data/v2/privileges.py +++ b/policyengine_api/data/v2/privileges.py @@ -287,7 +287,7 @@ def _run_table( # The UK areas disclosure control withheld from a local-area run's results. "withheld_area_codes": _RESULT, # Metadata catalog: the catalog writer publishes it, the Public API reads it. - # The writer also analyzes seven of them after every publication (_ANALYZE). + # The writer also analyzes nine of them after every publication (_ANALYZE). "dataset_versions": _access(catalog_writer=READ), "datasets": _access( runtime=READ, catalog_writer=READ_INSERT_UPDATE | _ANALYZE, **_RUN_INPUT_READS @@ -304,15 +304,29 @@ def _run_table( "parameter_tree_children": _access( runtime=READ, catalog_writer=READ_INSERT_DELETE | _ANALYZE ), - # API v1 also inserts a v2 policy's or dynamic's own parameter - # values. Catalog pruning deletes an older version's current-law values - # (those with no policy or dynamic), never a policy's or a dynamic's. + # API v1 also inserts a v2 policy's own parameter values. Catalog pruning + # deletes an older version's current-law values (those with no policy or + # dynamic), never a policy's. Dynamics' values were moved to + # dynamic_parameter_values (C1 · 50). "parameter_values": _access( runtime=READ_INSERT, catalog_writer=READ_WRITE | _ANALYZE, **_RUN_INPUT_READS ), "parameters": _access( runtime=READ, catalog_writer=READ_INSERT_UPDATE | _ANALYZE, **_RUN_INPUT_READS ), + # Model assumptions, apart from the policy parameters since C1 · 50, granted + # as those are: publication writes them, and a run reads a dynamic's. + "dynamic_parameters": _access( + runtime=READ, catalog_writer=READ_INSERT_UPDATE | _ANALYZE, **_RUN_INPUT_READS + ), + # Their current-law values, which catalog pruning deletes from an older + # version, and every dynamic's values, which API v1 inserts with its + # dynamic and never changes. Publication never updates a value. + "dynamic_parameter_values": _access( + runtime=READ_INSERT, + catalog_writer=READ_INSERT_DELETE | _ANALYZE, + **_RUN_INPUT_READS, + ), "regions": _access( runtime=READ, catalog_writer=READ_INSERT_UPDATE | _ANALYZE, **_RUN_INPUT_READS ), diff --git a/policyengine_api/dynamic_parameters.py b/policyengine_api/dynamic_parameters.py index 76d30c8e4..aa1344242 100644 --- a/policyengine_api/dynamic_parameters.py +++ b/policyengine_api/dynamic_parameters.py @@ -9,15 +9,25 @@ 2.174.1, ``gov.dynamic.`` holds one parameter, ``gov.dynamic.obr_labour_supply_assumptions``, a yes/no switch. -The rule is used in three places: - +The rule is used in these places: + +- Catalog publication stores these parameters and their current-law values + in ``dynamic_parameters`` and ``dynamic_parameter_values`` (C1 · 50), and + every other parameter in ``parameters``; a dynamic's values are + ``dynamic_parameter_values`` rows. The policy tree and search file leave + them out, with the folders that hold only them + (``is_dynamic_parameter_path``). - ``POST /v2/policies`` refuses a policy that sets any such parameter, and - ``POST /v2/dynamics`` refuses a dynamic that sets any other. + ``POST /v2/dynamics`` refuses a dynamic that sets any other: each finds the + IDs it lacks in the other table and names them. - The copy of each v1 policy into v2 splits the v1 policy's values with ``split_legacy_policy_json``: these values become a dynamic and the rest the policy. - The one-time migration splits v1 policies with the same functions. +C1 · 50's revision, which moved the rows stored before, keeps its own copy of +the prefixes, and a test keeps the two the same. + The UK renamed ``gov.simulation.labor_supply_responses`` to ``gov.simulation.labour_supply_responses`` on 2026-05-01. Its catalog has only the new names, so a UK v1 policy saved with the old spelling is @@ -76,6 +86,20 @@ def is_dynamic_parameter(country_id: SupportedCountryId, parameter_name: str) -> return parameter_name.startswith(DYNAMIC_PARAMETER_PREFIXES[country_id]) +def is_dynamic_parameter_path(country_id: SupportedCountryId, path: str) -> bool: + """Return whether a node or parameter path holds only model assumptions. + + That is a dynamic folder itself (``gov.simulation``, US ``simulation``, UK + ``gov.dynamic``) or anything below one, a bracket included: the path + followed by ``.`` starts with one of the country's prefixes. ``gov`` holds + policy parameters too, so it is not one. For a parameter's name this is + ``is_dynamic_parameter``. The policy tree and search file leave these + paths out, and C1 · 50's revision deletes their stored tree rows by the + same rule. + """ + return f"{path}.".startswith(DYNAMIC_PARAMETER_PREFIXES[country_id]) + + def canonical_parameter_name( country_id: SupportedCountryId, parameter_name: str ) -> str: diff --git a/policyengine_api/services/v2/dynamics/database_connectors/creates.py b/policyengine_api/services/v2/dynamics/database_connectors/creates.py index 142e79d06..22584ceb4 100644 --- a/policyengine_api/services/v2/dynamics/database_connectors/creates.py +++ b/policyengine_api/services/v2/dynamics/database_connectors/creates.py @@ -8,7 +8,7 @@ from sqlalchemy.dialects.postgresql import insert from sqlmodel import Session, col -from policyengine_api.data.v2.models import Dynamic, ParameterValue +from policyengine_api.data.v2.models import Dynamic, DynamicParameterValue if TYPE_CHECKING: from policyengine_api.services.v2.dynamics.types import ( @@ -52,13 +52,16 @@ def create_dynamic_parameter_values( dynamic_id: UUID, dynamic_input: ResolvedDynamicCreationInput, ) -> None: - """Insert a new dynamic's parameter values and flush them for later reads.""" + """Insert a new dynamic's parameter values and flush them for later reads. + + Each value's ``parameter_id`` names a dynamic parameter, which + ``resolve_dynamic_creation_input`` found in ``dynamic_parameters``. + """ session.add_all( [ - ParameterValue( - policy_id=None, + DynamicParameterValue( dynamic_id=dynamic_id, - parameter_id=value.parameter_id, + dynamic_parameter_id=value.parameter_id, value_json=value.value, start_date=value.start_date, end_date=value.end_date, diff --git a/policyengine_api/services/v2/dynamics/database_connectors/reads.py b/policyengine_api/services/v2/dynamics/database_connectors/reads.py index 003ae1a8a..798000fdc 100644 --- a/policyengine_api/services/v2/dynamics/database_connectors/reads.py +++ b/policyengine_api/services/v2/dynamics/database_connectors/reads.py @@ -1,4 +1,8 @@ -"""Database selections used by immutable v2 dynamic operations.""" +"""Database selections used by immutable v2 dynamic operations. + +A dynamic's values are ``dynamic_parameter_values`` rows, and the parameters +it may set are ``dynamic_parameters`` rows (C1 · 50). +""" from __future__ import annotations @@ -6,11 +10,18 @@ from sqlmodel import Session, col, select -from policyengine_api.data.v2.models import Dynamic, Parameter, ParameterValue +from policyengine_api.data.v2.models import ( + Dynamic, + DynamicParameter, + DynamicParameterValue, +) if TYPE_CHECKING: from uuid import UUID +# Parameter names bound in one statement; far below PostgreSQL's 65,535 limit. +DYNAMIC_PARAMETER_NAME_BATCH_SIZE = 1_000 + def read_dynamic_by_content_identity( session: Session, *, canonicalization_version: int, content_hash: str @@ -24,13 +35,53 @@ def read_dynamic_by_content_identity( ).one_or_none() +def read_version_dynamic_parameter_names( + session: Session, *, model_version_id: UUID, requested_ids: set[UUID] +) -> dict[UUID, str]: + """Return the names of the requested dynamic parameters of this version, by id.""" + if not requested_ids: + return {} + return dict( + session.exec( + select(DynamicParameter.id, DynamicParameter.name).where( + DynamicParameter.tax_benefit_model_version_id == model_version_id, + col(DynamicParameter.id).in_(requested_ids), + ) + ).all() + ) + + +def read_dynamic_parameters_by_name( + session: Session, *, model_version_id: UUID, names: set[str] +) -> dict[str, DynamicParameter]: + """Return this version's dynamic parameters with the given names, by name. + + The names are read in batches of DYNAMIC_PARAMETER_NAME_BATCH_SIZE, as + a PostgreSQL statement takes at most 65,535 bound values. + """ + ordered_names = sorted(names) + found: dict[str, DynamicParameter] = {} + for start in range(0, len(ordered_names), DYNAMIC_PARAMETER_NAME_BATCH_SIZE): + batch = ordered_names[start : start + DYNAMIC_PARAMETER_NAME_BATCH_SIZE] + parameters = session.exec( + select(DynamicParameter).where( + DynamicParameter.tax_benefit_model_version_id == model_version_id, + col(DynamicParameter.name).in_(batch), + ) + ).all() + found.update((parameter.name, parameter) for parameter in parameters) + return found + + def read_dynamic_parameter_values( session: Session, dynamic_id: UUID -) -> list[ParameterValue]: +) -> list[DynamicParameterValue]: """Return every parameter value stored for one dynamic, in no particular order.""" return list( session.exec( - select(ParameterValue).where(ParameterValue.dynamic_id == dynamic_id) + select(DynamicParameterValue).where( + DynamicParameterValue.dynamic_id == dynamic_id + ) ).all() ) @@ -48,19 +99,23 @@ def read_dynamic_row( def read_dynamic_parameter_values_with_names( session: Session, dynamic_ids: list[UUID] -) -> list[tuple[ParameterValue, str]]: +) -> list[tuple[DynamicParameterValue, str]]: """Return the dynamics' values with parameter names, by name then start date.""" if not dynamic_ids: return [] return list( session.exec( - select(ParameterValue, Parameter.name) - .join(Parameter, col(Parameter.id) == col(ParameterValue.parameter_id)) - .where(col(ParameterValue.dynamic_id).in_(dynamic_ids)) + select(DynamicParameterValue, DynamicParameter.name) + .join( + DynamicParameter, + col(DynamicParameter.id) + == col(DynamicParameterValue.dynamic_parameter_id), + ) + .where(col(DynamicParameterValue.dynamic_id).in_(dynamic_ids)) .order_by( - col(Parameter.name), - col(ParameterValue.start_date), - col(ParameterValue.id), + col(DynamicParameter.name), + col(DynamicParameterValue.start_date), + col(DynamicParameterValue.id), ) ).all() ) diff --git a/policyengine_api/services/v2/dynamics/services.py b/policyengine_api/services/v2/dynamics/services.py index 28d8c7d81..23069b12a 100644 --- a/policyengine_api/services/v2/dynamics/services.py +++ b/policyengine_api/services/v2/dynamics/services.py @@ -25,13 +25,16 @@ read_dynamic_by_content_identity, read_dynamic_parameter_values, read_dynamic_parameter_values_with_names, + read_dynamic_parameters_by_name, read_dynamic_row, + read_version_dynamic_parameter_names, ) from policyengine_api.services.v2.dynamics.transformations import ( checked_dynamic_read, dynamic_creation_input, dynamic_parameter_values_by_dynamic, dynamic_read, + stored_dynamic_creation_input, ) from policyengine_api.services.v2.dynamics.types import ( CheckedDynamicRead, @@ -51,7 +54,6 @@ ) from policyengine_api.services.v2.policies.database_connectors.reads import ( read_model_version, - read_parameters_by_name, read_policy_catalog, read_version_parameter_names, ) @@ -59,7 +61,6 @@ canonical_policy_document, canonicalize_policy, policy_missing_parameters, - stored_policy_creation_input, ) from policyengine_api.services.v2.policies.validators import validate_policy_catalog @@ -97,9 +98,11 @@ def resolve_dynamic_creation_input( ) -> ResolvedDynamicCreationInput: """Bind dynamic content to the selected catalog's model version. - Raise PolicyCatalogValidationError if the model or any parameter id is not - part of the selected catalog, and DynamicSetsPolicyParametersError if any - parameter is not one of the model's assumptions. + Its parameter IDs name the version's dynamic parameters. Raise + PolicyCatalogValidationError if the model or any parameter id is in + neither of the version's parameter tables, and + DynamicSetsPolicyParametersError, naming them, if any is one of its policy + parameters. """ selected = read_policy_catalog( session, @@ -107,17 +110,23 @@ def resolve_dynamic_creation_input( policyengine_version=policyengine_version, running_policyengine_version=running_policyengine_version, ) - parameter_names = read_version_parameter_names( + requested_ids = {value.parameter_id for value in dynamic_input.parameter_values} + dynamic_parameter_names = read_version_dynamic_parameter_names( session, model_version_id=selected.model_version.id, - requested_ids={value.parameter_id for value in dynamic_input.parameter_values}, + requested_ids=requested_ids, + ) + policy_parameter_names = read_version_parameter_names( + session, + model_version_id=selected.model_version.id, + requested_ids=requested_ids - set(dynamic_parameter_names), ) resolved = validate_policy_catalog( dynamic_input, selected=selected, - resolved_parameter_ids=set(parameter_names), + resolved_parameter_ids={*dynamic_parameter_names, *policy_parameter_names}, ) - require_dynamic_parameters(dynamic_input.country_id, parameter_names.values()) + require_dynamic_parameters(policy_parameter_names.values()) return dynamic_creation_input(resolved) @@ -160,7 +169,7 @@ def create_resolved_dynamic( if model_version is None: msg = "stored dynamic references an absent model version" raise DynamicCreationIntegrityError(msg) - stored_input = stored_policy_creation_input( + stored_input = stored_dynamic_creation_input( existing, model_version, read_dynamic_parameter_values(session, existing.id), @@ -212,7 +221,7 @@ def with_missing_dynamic_parameters( if dynamic.tax_benefit_model_version_id == running_model_version_id else {value.parameter_name for value in dynamic.parameter_values} ) - running_parameters = read_parameters_by_name( + running_parameters = read_dynamic_parameters_by_name( session, model_version_id=running_model_version_id, names=names_to_check ) return checked_dynamic_read( diff --git a/policyengine_api/services/v2/dynamics/transformations.py b/policyengine_api/services/v2/dynamics/transformations.py index 11aa3f42a..1783873a2 100644 --- a/policyengine_api/services/v2/dynamics/transformations.py +++ b/policyengine_api/services/v2/dynamics/transformations.py @@ -15,14 +15,18 @@ DynamicRead, ResolvedDynamicCreationInput, ) -from policyengine_api.services.v2.policies.types import PolicyParameterValueRead +from policyengine_api.services.v2.policies.types import ( + PolicyParameterValueRead, + ResolvedPolicyCreationInput, +) if TYPE_CHECKING: from uuid import UUID - from policyengine_api.data.v2.models import Dynamic, ParameterValue - from policyengine_api.services.v2.policies.types import ( - ResolvedPolicyCreationInput, + from policyengine_api.data.v2.models import ( + Dynamic, + DynamicParameterValue, + TaxBenefitModelVersion, ) @@ -33,9 +37,38 @@ def dynamic_creation_input( return ResolvedDynamicCreationInput.model_validate(dict(content)) +def stored_dynamic_creation_input( + dynamic: Dynamic, + model_version: TaxBenefitModelVersion, + values: list[DynamicParameterValue], +) -> ResolvedPolicyCreationInput: + """Rebuild a stored dynamic's input to compare its canonical bytes. + + A value's ``dynamic_parameter_id`` is the ``parameter_id`` the dynamic was + created with: the revision that moved stored dynamics kept their IDs. + """ + return ResolvedPolicyCreationInput.model_validate( + { + "country_id": dynamic.country_id, + "tax_benefit_model_id": dynamic.tax_benefit_model_id, + "tax_benefit_model_version_id": dynamic.tax_benefit_model_version_id, + "policyengine_version": model_version.version, + "parameter_values": [ + { + "parameter_id": value.dynamic_parameter_id, + "value": value.value_json, + "start_date": value.start_date, + "end_date": value.end_date, + } + for value in values + ], + } + ) + + def dynamic_parameter_values_by_dynamic( dynamic_ids: list[UUID], - rows: list[tuple[ParameterValue, str]], + rows: list[tuple[DynamicParameterValue, str]], ) -> dict[UUID, tuple[PolicyParameterValueRead, ...]]: """Group named value rows by dynamic id; every requested dynamic gets an entry.""" grouped: dict[UUID, list[PolicyParameterValueRead]] = { @@ -47,7 +80,7 @@ def dynamic_parameter_values_by_dynamic( grouped[value.dynamic_id].append( PolicyParameterValueRead( id=value.id, - parameter_id=value.parameter_id, + parameter_id=value.dynamic_parameter_id, parameter_name=parameter_name, value=value.value_json, start_date=value.start_date, diff --git a/policyengine_api/services/v2/dynamics/validators.py b/policyengine_api/services/v2/dynamics/validators.py index 66c78f37f..8284100c7 100644 --- a/policyengine_api/services/v2/dynamics/validators.py +++ b/policyengine_api/services/v2/dynamics/validators.py @@ -4,7 +4,6 @@ from typing import TYPE_CHECKING -from policyengine_api.dynamic_parameters import is_dynamic_parameter from policyengine_api.services.v2.policies.validators import ( PolicyParametersMissingError, ) @@ -13,8 +12,6 @@ from collections.abc import Iterable from uuid import UUID - from policyengine_api.supported_countries import SupportedCountryId - class DynamicNotFoundError(LookupError): """Raised when a dynamic UUID is absent from the selected country.""" @@ -77,21 +74,15 @@ def __str__(self) -> str: ) -def require_dynamic_parameters( - country_id: SupportedCountryId, parameter_names: Iterable[str] -) -> None: - """Raise DynamicSetsPolicyParametersError unless each parameter is an assumption.""" - policy_parameter_names = tuple( - sorted( - { - name - for name in parameter_names - if not is_dynamic_parameter(country_id, name) - } - ) - ) - if policy_parameter_names: - raise DynamicSetsPolicyParametersError(policy_parameter_names) +def require_dynamic_parameters(policy_parameter_names: Iterable[str]) -> None: + """Raise DynamicSetsPolicyParametersError when the dynamic sets policy parameters. + + ``policy_parameter_names`` names the requested parameters found among the + catalog version's policy parameters rather than its dynamic parameters. + """ + names = tuple(sorted(set(policy_parameter_names))) + if names: + raise DynamicSetsPolicyParametersError(names) def require_dynamic_parameters_present( diff --git a/policyengine_api/services/v2/policies/services.py b/policyengine_api/services/v2/policies/services.py index bbe61a8c3..92d16c56a 100644 --- a/policyengine_api/services/v2/policies/services.py +++ b/policyengine_api/services/v2/policies/services.py @@ -8,6 +8,10 @@ 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, + read_version_dynamic_parameter_names, +) from policyengine_api.services.v2.dynamics.transformations import ( dynamic_creation_input, ) @@ -71,6 +75,7 @@ from sqlmodel import Session + from policyengine_api.data.v2.models import DynamicParameter, Parameter from policyengine_api.services.v2.policies.database_session import ( PolicyDatabaseSession, ) @@ -85,9 +90,11 @@ def resolve_policy_creation_input( ) -> ResolvedPolicyCreationInput: """Bind policy content to the selected catalog's model version. - Raise PolicyCatalogValidationError if the model or any parameter id is not - part of the selected catalog, and PolicySetsDynamicParametersError if any - parameter is one only a dynamic may hold. + Its parameter IDs name the version's policy parameters. Raise + PolicyCatalogValidationError if the model or any parameter id is in + neither of the version's parameter tables, and + PolicySetsDynamicParametersError, naming them, if any is one of its + dynamic parameters, which only a dynamic may hold. """ selected = read_policy_catalog( session, @@ -103,12 +110,17 @@ def resolve_policy_creation_input( model_version_id=selected.model_version.id, requested_ids=requested_parameter_ids, ) + dynamic_parameter_names = read_version_dynamic_parameter_names( + session, + model_version_id=selected.model_version.id, + requested_ids=requested_parameter_ids - set(parameter_names), + ) resolved = validate_policy_catalog( policy_input, selected=selected, - resolved_parameter_ids=set(parameter_names), + resolved_parameter_ids={*parameter_names, *dynamic_parameter_names}, ) - refuse_dynamic_parameters(policy_input.country_id, parameter_names.values()) + refuse_dynamic_parameters(dynamic_parameter_names.values()) return resolved @@ -296,11 +308,20 @@ def mirror_legacy_policy_in_session( running_policyengine_version=running_policyengine_version, ) split = split_legacy_policy(snapshot) - parameters = read_parameters_by_name( - session, - model_version_id=selected.model_version.id, - names={*split.policy_values, *split.dynamic_values}, - ) + # Each part's names are looked up in its own table (C1 · 50): the policy's + # among policy parameters, the model assumptions among dynamic parameters. + 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), + ), + } translation = translate_legacy_policy( snapshot, selected=selected, diff --git a/policyengine_api/services/v2/policies/transformations.py b/policyengine_api/services/v2/policies/transformations.py index e40d87d2e..83ae02951 100644 --- a/policyengine_api/services/v2/policies/transformations.py +++ b/policyengine_api/services/v2/policies/transformations.py @@ -46,7 +46,7 @@ SelectedCatalog, ) from policyengine_api.data.v2.models import ( - Dynamic, + DynamicParameter, Parameter, ParameterValue, Policy, @@ -147,11 +147,14 @@ def canonicalize_policy( def stored_policy_creation_input( - policy: Policy | Dynamic, + policy: Policy, model_version: TaxBenefitModelVersion, values: list[ParameterValue], ) -> ResolvedPolicyCreationInput: - """Rebuild a stored policy's or dynamic's input to compare its canonical bytes.""" + """Rebuild a stored policy's input to compare its canonical bytes. + + A dynamic's is ``dynamics.transformations.stored_dynamic_creation_input``. + """ return ResolvedPolicyCreationInput.model_validate( { "country_id": policy.country_id, @@ -330,7 +333,7 @@ def _translate_legacy_values( values_by_name: Mapping[str, object], *, selected: SelectedCatalog, - parameters: Mapping[str, Parameter], + parameters: Mapping[str, Parameter | DynamicParameter], ) -> ResolvedPolicyCreationInput: """Translate one part of a v1 policy's values into content bound to the catalog. @@ -397,7 +400,7 @@ def translate_legacy_policy( snapshot: LegacyPolicySnapshot, *, selected: SelectedCatalog, - parameters: Mapping[str, Parameter], + parameters: Mapping[str, Parameter | DynamicParameter], ) -> LegacyPolicyTranslation: """Translate a v1 policy into a policy and a dynamic bound to the running catalog. @@ -411,9 +414,11 @@ def translate_legacy_policy( binds it to the running catalog the same way. ``parameters`` holds the running catalog's parameters with the split's - parameter names, keyed by name. Raise LegacyPolicyTranslationError, with a - fixed reason, if the v1 policy sets a parameter the catalog lacks, sets no - value for a parameter, or has invalid or conflicting periods or spellings. + parameter names, keyed by name: its policy parameters for the policy's + values and its dynamic parameters for the model assumptions. Raise + LegacyPolicyTranslationError, with a fixed reason, if the v1 policy sets a + parameter the catalog lacks, sets no value for a parameter, or has invalid + or conflicting periods or spellings. """ split = split_legacy_policy(snapshot) if parameters_missing_from_model( diff --git a/policyengine_api/services/v2/policies/validators.py b/policyengine_api/services/v2/policies/validators.py index 03ff1d6e4..ca53e859f 100644 --- a/policyengine_api/services/v2/policies/validators.py +++ b/policyengine_api/services/v2/policies/validators.py @@ -6,8 +6,6 @@ from datetime import UTC, datetime from typing import TYPE_CHECKING, Any -from policyengine_api.dynamic_parameters import is_dynamic_parameter - if TYPE_CHECKING: from collections.abc import Container, Iterable from uuid import UUID @@ -21,7 +19,6 @@ PolicyCreationInput, ResolvedPolicyCreationInput, ) - from policyengine_api.supported_countries import SupportedCountryId MAXIMUM_POLICY_PARAMETER_VALUES = 1_000 @@ -86,17 +83,15 @@ def __str__(self) -> str: ) -def refuse_dynamic_parameters( - country_id: SupportedCountryId, parameter_names: Iterable[str] -) -> None: - """Raise PolicySetsDynamicParametersError if any parameter belongs in a dynamic.""" - dynamic_parameter_names = tuple( - sorted( - {name for name in parameter_names if is_dynamic_parameter(country_id, name)} - ) - ) - if dynamic_parameter_names: - raise PolicySetsDynamicParametersError(dynamic_parameter_names) +def refuse_dynamic_parameters(dynamic_parameter_names: Iterable[str]) -> None: + """Raise PolicySetsDynamicParametersError when the policy sets model assumptions. + + ``dynamic_parameter_names`` names the requested parameters found among the + catalog version's dynamic parameters rather than its policy parameters. + """ + names = tuple(sorted(set(dynamic_parameter_names))) + if names: + raise PolicySetsDynamicParametersError(names) class PolicyParametersMissingError(ValueError): diff --git a/scripts/qualify_v2_dynamic_parameter_move.py b/scripts/qualify_v2_dynamic_parameter_move.py new file mode 100755 index 000000000..b2f7bf9a9 --- /dev/null +++ b/scripts/qualify_v2_dynamic_parameter_move.py @@ -0,0 +1,7 @@ +#!/usr/bin/env python3 +"""Check that no policy value names a dynamic parameter before revision 7f7335f0eb31.""" + +from policyengine_api.data.v2.dynamic_parameter_move_qualification import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/integration/test_alembic_v2_dynamic_parameter_tables.py b/tests/integration/test_alembic_v2_dynamic_parameter_tables.py index a97d1cec4..b3e8a6389 100644 --- a/tests/integration/test_alembic_v2_dynamic_parameter_tables.py +++ b/tests/integration/test_alembic_v2_dynamic_parameter_tables.py @@ -24,13 +24,13 @@ import pytest from alembic import command +from sqlalchemy import delete, select, update +from sqlmodel import col + from policyengine_api.data.v2.dynamic_parameter_move_qualification import ( count_policy_values_naming_dynamic_parameters, dynamic_parameter_move_is_pending, ) -from sqlalchemy import delete, select, update -from sqlmodel import col - from policyengine_api.data.v2.models import ( Dynamic, DynamicParameter, @@ -533,6 +533,19 @@ def _tree_counts(snapshot: CatalogSnapshot, version_id: UUID) -> dict: return {row[3]: (row[7], row[9]) for row in snapshot.tree if row[1] == version_id} +def _column_shapes(inspector: Any, table: str) -> list[tuple]: + """Return a table's columns as comparable tuples: name, type, null, default.""" + return [ + ( + column["name"], + str(column["type"]), + column["nullable"], + column["default"], + ) + for column in inspector.get_columns(table) + ] + + def test_the_revision_adds_only_the_two_tables( sessions: sessionmaker[Session], ) -> None: @@ -541,7 +554,7 @@ def test_the_revision_adds_only_the_two_tables( with sessions() as session: inspector = schema_inspector(session) before = { - table: (inspector.get_columns(table), inspector.get_indexes(table)) + table: (_column_shapes(inspector, table), inspector.get_indexes(table)) for table in inspector.get_table_names() } command.upgrade(config, DYNAMIC_PARAMETER_TABLES_REVISION) @@ -550,7 +563,7 @@ def test_the_revision_adds_only_the_two_tables( tables = set(inspector.get_table_names()) assert tables - set(before) == NEW_TABLES for table, (columns, indexes) in before.items(): - assert inspector.get_columns(table) == columns, table + assert _column_shapes(inspector, table) == columns, table assert inspector.get_indexes(table) == indexes, table parameter_columns = { column["name"]: (str(column["type"]), column["nullable"]) diff --git a/tests/unit/v2/test_dynamic_catalog.py b/tests/unit/v2/test_dynamic_catalog.py index fdab57462..21c094b7b 100644 --- a/tests/unit/v2/test_dynamic_catalog.py +++ b/tests/unit/v2/test_dynamic_catalog.py @@ -456,22 +456,6 @@ def test_a_created_dynamic_keeps_its_values_in_their_own_table( assert read.missing_parameters == () -def test_identical_dynamic_content_is_found_from_its_stored_values( - sessions: sessionmaker[Session], catalog: Catalog -) -> None: - content = NativeDynamicCreationInput( - **_dynamic_input(catalog, INCOME_ELASTICITY).model_dump() - ) - first = _service(sessions).create_dynamic(content) - - again = _service(sessions).create_dynamic(content) - - assert not again.created - assert again.item.id == first.item.id - with sessions() as session: - assert len(session.exec(select(DynamicParameterValue)).all()) == 1 - - def test_a_dynamic_lists_the_assumptions_the_running_catalog_lacks( sessions: sessionmaker[Session], session: Session, catalog: Catalog ) -> None: diff --git a/tests/unit/v2/test_simulation_submission_database_routes.py b/tests/unit/v2/test_simulation_submission_database_routes.py index f6ba5f624..3ad767a9f 100644 --- a/tests/unit/v2/test_simulation_submission_database_routes.py +++ b/tests/unit/v2/test_simulation_submission_database_routes.py @@ -17,12 +17,15 @@ from policyengine_api.data.v2.models import ( Country, Dynamic, + DynamicParameter, + DynamicParameterValue, Parameter, ParameterValue, Policy, TaxBenefitModel, TaxBenefitModelVersion, ) +from policyengine_api.dynamic_parameters import is_dynamic_parameter from policyengine_api.services.v2.countries.database_session import ( CountryDatabaseSession, ) @@ -108,13 +111,20 @@ def sessions() -> Iterator[sessionmaker[Session]]: def store_catalog_version( session: Session, model: TaxBenefitModel, version: str, names: list[str] -) -> dict[str, Parameter]: - """Store a catalog version of ``model`` with these parameters, keyed by name.""" +) -> dict[str, Any]: + """Store a catalog version of ``model`` with these parameters, keyed by name. + + Model assumptions are ``dynamic_parameters`` rows and the others + ``parameters`` rows, as catalog publication stores them (C1 · 50). + """ model_version = TaxBenefitModelVersion( model=model, version=version, current_law_id=1, metadata_time_periods=[2026] ) + country_id = "uk" if model.name == "policyengine-uk" else "us" parameters = { - name: Parameter(name=name, tax_benefit_model_version=model_version) + name: ( + DynamicParameter if is_dynamic_parameter(country_id, name) else Parameter + )(name=name, tax_benefit_model_version=model_version) for name in names } session.add(model_version) @@ -183,7 +193,7 @@ def stored_policy_ids(sessions: sessionmaker[Session]) -> dict[str, UUID]: def store_dynamic( session: Session, country_id: str, - parameters: dict[str, Parameter], + parameters: dict[str, DynamicParameter], content_hash_letter: str, ) -> Dynamic: """Store a dynamic setting each of ``parameters``, of their catalog version.""" @@ -200,8 +210,8 @@ def store_dynamic( session.add(dynamic) session.flush() session.add_all( - ParameterValue( - parameter_id=parameter.id, + DynamicParameterValue( + dynamic_parameter_id=parameter.id, value_json=0.25, start_date=STORED_AT, dynamic_id=dynamic.id, From b8c886de80cd5619688da08b2d0f3fda65d15e7e Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:14:07 +0400 Subject: [PATCH 04/10] =?UTF-8?q?C1=20=C2=B7=2050:=20tests=20for=20review?= =?UTF-8?q?=20round=201's=20findings=20(failing)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The read-only check before revision 7f7335f0eb31 counts no value on a target without the catalog tables, as the other check steps do, so a new or reset database can still be upgraded and seeded. - The catalog writer holds no UPDATE on dynamic_parameters: publication only inserts it. - The revision tests' fixture deletes its rows before upgrading back to the head, so a failed refusal test leaves neither rows nor a downgraded database; the tree test that could not fail is removed. Co-Authored-By: Claude Opus 5.5 --- ...est_alembic_v2_dynamic_parameter_tables.py | 32 ++++------------- tests/integration/test_v2_metadata_routes.py | 6 ++-- ...st_dynamic_parameter_move_qualification.py | 36 +++++++++++++++++++ tests/unit/v2/test_metadata_service.py | 7 ++-- tests/unit/v2/test_privilege_manifest.py | 14 ++++---- 5 files changed, 58 insertions(+), 37 deletions(-) diff --git a/tests/integration/test_alembic_v2_dynamic_parameter_tables.py b/tests/integration/test_alembic_v2_dynamic_parameter_tables.py index b3e8a6389..fd64ca69d 100644 --- a/tests/integration/test_alembic_v2_dynamic_parameter_tables.py +++ b/tests/integration/test_alembic_v2_dynamic_parameter_tables.py @@ -24,7 +24,7 @@ import pytest from alembic import command -from sqlalchemy import delete, select, update +from sqlalchemy import delete, select from sqlmodel import col from policyengine_api.data.v2.dynamic_parameter_move_qualification import ( @@ -377,8 +377,12 @@ def stored_countries( ) yield countries finally: - command.upgrade(alembic_v2_config(), "head") - _remove(sessions, countries) + # Remove the rows first: a failed refusal test may have left a policy + # value that would refuse the upgrade back to the head. + try: + _remove(sessions, countries) + finally: + command.upgrade(alembic_v2_config(), "head") def _version_ids(countries: list[StoredCountry]) -> list[UUID]: @@ -891,28 +895,6 @@ def test_a_dynamic_s_values_go_with_it_and_a_parameter_s_with_the_parameter( us.dynamic_id = None -def test_tree_counts_lower_only_for_kept_parents( - sessions: sessionmaker[Session], stored_countries: list[StoredCountry] -) -> None: - """A parent row the revision deletes itself has nothing to lower.""" - with sessions.begin() as session: - session.execute( - update(ParameterTreeChild) - .where( - col(ParameterTreeChild.tax_benefit_model_version_id) - == stored_countries[0].version_id, - col(ParameterTreeChild.path) == "gov.simulation", - ) - .values(child_count=7) - ) - command.upgrade(alembic_v2_config(), DYNAMIC_PARAMETER_TABLES_REVISION) - moved = _snapshot(sessions, stored_countries) - assert ( - _tree_counts(moved, stored_countries[0].version_id) - == (TREES_AFTER_THE_MOVE["us"]) - ) - - def test_the_seed_workflow_s_check_counts_what_the_revision_refuses( sessions: sessionmaker[Session], stored_countries: list[StoredCountry] ) -> None: diff --git a/tests/integration/test_v2_metadata_routes.py b/tests/integration/test_v2_metadata_routes.py index 4dcec4c9d..2424bb04e 100644 --- a/tests/integration/test_v2_metadata_routes.py +++ b/tests/integration/test_v2_metadata_routes.py @@ -1069,9 +1069,9 @@ def test_postgres_search_file_of_a_version_without_one_is_unavailable( "status": "error", "message": ( f"catalog version {POLICYENGINE_VERSION} has no parameter search " - "file: only catalog format 2 versions that catalog publication has " - "published, or run with installed, since search files were added have " - "one" + "file of the current format: only catalog format 2 versions that " + "catalog publication has published, or run with installed, since that " + "format was added have one" ), } diff --git a/tests/unit/v2/test_dynamic_parameter_move_qualification.py b/tests/unit/v2/test_dynamic_parameter_move_qualification.py index 08d7708f6..8a8c182cb 100644 --- a/tests/unit/v2/test_dynamic_parameter_move_qualification.py +++ b/tests/unit/v2/test_dynamic_parameter_move_qualification.py @@ -22,6 +22,7 @@ from tests.unit.v2.qualification_sessions import ( CountingSession, QualificationSessions, + serve_public_tables, serve_read_only_sessions, ) @@ -35,6 +36,11 @@ } +@pytest.fixture(autouse=True) +def _every_table_exists(monkeypatch: pytest.MonkeyPatch) -> None: + serve_public_tables(monkeypatch) + + def test_the_check_belongs_to_the_dynamic_parameter_tables_revision() -> None: assert move.DYNAMIC_PARAMETER_TABLES_REVISION == "7f7335f0eb31" @@ -125,3 +131,33 @@ def fail() -> None: assert "qualification failed unexpectedly" in captured.err assert "secret" not in captured.err assert "private-host" not in captured.err + + +@pytest.mark.parametrize( + "public_tables", + [(), ("parameters", "tax_benefit_models", "tax_benefit_model_versions")], +) +def test_a_target_without_the_catalog_tables_counts_no_value( + monkeypatch: pytest.MonkeyPatch, public_tables: tuple[str, ...] +) -> None: + """An empty or partial target, whose revisions are all pending, is qualified. + + As the other check steps do, a missing table counts as holding no row, so + a new database can be upgraded and seeded. + """ + serve_public_tables(monkeypatch, public_tables) + session = CountingSession(()) + sessions = QualificationSessions(session) + + evidence = move.qualify_dynamic_parameter_move_if_pending( + ENVIRONMENT, + session_factories=sessions, + pending_checker=lambda _session: True, + ) + + assert evidence.as_dict()["qualification"] == "performed" + assert evidence.as_dict()["counts"] == { + "policy_values_naming_dynamic_parameters": 0 + } + assert session.statements == [] + assert session.rolled_back diff --git a/tests/unit/v2/test_metadata_service.py b/tests/unit/v2/test_metadata_service.py index 5f4779a70..831936739 100644 --- a/tests/unit/v2/test_metadata_service.py +++ b/tests/unit/v2/test_metadata_service.py @@ -704,7 +704,8 @@ def test_a_version_without_a_search_file_of_the_current_format_is_unavailable( assert str(raised_for_hash.value) == str(raised.value) assert str(raised.value) == ( - f"catalog version {POLICYENGINE_VERSION} has no parameter search file: " - "only catalog format 2 versions that catalog publication has published, " - "or run with installed, since search files were added have one" + f"catalog version {POLICYENGINE_VERSION} has no parameter search file of " + "the current format: only catalog format 2 versions that catalog " + "publication has published, or run with installed, since that format " + "was added have one" ) diff --git a/tests/unit/v2/test_privilege_manifest.py b/tests/unit/v2/test_privilege_manifest.py index f40112f51..6749cf762 100644 --- a/tests/unit/v2/test_privilege_manifest.py +++ b/tests/unit/v2/test_privilege_manifest.py @@ -551,8 +551,9 @@ def test_api_v1_creates_and_reads_dynamics_but_never_changes_them() -> None: def test_dynamic_parameters_are_granted_as_policy_parameters_are() -> None: """The two dynamic parameter tables take the policy parameter tables' grants. - Catalog publication writes and analyzes both, and catalog pruning deletes - current-law values from the values table. API v1 reads both and inserts a + Catalog publication inserts and analyzes both, and catalog pruning deletes + current-law values from the values table; nothing updates either. API v1 + reads both and inserts a dynamic's values, which a run of the simulation service and its Modal workers reads. Comparison runs never read them. """ @@ -573,10 +574,11 @@ def test_dynamic_parameters_are_granted_as_policy_parameters_are() -> None: dynamic_table, ) assert declared[RUNTIME_ROLE]["dynamic_parameter_values"] == READ_INSERT - assert ( - declared[CATALOG_WRITER_ROLE]["dynamic_parameters"] - == (declared[CATALOG_WRITER_ROLE]["parameters"]) - ) + # Publication only inserts both tables' rows, and pruning deletes only + # current-law values: nothing updates either. + assert declared[CATALOG_WRITER_ROLE]["dynamic_parameters"] == READ_INSERT | { + TablePrivilege.MAINTAIN + } def test_api_v1_saves_users_dynamics_as_it_saves_their_policies() -> None: From aca49e3872eb3f21cd28d1ebb2b79fa143f99c3f Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:21:28 +0400 Subject: [PATCH 05/10] =?UTF-8?q?C1=20=C2=B7=2050:=20fix=20review=20round?= =?UTF-8?q?=201's=20findings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The read-only check before revision 7f7335f0eb31 counts nothing on a database lacking any of the catalog tables it reads, as the other check steps do, so a new or reset database can still be upgraded and seeded. - The catalog writer has no UPDATE on dynamic_parameters, which publication only inserts. - The search file's 503 message and its route description say that only versions published since the current format have a file; the migration guide and the stage 9 runbook say that older kept versions get one only when a release installs them again; mirror_legacy_policy_in_session's docstring no longer says a stored copy keeps its assumptions. Co-Authored-By: Claude Opus 5.5 --- docs/engineering/skills/alembic-migrations.md | 10 +++++---- docs/migration/stage-9-v2-metadata.md | 6 ++++-- .../dynamic_parameter_move_qualification.py | 21 ++++++++++++++++++- policyengine_api/data/v2/privileges.py | 5 +++-- .../v2/metadata/route_support.py | 8 +++---- .../services/v2/metadata/validators.py | 5 +++-- .../services/v2/policies/services.py | 6 ++++-- 7 files changed, 44 insertions(+), 17 deletions(-) diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 2278bef46..ad4a529bc 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -1645,8 +1645,10 @@ upgrade. Publication then writes, compares, restores and prunes both tables (`policyengine_api/data/v2/catalog/dynamic_parameter_records.py`), builds the policy tree without dynamic parameters and their folders, and writes the search file in format 2, which lists none of them; versions stored before keep -their format 1 files, which the previous release serves, and answer 503 from -`/v2/parameters/search-file` until a publication writes their format 2 file. +their format 1 files, which the previous release serves. Publication writes a +format 2 file only for the version it installs, so an older stored version +answers 503 from `/v2/parameters/search-file` until a release installs it +again (after it has been pruned, publishing it restores its file too). **The downgrade** copies both tables back into `parameters` and `parameter_values` (with a null `policy_id`), with their IDs, versions @@ -1697,8 +1699,8 @@ and its `allowList.ts` forwards neither `/v2/dynamics` nor `/v2/user-dynamics`. The runtime role reads both tables and inserts dynamics' values; the catalog -writer inserts both, updates `dynamic_parameters`, deletes only current-law -values (pruning) and analyzes both (`MAINTAIN`); the simulation service and +writer inserts both, deletes only current-law values (pruning) and analyzes +both (`MAINTAIN`), and updates neither; the simulation service and its Modal workers read both, which C1 · 52 needs; comparison runs have no access. `parameter_values.dynamic_id`, its single-owner check and its partial unique index stay until C1 · 53, because older simulation service releases diff --git a/docs/migration/stage-9-v2-metadata.md b/docs/migration/stage-9-v2-metadata.md index f0087cbb5..9a3c57726 100644 --- a/docs/migration/stage-9-v2-metadata.md +++ b/docs/migration/stage-9-v2-metadata.md @@ -487,8 +487,10 @@ publishes into `parameter_search_files`: one gzip-compressed JSON file per version and file format, with the SHA-256 of the uncompressed JSON. The current format is 2 (C1 · 50), which leaves model assumptions and their folders out of every list, as the tree does; format 1 listed them. Versions stored before -keep their format 1 files, which the previous release serves, and have no -format 2 file until a publication of the version writes one. The file holds +keep their format 1 files, which the previous release serves. Publication +writes a format 2 file only for the version it installs, so an older stored +version has none, and the route answers 503 for it, until a release installs +it again. The file holds what the app's newer interface's parameter search reads: - every parameter a reform can change (the parameter tree's rule) with its diff --git a/policyengine_api/data/v2/dynamic_parameter_move_qualification.py b/policyengine_api/data/v2/dynamic_parameter_move_qualification.py index d2e81bac9..e1f0e0123 100644 --- a/policyengine_api/data/v2/dynamic_parameter_move_qualification.py +++ b/policyengine_api/data/v2/dynamic_parameter_move_qualification.py @@ -11,6 +11,8 @@ A parameter is a model assumption of its country, the country of its catalog version's model ``policyengine-``, as the revision decides. +As in the other check steps, a missing table holds no row: on a new or reset +database every revision is pending and none of the tables exists yet. """ from __future__ import annotations @@ -46,6 +48,15 @@ from sqlmodel import Session DYNAMIC_PARAMETER_TABLES_REVISION = "7f7335f0eb31" +# The tables the count reads; it counts nothing unless all of them exist. +COUNTED_TABLES = frozenset( + { + "parameter_values", + "parameters", + "tax_benefit_model_versions", + "tax_benefit_models", + } +) @dataclass(frozen=True) @@ -117,7 +128,15 @@ def _names_a_dynamic_parameter() -> ColumnElement[bool]: def count_policy_values_naming_dynamic_parameters(session: Session) -> int: - """Count the policy values whose parameter the revision would move.""" + """Count the policy values whose parameter the revision would move. + + Return 0 without a statement on a database lacking any of the tables. + """ + from policyengine_api.data.v2.database import v2_schema_inspector + + existing_tables = set(v2_schema_inspector(session).get_table_names(schema="public")) + if not existing_tables.issuperset(COUNTED_TABLES): + return 0 count = session.scalar( select(func.count()) .select_from(ParameterValue) diff --git a/policyengine_api/data/v2/privileges.py b/policyengine_api/data/v2/privileges.py index 85cc272cd..5dc02fbbc 100644 --- a/policyengine_api/data/v2/privileges.py +++ b/policyengine_api/data/v2/privileges.py @@ -315,9 +315,10 @@ def _run_table( runtime=READ, catalog_writer=READ_INSERT_UPDATE | _ANALYZE, **_RUN_INPUT_READS ), # Model assumptions, apart from the policy parameters since C1 · 50, granted - # as those are: publication writes them, and a run reads a dynamic's. + # as those are, but publication only inserts them, and a run reads a + # dynamic's. "dynamic_parameters": _access( - runtime=READ, catalog_writer=READ_INSERT_UPDATE | _ANALYZE, **_RUN_INPUT_READS + runtime=READ, catalog_writer=READ_INSERT | _ANALYZE, **_RUN_INPUT_READS ), # Their current-law values, which catalog pruning deletes from an older # version, and every dynamic's values, which API v1 inserts with its diff --git a/policyengine_api/fastapi_routes/v2/metadata/route_support.py b/policyengine_api/fastapi_routes/v2/metadata/route_support.py index 3efeecf20..5b67d181a 100644 --- a/policyengine_api/fastapi_routes/v2/metadata/route_support.py +++ b/policyengine_api/fastapi_routes/v2/metadata/route_support.py @@ -124,10 +124,10 @@ "model": V2ErrorResponse, "description": ( "The initialized v2 catalog is unavailable, or the catalog version " - "has no parameter search file: only catalog format 2 versions that " - "publication has published, or run with installed, since search files " - "were added have one. The message then names the version." - + PRUNED_RUNNING_VERSION_DESCRIPTION + "has no parameter search file of the current format: only catalog " + "format 2 versions that publication has published, or run with " + "installed, since that format was added have one. The message then " + "names the version." + PRUNED_RUNNING_VERSION_DESCRIPTION ), }, } diff --git a/policyengine_api/services/v2/metadata/validators.py b/policyengine_api/services/v2/metadata/validators.py index d7d3051f2..d21f7f648 100644 --- a/policyengine_api/services/v2/metadata/validators.py +++ b/policyengine_api/services/v2/metadata/validators.py @@ -89,8 +89,9 @@ def parameter_search_file_unavailable_error( """Return the error for a selected version that has no parameter search file.""" msg = ( f"catalog version {selected.policyengine_version} has no parameter search " - "file: only catalog format 2 versions that catalog publication has " - "published, or run with installed, since search files were added have one" + "file of the current format: only catalog format 2 versions that catalog " + "publication has published, or run with installed, since that format " + "was added have one" ) return ParameterSearchFileUnavailableError(msg) diff --git a/policyengine_api/services/v2/policies/services.py b/policyengine_api/services/v2/policies/services.py index 92d16c56a..eae8ab755 100644 --- a/policyengine_api/services/v2/policies/services.py +++ b/policyengine_api/services/v2/policies/services.py @@ -274,8 +274,10 @@ def mirror_legacy_policy_in_session( mapping names both. A v1 policy that sets no assumptions maps to no dynamic. A v1 policy that already has a v2 copy returns that copy without being translated again, so writing it again after a PolicyEngine.py or - country package upgrade still succeeds; a copy made before the split - existed keeps its assumptions in its policy and maps to no dynamic. Raise + country package upgrade still succeeds. A copy made before the split + existed maps to no dynamic; operator step C1 · 49 moved its assumptions + into a dynamic before revision 7f7335f0eb31, after which no policy can + hold one. Raise LegacyPolicyMappingIntegrityError if the v1 id is already mapped with a different source hash. """ From 02711604aba003968b052bc7c5b912506759a89f Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:44:46 +0400 Subject: [PATCH 06/10] =?UTF-8?q?C1=20=C2=B7=2050:=20tests=20for=20review?= =?UTF-8?q?=20round=202's=20findings=20(failing)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The revision refuses while a dynamic's value names a parameter it doesn't move, which the new tables couldn't hold (failing). - A policy value written while the upgrade waits for its lock is counted and refused: without the lock the upgrade would delete it with its parameter. - The seed workflow's check counts no policy value on another country's look-alike prefix. - A version stored before catalog format 2 compares its dynamic parameters without format 2's fields; clear_format_2_fields clears their flags too. - The copy test named for parameters of the same name says what it checks. Co-Authored-By: Claude Opus 5.5 --- .../catalog_publication_support.py | 6 +- ...est_alembic_v2_dynamic_parameter_tables.py | 86 +++++++++++++++++++ ..._catalog_publication_dynamic_parameters.py | 49 ++++++++++- tests/unit/v2/test_policy_legacy_copy.py | 2 +- 4 files changed, 139 insertions(+), 4 deletions(-) diff --git a/tests/integration/catalog_publication_support.py b/tests/integration/catalog_publication_support.py index f9a534e5e..6b92cd590 100644 --- a/tests/integration/catalog_publication_support.py +++ b/tests/integration/catalog_publication_support.py @@ -21,6 +21,7 @@ from policyengine_api.data.v2.models import ( Dataset, + DynamicParameter, Parameter, ParameterNode, ParameterValue, @@ -117,8 +118,8 @@ def clear_version_format_2_fields(*conditions: ColumnElement[bool]) -> Update: def clear_format_2_fields(session: Session) -> None: """Make every stored version look as if published before catalog format 2. - Clears the versions' format 2 fields, and those of their variables and - parameters, in the Session's transaction. + Clears the versions' format 2 fields, and those of their variables, + parameters and dynamic parameters, in the Session's transaction. """ session.execute(clear_version_format_2_fields()) session.execute( @@ -134,3 +135,4 @@ def clear_format_2_fields(session: Session) -> None: ) ) session.execute(update(Parameter).values(economy=None, household=None)) + session.execute(update(DynamicParameter).values(economy=None, household=None)) diff --git a/tests/integration/test_alembic_v2_dynamic_parameter_tables.py b/tests/integration/test_alembic_v2_dynamic_parameter_tables.py index fd64ca69d..807495ab1 100644 --- a/tests/integration/test_alembic_v2_dynamic_parameter_tables.py +++ b/tests/integration/test_alembic_v2_dynamic_parameter_tables.py @@ -17,6 +17,8 @@ from __future__ import annotations +import threading +from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass, field from datetime import UTC, datetime from typing import TYPE_CHECKING, Any @@ -907,6 +909,14 @@ def test_the_seed_workflow_s_check_counts_what_the_revision_refuses( assert dynamic_parameter_move_is_pending(session) before = count_policy_values_naming_dynamic_parameters(session) us, uk = stored_countries + # Policy values on another country's prefix count for neither. + with sessions.begin() as session: + look_alike_us = _store_policy(session, us) + _store_policy_value(session, us, look_alike_us, US_GOV_DYNAMIC_POLICY_PARAMETER) + look_alike_uk = _store_policy(session, uk) + _store_policy_value(session, uk, look_alike_uk, UK_SIMULATION_POLICY_PARAMETER) + with sessions() as session: + assert count_policy_values_naming_dynamic_parameters(session) == before with sessions.begin() as session: us_policy = _store_policy(session, us) _store_policy_value(session, us, us_policy, US_MTR_DELTA) @@ -930,3 +940,79 @@ def test_the_seed_workflow_s_check_counts_what_the_revision_refuses( command.upgrade(alembic_v2_config(), "head") with sessions() as session: assert not dynamic_parameter_move_is_pending(session) + + +def test_the_upgrade_refuses_while_a_dynamic_value_names_a_policy_parameter( + sessions: sessionmaker[Session], stored_countries: list[StoredCountry] +) -> None: + """A dynamic's value on a parameter that stays in ``parameters`` would be lost. + + The new tables can't hold it, and every reader after the move reads a + dynamic's values from them, so the revision refuses rather than leave it. + """ + us = stored_countries[0] + value_id = uuid4() + with sessions.begin() as session: + add_row( + session, + ParameterValue, + id=value_id, + parameter_id=us.parameter_ids[US_POLICY_PARAMETER], + dynamic_id=us.dynamic_id, + value_json=0.3, + start_date=START_2027, + ) + before = _snapshot(sessions, stored_countries) + + with pytest.raises(RuntimeError, match="dynamic values name policy parameters"): + command.upgrade(alembic_v2_config(), DYNAMIC_PARAMETER_TABLES_REVISION) + + assert current_revision(sessions) == PARENT_REVISION + assert _snapshot(sessions, stored_countries) == before + with sessions.begin() as session: + session.execute( + delete(ParameterValue).where(col(ParameterValue.id) == value_id) + ) + command.upgrade(alembic_v2_config(), DYNAMIC_PARAMETER_TABLES_REVISION) + assert current_revision(sessions) == DYNAMIC_PARAMETER_TABLES_REVISION + + +# Long enough for the upgrade to reach its lock before the concurrent +# transaction commits; a slower start only makes the test weaker, never fail. +CONCURRENT_COMMIT_DELAY_SECONDS = 3.0 + + +def test_a_policy_value_written_while_the_upgrade_waits_is_refused( + sessions: sessionmaker[Session], stored_countries: list[StoredCountry] +) -> None: + """The revision locks the parameters it moves before it counts policy values. + + A transaction that writes a policy value naming one, and commits only after + the upgrade started, holds a key-share lock on the parameter. The upgrade + waits for it, then counts the value and refuses. Without the lock it would + count before the commit, then delete the parameter and with it the value. + """ + us = stored_countries[0] + committed = threading.Event() + with sessions() as writer: + policy_id = _store_policy(writer, us) + _store_policy_value(writer, us, policy_id, US_ELASTICITY) + writer.flush() + + def commit_later() -> None: + committed.wait(CONCURRENT_COMMIT_DELAY_SECONDS) + writer.commit() + + with ThreadPoolExecutor(max_workers=1) as executor: + commit = executor.submit(commit_later) + try: + with pytest.raises( + RuntimeError, match="policy values name dynamic parameters" + ): + command.upgrade( + alembic_v2_config(), DYNAMIC_PARAMETER_TABLES_REVISION + ) + finally: + committed.set() + commit.result() + assert current_revision(sessions) == PARENT_REVISION diff --git a/tests/integration/test_v2_catalog_publication_dynamic_parameters.py b/tests/integration/test_v2_catalog_publication_dynamic_parameters.py index 459e31c4c..a83b28613 100644 --- a/tests/integration/test_v2_catalog_publication_dynamic_parameters.py +++ b/tests/integration/test_v2_catalog_publication_dynamic_parameters.py @@ -53,7 +53,10 @@ DYNAMIC_PARAMETER_RECORDS, catalog_with_dynamic_parameters, ) -from tests.integration.catalog_publication_support import emptied_catalog +from tests.integration.catalog_publication_support import ( + clear_format_2_fields, + emptied_catalog, +) from tests.integration.simulation_rows import add_row if TYPE_CHECKING: @@ -560,3 +563,47 @@ def test_republication_writes_format_2_beside_a_stored_format_1_file( assert [model for model, *_sizes in evidence.parameter_search_files_written] == [ "policyengine-us" ] + + +def test_a_version_stored_before_format_2_compares_its_dynamic_parameters_too( + publication_sessions: sessionmaker[Session], + writer_sessions: sessionmaker[Session], +) -> None: + """A version stored before catalog format 2 has no flags in either table. + + Publishing it again compares both parameter tables without format 2's + fields, so it passes, and still fails when a dynamic parameter's label + differs. + """ + _publish(writer_sessions) + with publication_sessions.begin() as session: + clear_format_2_fields(session) + + republished = _publish(writer_sessions) + + assert republished.parameter_trees_written == () + with publication_sessions() as session: + flags = session.execute( + sa.select(col(DynamicParameter.economy), col(DynamicParameter.household)) + ).all() + assert flags + assert {tuple(row) for row in flags} == {(None, None)} + catalog = catalog_with_dynamic_parameters(policyengine_version=INSTALLED_VERSION) + uk = catalog.country("uk") + changed = replace( + catalog, + countries=( + catalog.country("us"), + replace( + uk, + parameters=tuple( + replace(parameter, label="Changed label") + if parameter.name == "gov.dynamic.obr_labour_supply_assumptions" + else parameter + for parameter in uk.parameters + ), + ), + ), + ) + with pytest.raises(CatalogPublicationError, match=r"in its dynamic parameters$"): + publish_catalog(writer_sessions, changed) diff --git a/tests/unit/v2/test_policy_legacy_copy.py b/tests/unit/v2/test_policy_legacy_copy.py index b13f0bf2d..4d0173d4a 100644 --- a/tests/unit/v2/test_policy_legacy_copy.py +++ b/tests/unit/v2/test_policy_legacy_copy.py @@ -570,7 +570,7 @@ def test_a_copy_that_loses_the_mapping_race_reports_the_mapped_dynamic( ) -def test_a_policy_parameter_and_an_assumption_of_the_same_name_stay_apart( +def test_a_model_assumption_found_only_among_policy_parameters_is_missing( catalog_session: Session, recorded_writes: RecordedCopyWrites ) -> None: """The copy looks each part's names up in its own table. From cb162caadc0f91dc96b11008c340376524e4dc2e Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:46:55 +0400 Subject: [PATCH 07/10] =?UTF-8?q?C1=20=C2=B7=2050:=20fix=20review=20round?= =?UTF-8?q?=202's=20findings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Revision 7f7335f0eb31 also refuses, changing nothing, while a dynamic's value names a parameter it doesn't move: dynamic_parameter_values can't hold it, and after the move no reader would find it. - ParameterTreeChild's docstring says model assumptions and their folders have no tree rows; the migration guide names the publication modules that write both tables and says the check step classifies with the package's prefixes, which a test keeps equal to the revision's. Co-Authored-By: Claude Opus 5.5 --- docs/engineering/skills/alembic-migrations.md | 11 ++++++++-- ...move_dynamic_parameters_into_their_own_.py | 21 ++++++++++++++++++- policyengine_api/data/v2/models/metadata.py | 10 +++++---- 3 files changed, 35 insertions(+), 7 deletions(-) diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index ad4a529bc..4a7c0268a 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -1618,6 +1618,11 @@ schema check in, so a failure anywhere changes nothing: "Qualify the pending dynamic parameter move" (`scripts/qualify_v2_dynamic_parameter_move.py`) counts the same values while the revision is pending, so a deploy stops before Alembic starts. + The step classifies with the package's prefixes, which a test keeps equal + to the revision's. The revision also refuses while a dynamic's value names + a parameter it doesn't move: the new tables can't hold such a value, and + after the move no reader would find it. `require_dynamic_parameters` has + refused such values since dynamics were added, so none is expected. 2. It copies every stored version's dynamic parameters into `dynamic_parameters`, and their current-law values and every dynamic's values into `dynamic_parameter_values`, with their IDs and `created_at`. @@ -1642,8 +1647,10 @@ which `test_dynamic_parameter_tables_revision_keeps_its_own_copy_of_the_prefixes keeps equal to the package's, and catalog publication compares the installed version's rows with the package's own classification right after the upgrade. Publication then writes, compares, restores and prunes both tables -(`policyengine_api/data/v2/catalog/dynamic_parameter_records.py`), builds the -policy tree without dynamic parameters and their folders, and writes the +(`publication_inserts`, `publication_reconciliation` and +`publication_pruning`, classifying records with `dynamic_parameter_records`), +builds the policy tree without dynamic parameters and their folders, and +writes the search file in format 2, which lists none of them; versions stored before keep their format 1 files, which the previous release serves. Publication writes a format 2 file only for the version it installs, so an older stored version diff --git a/migrations/v2/versions/7f7335f0eb31_move_dynamic_parameters_into_their_own_.py b/migrations/v2/versions/7f7335f0eb31_move_dynamic_parameters_into_their_own_.py index 33e1ebc48..19b3fa1c7 100644 --- a/migrations/v2/versions/7f7335f0eb31_move_dynamic_parameters_into_their_own_.py +++ b/migrations/v2/versions/7f7335f0eb31_move_dynamic_parameters_into_their_own_.py @@ -21,7 +21,9 @@ 1. It locks the parameters it moves, so no value can start naming one, and refuses, changing nothing, while a policy value names one: deleting the parameter would delete that value with it and silently change the policy. - Operator step C1 · 49 splits such policies first. + Operator step C1 · 49 splits such policies first. It also refuses while a + dynamic's value names a parameter it doesn't move, which the new tables + can't hold and no reader would find after the move. 2. It copies every version's dynamic parameters, their current-law values and every dynamic's values into the new tables, with their IDs and creation times, so stored dynamics' content hashes, which cover parameter IDs, stay @@ -237,6 +239,23 @@ def _move_dynamic_parameters_into_their_tables() -> None: "(operator step C1 · 49), then upgrade again" ) raise RuntimeError(msg) + stranded_values = bind.execute( + sa.select(sa.func.count()) + .select_from(_parameter_values) + .where( + _parameter_values.c.dynamic_id.is_not(None), + _parameter_values.c.parameter_id.not_in(moved_ids), + ) + ).scalar_one() + if stranded_values: + msg = ( + "the upgrade to 7f7335f0eb31 stopped, changing nothing: dynamic values " + f"name policy parameters ({stranded_values} found), which " + "dynamic_parameter_values can't hold, so the move would leave them " + "where no reader finds them; delete or correct them first, then " + "upgrade again" + ) + raise RuntimeError(msg) # SQLAlchemy keeps an INSERT's row count only when asked to. copied_parameters = bind.execute( diff --git a/policyengine_api/data/v2/models/metadata.py b/policyengine_api/data/v2/models/metadata.py index 0ad97659a..ca41b0097 100644 --- a/policyengine_api/data/v2/models/metadata.py +++ b/policyengine_api/data/v2/models/metadata.py @@ -624,10 +624,12 @@ class ParameterTreeChild(IdentifiedModel, table=True): Catalog publication writes a version's rows from the installed packages' catalog: for each version it publishes, and for the installed version when it is stored with catalog format 2 but without a tree. Other versions have - no rows. Every node and parameter of the version is one row under its - parent's path ("" for top-level paths), so listing one level reads one - index. ``position`` orders all children of a parent; ``reform_position`` - orders only those a reform can change and is null for the others. Node rows + no rows. Every policy parameter of the version, and every node above one, + is one row under its parent's path ("" for top-level paths), so listing + one level reads one index; model assumptions (``DynamicParameter``) and + the folders that hold only them have no rows. ``position`` orders all + children of a parent; ``reform_position`` orders only those a reform can + change and is null for the others. Node rows count their direct children; parameter rows reference their parameter and copy its flags. """ From 302f17355ced10976e20e0240c870fbdb40afb11 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:32:54 +0400 Subject: [PATCH 08/10] =?UTF-8?q?Store=20C1=20=C2=B7=2045's=20household=20?= =?UTF-8?q?test=20assumptions=20in=20the=20dynamic=20parameter=20tables?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The merge of C1 · 48's branch brought C1 · 45's household calculation route tests, whose catalog stored model assumptions in parameters and a dynamic's values in parameter_values. Since C1 · 50 they are dynamic_parameters and dynamic_parameter_values rows, as catalog publication and the dynamics service store them, so the missing-assumption check reads them there. Co-Authored-By: Claude Opus 5.5 --- ...t_household_calculation_database_routes.py | 21 +++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/tests/unit/v2/test_household_calculation_database_routes.py b/tests/unit/v2/test_household_calculation_database_routes.py index fcccdb432..118baddd1 100644 --- a/tests/unit/v2/test_household_calculation_database_routes.py +++ b/tests/unit/v2/test_household_calculation_database_routes.py @@ -9,7 +9,7 @@ import json from datetime import UTC, datetime -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any from uuid import UUID, uuid4 import httpx @@ -21,6 +21,8 @@ from policyengine_api.data.v2.models import ( Country, Dynamic, + DynamicParameter, + DynamicParameterValue, Household, Parameter, ParameterValue, @@ -93,12 +95,19 @@ def sessions() -> Iterator[sessionmaker[Session]]: def _catalog_version( session: Session, model: TaxBenefitModel, version: str, names: list[str] -) -> dict[str, Parameter]: +) -> dict[str, Any]: + """Store a catalog version with these parameters, keyed by name. + + Model assumptions are ``dynamic_parameters`` rows and the others + ``parameters`` rows, as catalog publication stores them (C1 · 50). + """ model_version = TaxBenefitModelVersion( model=model, version=version, current_law_id=1, metadata_time_periods=[2026] ) parameters = { - name: Parameter(name=name, tax_benefit_model_version=model_version) + name: (DynamicParameter if name.startswith("gov.simulation.") else Parameter)( + name=name, tax_benefit_model_version=model_version + ) for name in names } session.add(model_version) @@ -109,7 +118,7 @@ def _catalog_version( def _dynamic( session: Session, - parameters: dict[str, Parameter], + parameters: dict[str, Any], hash_seed: str, *, country_id: str = "us", @@ -127,8 +136,8 @@ def _dynamic( session.add(dynamic) session.flush() session.add_all( - ParameterValue( - parameter_id=parameter.id, + DynamicParameterValue( + dynamic_parameter_id=parameter.id, value_json=0.1, start_date=STORED_AT, dynamic_id=dynamic.id, From fdb03deeba17b18ac000c8900c5ecce362f386a4 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:06:27 +0400 Subject: [PATCH 09/10] Update the publication tests that pin its output to both parameter tables CI found seven existing tests still expecting publication's shapes from before the dynamic parameter tables: the evidence's entity counts (now with dynamic_parameters and dynamic_parameter_values), the restored versions' tuples (now with a second count), the nine analyzed tables, the comparison pairs (now with dynamic parameters and their values), and the staged parameter rows (now ending with is_dynamic). Co-Authored-By: Claude Opus 5.5 --- tests/integration/test_v2_catalog_publication.py | 3 +++ tests/integration/test_v2_catalog_publication_pruning.py | 4 ++-- tests/integration/test_v2_catalog_statistics.py | 2 ++ tests/unit/v2/test_catalog_publication.py | 9 ++++++--- tests/unit/v2/test_catalog_staging_rows.py | 2 ++ 5 files changed, 15 insertions(+), 5 deletions(-) diff --git a/tests/integration/test_v2_catalog_publication.py b/tests/integration/test_v2_catalog_publication.py index bcd992b34..4203ec36f 100644 --- a/tests/integration/test_v2_catalog_publication.py +++ b/tests/integration/test_v2_catalog_publication.py @@ -370,6 +370,9 @@ def test_stored_version_keeps_its_published_regions_and_logs_the_difference( "parameter_nodes": before_counts["parameter_nodes"], "parameters": before_counts["parameters"], "parameter_values": before_counts["parameter_values"], + # The fixture catalog holds no model assumption. + "dynamic_parameters": 0, + "dynamic_parameter_values": 0, "datasets": before_counts["datasets"], "regions": before_counts["regions"], } diff --git a/tests/integration/test_v2_catalog_publication_pruning.py b/tests/integration/test_v2_catalog_publication_pruning.py index fcbbce5bf..74c4ebe90 100644 --- a/tests/integration/test_v2_catalog_publication_pruning.py +++ b/tests/integration/test_v2_catalog_publication_pruning.py @@ -1076,7 +1076,7 @@ def test_every_publication_records_when_it_published_the_version( assert { (country_id, version) - for country_id, version, _values in restoring.restored_catalog_versions + for country_id, version, *_values in restoring.restored_catalog_versions } == {("us", OLD_VERSION), ("uk", OLD_VERSION)} for model_name in MODEL_NAMES: assert first[model_name] is not None @@ -1310,7 +1310,7 @@ def test_restoring_a_version_stored_before_catalog_format_2_writes_values_only( assert _pruned_at(publication_sessions, model_name, OLD_VERSION) is None assert { (country_id, version) - for country_id, version, _values in restoring.restored_catalog_versions + for country_id, version, *_values in restoring.restored_catalog_versions } == {("us", OLD_VERSION), ("uk", OLD_VERSION)} assert restoring.parameter_trees_written == () assert restoring.parameter_search_files_written == () diff --git a/tests/integration/test_v2_catalog_statistics.py b/tests/integration/test_v2_catalog_statistics.py index feff77bdc..eb9fd4d33 100644 --- a/tests/integration/test_v2_catalog_statistics.py +++ b/tests/integration/test_v2_catalog_statistics.py @@ -49,6 +49,8 @@ UNDEFINED_TABLE_FAILURE = "psycopg.errors.UndefinedTable (SQLSTATE 42P01)" ANALYZED_TABLES = ( "datasets", + "dynamic_parameter_values", + "dynamic_parameters", "parameter_nodes", "parameter_tree_children", "parameter_values", diff --git a/tests/unit/v2/test_catalog_publication.py b/tests/unit/v2/test_catalog_publication.py index fb41c7cec..690f75e72 100644 --- a/tests/unit/v2/test_catalog_publication.py +++ b/tests/unit/v2/test_catalog_publication.py @@ -235,7 +235,9 @@ def test_publication_uses_mapped_tables_and_sqlalchemy_statements() -> None: "variables", "parameter nodes", "parameters", + "dynamic parameters", "parameter values", + "dynamic parameter values", "datasets", ] pairs = (*comparisons, ("regions", *region_pair)) @@ -249,14 +251,15 @@ def test_publication_uses_mapped_tables_and_sqlalchemy_statements() -> None: len(staged.selected_columns) == len(stored.selected_columns) for _table_name, staged, stored in pairs ) - # Format 2 compares model versions, variables and parameters on more fields. - # Regions are compared separately, on the same fields in both formats. + # Format 2 compares model versions, variables, parameters and dynamic + # parameters on more fields. Regions are compared separately, on the same + # fields in both formats. assert [ len(format_2[1].selected_columns) - len(format_1[1].selected_columns) for format_1, format_2 in zip( format_1_comparisons, format_2_comparisons, strict=True ) - ] == [3, 8, 0, 2, 0, 0] + ] == [3, 8, 0, 2, 2, 0, 0, 0] class Result: def scalar_one(self): diff --git a/tests/unit/v2/test_catalog_staging_rows.py b/tests/unit/v2/test_catalog_staging_rows.py index ad23cb02c..33df63b75 100644 --- a/tests/unit/v2/test_catalog_staging_rows.py +++ b/tests/unit/v2/test_catalog_staging_rows.py @@ -108,6 +108,8 @@ def test_catalog_rows_project_every_record_field_in_column_order() -> None: record.unit, record.economy, record.household, + # The fixture catalog's parameters are all policy parameters. + False, ) for record in country.parameters ] From a1c89ad052b1e723709937ae61f837318c0bfcc9 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:20:56 +0400 Subject: [PATCH 10/10] Cover the check command's success output, its pending check and the unsupported country Codecov's first report on #4347 listed these as uncovered changed lines: the dynamic parameter move check printing its evidence, asking Alembic about revision 7f7335f0eb31, and publication refusing to classify a country with no model assumption prefixes. Co-Authored-By: Claude Opus 5.5 --- tests/unit/test_dynamic_parameters.py | 14 +++++++++ ...st_dynamic_parameter_move_qualification.py | 31 +++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/tests/unit/test_dynamic_parameters.py b/tests/unit/test_dynamic_parameters.py index 0f32b3469..30feb2f75 100644 --- a/tests/unit/test_dynamic_parameters.py +++ b/tests/unit/test_dynamic_parameters.py @@ -239,3 +239,17 @@ def test_gov_dynamic_has_one_spelling_and_is_never_rewritten() -> None: assert canonical_parameter_name("uk", UK_OBR_LABOUR_SUPPLY_SWITCH) == ( UK_OBR_LABOUR_SUPPLY_SWITCH ) + + +def test_publication_refuses_to_classify_an_unsupported_country() -> None: + """A catalog country with no prefixes can't be split into the two tables.""" + from policyengine_api.data.v2.catalog.dynamic_parameter_records import ( + is_dynamic_record, + ) + from policyengine_api.data.v2.catalog.publication_types import ( + CatalogPublicationError, + ) + + assert is_dynamic_record("uk", "gov.dynamic.obr_labour_supply_assumptions") + with pytest.raises(CatalogPublicationError, match="'ca' is not a supported"): + is_dynamic_record("ca", "gov.simulation.example") diff --git a/tests/unit/v2/test_dynamic_parameter_move_qualification.py b/tests/unit/v2/test_dynamic_parameter_move_qualification.py index 8a8c182cb..8c817a925 100644 --- a/tests/unit/v2/test_dynamic_parameter_move_qualification.py +++ b/tests/unit/v2/test_dynamic_parameter_move_qualification.py @@ -161,3 +161,34 @@ def test_a_target_without_the_catalog_tables_counts_no_value( } assert session.statements == [] assert session.rolled_back + + +def test_main_prints_the_evidence_and_exits_zero( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + evidence = move.DynamicParameterMoveQualification( + environment="staging", + project_ref="abcdefghijklmnopqrst", + policy_values_naming_dynamic_parameters=0, + ) + monkeypatch.setattr( + move, "qualify_dynamic_parameter_move_if_pending", lambda: evidence + ) + + assert move.main() == 0 + assert json.loads(capsys.readouterr().out) == evidence.as_dict() + + +def test_the_pending_check_asks_about_the_dynamic_parameter_tables_revision( + monkeypatch: pytest.MonkeyPatch, +) -> None: + asked: list[str] = [] + + def pending(_session: object, revision: str) -> bool: + asked.append(revision) + return True + + monkeypatch.setattr(move, "v2_revision_is_pending", pending) + + assert move.dynamic_parameter_move_is_pending(object()) + assert asked == ["7f7335f0eb31"]