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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/scripts/test_alembic_v2_lifecycle.sh
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ set -euo pipefail
uv run --frozen --extra dev pytest -q \
tests/unit/v2/test_alembic_v2.py \
tests/unit/v2/test_alembic_v2_revisions.py \
tests/unit/v2/test_alembic_v2_dynamic_revisions.py \
tests/integration/test_alembic_v2_lifecycle.py \
tests/integration/test_alembic_v2_catalog_tables.py \
tests/integration/test_alembic_v2_simulation_runs.py \
Expand All @@ -16,4 +17,5 @@ uv run --frozen --extra dev pytest -q \
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_dynamic_parameter_tables.py
tests/integration/test_alembic_v2_dynamic_parameter_tables.py \
tests/integration/test_alembic_v2_parameter_values_dynamic_id_drop.py
1 change: 1 addition & 0 deletions changelog.d/v2-parameter-values-dynamic-id.removed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`parameter_values` no longer has `dynamic_id`: since revision `7f7335f0eb31` a dynamic's values are `dynamic_parameter_values` rows. Revision `1c651058fac5` drops the column with its key to `dynamics`, the single-owner check `ck_parameter_values_single_owner` and the per-dynamic index `uq_parameter_values_dynamic_parameter_start_date`, and replaces the current-law index with `uq_parameter_values_current_law_parameter_start_date` on `policy_id IS NULL`. A `parameter_values` row is now a policy's value or a current-law value.
96 changes: 87 additions & 9 deletions docs/engineering/skills/alembic-migrations.md
Original file line number Diff line number Diff line change
Expand Up @@ -310,9 +310,9 @@ and `refused(session, ...)`.
takes the Python value, such as `[2026]`, not its JSON text.
- **Columns a mapper leaves out**: a column kept in its table but left out of
the model's mapper (`exclude_properties`) until a revision drops it, as
`parameter_values.dynamic_id` is until C1 · 53's revision, and the per-user
and cliff columns of `reports`, `report_runs` and `budget_window_runs` were
until revision `4e30076d4b9f`, has no statement
`parameter_values.dynamic_id` was until revision `1c651058fac5`, and the
per-user and cliff columns of `reports`, `report_runs` and
`budget_window_runs` were until revision `4e30076d4b9f`, has no statement
through the model: `update(Model).values(column=...)` raises
`AttributeError`, a constructor value is never stored, and `Model.column`
is the table's Core column, which the rule rules out even in a `select`. A
Expand Down Expand Up @@ -756,6 +756,8 @@ 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:
`1c651058fac5`'s adds `parameter_values.dynamic_id` back empty, with its key,
check and per-dynamic index (see "API v2 parameter values without dynamics"),
`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"),
Expand Down Expand Up @@ -1357,7 +1359,8 @@ changes, so that dynamics are stored as policies are:
still reads every row of `parameter_values` (millions of current-law
values), and, as Alembic creates it without `CONCURRENTLY`, inserts into
that table wait until the build finishes. It is also declared for SQLite,
so the unit tests' databases keep the same rule.
so the unit tests' databases keep the same rule. Revision `1c651058fac5`
drops it with `parameter_values.dynamic_id`.
- `legacy_policy_mappings` gains the nullable `dynamic_id`, the dynamic the
v1-to-v2 policy copy split from a v1 policy: a key with the mapping's
country to `dynamics` (`fk_legacy_policy_mappings_dynamic_country`,
Expand Down Expand Up @@ -1710,13 +1713,88 @@ 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
map the column; API v1 stops mapping it from C1 · 51a's release (see
"Columns a mapper leaves out"), so the release serving while C1 · 53's
revision runs names none of what it drops.
`tests/integration/test_alembic_v2_dynamic_parameter_tables.py`
unique index stay until revision `1c651058fac5` (see "API v2 parameter values
without dynamics"), because older simulation service releases map the column;
API v1 stops mapping it from C1 · 51a's release (see "Columns a mapper leaves
out"), so the release serving while that revision runs names none of what it
drops. `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.

### API v2 parameter values without dynamics

Revision `1c651058fac5` (parent `7f7335f0eb31`) was autogenerated, with its ID
given by `--rev-id`, after `ParameterValue` lost `dynamic_id`, the
single-owner check and the per-dynamic index. It has no post-generation
correction. Since `7f7335f0eb31` moved every dynamic's values to
`dynamic_parameter_values`, no `parameter_values` row names a dynamic, so it
drops:

- `parameter_values.dynamic_id`, with its key to `dynamics`
(`fk_parameter_values_dynamic_id_dynamics`);
- `ck_parameter_values_single_owner`, which kept a row to one of a policy and
a dynamic;
- `uq_parameter_values_dynamic_parameter_start_date`, `9d1d12a7ac58`'s index
of one value per dynamic, parameter and start date.

A `parameter_values` row is then a policy's value (`policy_id` set) or a
current-law value (`policy_id` null).

**The current-law index is renamed.** The condition of
`uq_parameter_values_canonical_parameter_start_date`, one current-law value
per parameter and start date, was `policy_id IS NULL AND dynamic_id IS NULL`,
and PostgreSQL drops an index whose condition names a dropped column. Alembic
compares an index's condition by name only, as it does a check's, so, as for
`ck_users_user_type_allowed`, the model names the index with its new condition
`policy_id IS NULL` `uq_parameter_values_current_law_parameter_start_date`,
and autogenerate drops the old index and creates the new one (the user's
decision 2 for C1 · 53, 2026-11-26). It is also declared for SQLite.

Building it reads every current-law value (millions of rows), after the drop
of the old index has locked `parameter_values` until the migration
transaction commits, so every read and write of the table waits for the
build, and API v1's and the simulation service's statements, which time out
after 5 seconds, fail meanwhile. `9d1d12a7ac58`'s index build, which read every
row but indexed only dynamics' rows, took about 10 seconds in production. In
production nothing reads these rows through the v2 routes yet; the dual-write
v1-to-v2 policy copy writes them, and a failed copy is logged with the v1
response unchanged.

**What must be in production first,** because the deploy upgrades the schema
before the new release takes traffic (see "CI/CD behavior"), and a whole-row
load names every mapped column:

- An API v1 release whose `ParameterValue` doesn't map `dynamic_id`: C1 · 51a
leaves it out of the mapper (the user's decision 1 for C1 · 53; C1 · 50
merged without that change), so the pull request merges only once C1 · 51a's
release is in production.
- The simulation service's C1 · 52 (PolicyEngine/policyengine-sim-api#1129),
which stops mapping the column: older releases select it in every policy
read.

**An operator counts first** (the user's decision 3 for C1 · 53). A row that
still names a dynamic becomes a current-law value when the column goes,
silently, unless it shares its parameter and start date with a current-law
value, when the new index fails the upgrade and nothing changes. None is
expected: `7f7335f0eb31` moves every dynamic's value and refuses one that
names a parameter it doesn't move, and no release since writes the column.
One merge takes the revision through staging and production, so before
merging, an operator runs this read-only count in both environments, and the
pull request merges only when both are 0:

```sql
SELECT count(*) FROM parameter_values WHERE dynamic_id IS NOT NULL;
```

**The downgrade** adds the column back empty with its key, the check and the
per-dynamic index, and replaces the current-law index with the old one, so
that `7f7335f0eb31`'s downgrade can copy every dynamic's values back into
`parameter_values` with their `dynamic_id`. No role's privilege names the
column. `tests/integration/test_alembic_v2_parameter_values_dynamic_id_drop.py`
compares the revision and its downgrade with the parent schema built from
the base, and checks that rows survive, the new index, a downgrade through
`7f7335f0eb31` and back, what a row still naming a dynamic becomes, and the
deploy's privilege steps.
3 changes: 2 additions & 1 deletion docs/engineering/skills/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ The generated-only v2 Alembic chain and disposable Postgres lifecycle:

```bash
uv run pytest tests/unit/v2/test_alembic_v2.py tests/unit/v2/test_alembic_v2_revisions.py \
tests/unit/test_alembic_workflows.py -q
tests/unit/v2/test_alembic_v2_dynamic_revisions.py tests/unit/test_alembic_workflows.py -q
V2_ALEMBIC_DISPOSABLE_TEST=1 V2_MIGRATION_DATABASE_URL="postgresql+psycopg://.../policyengine_v2_alembic_test" \
uv run pytest tests/integration/test_alembic_v2_lifecycle.py tests/integration/test_alembic_v2_catalog_tables.py -q
```
Expand Down Expand Up @@ -642,6 +642,7 @@ uv run --frozen pytest \
tests/unit/v2/test_models.py \
tests/unit/v2/test_alembic_v2.py \
tests/unit/v2/test_alembic_v2_revisions.py \
tests/unit/v2/test_alembic_v2_dynamic_revisions.py \
tests/unit/test_readiness.py \
tests/unit/test_cloud_run_deploy_scripts.py \
tests/unit/test_migration_contract_artifacts.py \
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"""drop parameter values dynamic_id

Revision ID: 1c651058fac5
Revises: 7f7335f0eb31
Create Date: 2026-11-26 18:42:38.287815
Generation: uv run alembic -c alembic-v2.ini revision --autogenerate --rev-id 1c651058fac5

Revision 7f7335f0eb31 moved every dynamic's values to dynamic_parameter_values,
so no parameter_values row names a dynamic. This drops parameter_values'
dynamic_id with its key to dynamics, the single-owner check and the
per-dynamic partial unique index. PostgreSQL also drops an index whose
condition names a dropped column, and Alembic compares an index's condition
by name only, so the model renamed the current-law index, and the upgrade
replaces uq_parameter_values_canonical_parameter_start_date with
uq_parameter_values_current_law_parameter_start_date on policy_id IS NULL.
The operations are exactly as generated.

A row that still names a dynamic becomes a current-law value, so an operator
counts them first. Every release still serving when this runs must leave
dynamic_id out of its models. The downgrade adds the column back empty, with
its key, check and indexes, so that 7f7335f0eb31's downgrade can copy
dynamics' values back.
"""

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
import sqlmodel


revision: str = '1c651058fac5'
down_revision: Union[str, None] = '7f7335f0eb31'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('uq_parameter_values_canonical_parameter_start_date'), table_name='parameter_values', postgresql_where='((policy_id IS NULL) AND (dynamic_id IS NULL))')
op.drop_index(op.f('uq_parameter_values_dynamic_parameter_start_date'), table_name='parameter_values', postgresql_where='(dynamic_id IS NOT NULL)')
op.create_index('uq_parameter_values_current_law_parameter_start_date', 'parameter_values', ['parameter_id', 'start_date'], unique=True, postgresql_where=sa.text('policy_id IS NULL'), sqlite_where=sa.text('policy_id IS NULL'))
op.drop_constraint(op.f('fk_parameter_values_dynamic_id_dynamics'), 'parameter_values', type_='foreignkey')
op.drop_constraint(op.f('ck_parameter_values_single_owner'), 'parameter_values', type_='check')
op.drop_column('parameter_values', 'dynamic_id')
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('parameter_values', sa.Column('dynamic_id', sa.UUID(), autoincrement=False, nullable=True))
op.create_check_constraint(op.f('ck_parameter_values_single_owner'), 'parameter_values', 'policy_id IS NULL OR dynamic_id IS NULL')
op.create_foreign_key(op.f('fk_parameter_values_dynamic_id_dynamics'), 'parameter_values', 'dynamics', ['dynamic_id'], ['id'], ondelete='CASCADE')
op.drop_index('uq_parameter_values_current_law_parameter_start_date', table_name='parameter_values', postgresql_where=sa.text('policy_id IS NULL'), sqlite_where=sa.text('policy_id IS NULL'))
op.create_index(op.f('uq_parameter_values_dynamic_parameter_start_date'), 'parameter_values', ['dynamic_id', 'parameter_id', 'start_date'], unique=True, postgresql_where='(dynamic_id IS NOT NULL)')
op.create_index(op.f('uq_parameter_values_canonical_parameter_start_date'), 'parameter_values', ['parameter_id', 'start_date'], unique=True, postgresql_where='((policy_id IS NULL) AND (dynamic_id IS NULL))')
# ### end Alembic commands ###
2 changes: 1 addition & 1 deletion policyengine_api/data/v2/migration_target.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
from sqlmodel import Session

V2_ALEMBIC_DISPOSABLE_TEST = "V2_ALEMBIC_DISPOSABLE_TEST"
V2_ALEMBIC_HEAD_REVISION = "7f7335f0eb31"
V2_ALEMBIC_HEAD_REVISION = "1c651058fac5"
DISPOSABLE_DATABASE_NAME = "policyengine_v2_alembic_test"
DISPOSABLE_HOSTS = frozenset({"localhost", "127.0.0.1", "::1", "postgres"})
MIGRATION_ROLE = "policyengine_v2_migrator"
Expand Down
6 changes: 0 additions & 6 deletions policyengine_api/data/v2/models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,6 @@
"Concurrent report idempotency requires a savepoint and bounded "
"IntegrityError recovery around the database uniqueness constraint."
),
"columns_left_out_of_the_mapper": (
"A column API v1 no longer uses stays a SQLModel field of its "
"table, left out of the mapper by exclude_properties, until other "
"writers have stopped and a later revision drops it; API v1 neither "
"loads nor writes it meanwhile."
),
}
)

Expand Down
48 changes: 10 additions & 38 deletions policyengine_api/data/v2/models/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from datetime import datetime
from enum import StrEnum
from typing import TYPE_CHECKING, Any, ClassVar, Literal, Optional
from typing import TYPE_CHECKING, Any, Literal, Optional
from uuid import UUID

import sqlalchemy as sa
Expand Down Expand Up @@ -431,23 +431,12 @@ class ParameterValue(IdentifiedModel, table=True):
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. A dynamic's values are
``DynamicParameterValue`` rows since revision 7f7335f0eb31 moved them, so
no row has a ``dynamic_id``. The column stays a SQLModel field, as rule
``api.data.orm-only`` requires of every column, and ``exclude_properties``
leaves it out of the mapper, so API v1 neither loads nor writes it: a value
given to the constructor is never stored, and the class attribute is the
table's column, not a value to read. A release keeps working while C1 · 53
drops the column, its check and its index, once no simulation service
release maps it either.
``DynamicParameterValue`` rows: revision 7f7335f0eb31 moved them there, and
revision 1c651058fac5 dropped ``dynamic_id`` with its check and index.
"""

__tablename__ = "parameter_values"
__mapper_args__: ClassVar[dict[str, Any]] = {"exclude_properties": ("dynamic_id",)}
__table_args__ = (
sa.CheckConstraint(
"policy_id IS NULL OR dynamic_id IS NULL",
name="ck_parameter_values_single_owner",
),
sa.CheckConstraint(
"end_date IS NULL OR end_date >= start_date",
name="ck_parameter_values_effective_period",
Expand All @@ -458,34 +447,24 @@ class ParameterValue(IdentifiedModel, table=True):
"start_date",
name="uq_parameter_values_policy_parameter_start_date",
),
# A dynamic's values are unique as a policy's are. The index covers
# only dynamics' rows, so it doesn't index every current-law value;
# rows without a dynamic never conflict in a unique key anyway.
sa.Index(
"uq_parameter_values_dynamic_parameter_start_date",
"dynamic_id",
"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_parameter_values_parameter_period",
"parameter_id",
"start_date",
"end_date",
),
# SQLModel does not expose dialect-specific partial unique indexes.
# Canonical values have neither an owning policy nor dynamic, while
# those owners may each store their own value for the same period.
# Current-law values have no owning policy, while each policy may
# store its own value for the same period. Alembic compares an
# index's condition by its name only, so the index took a new name
# when its condition stopped naming dynamic_id (revision 1c651058fac5).
sa.Index(
"uq_parameter_values_canonical_parameter_start_date",
"uq_parameter_values_current_law_parameter_start_date",
"parameter_id",
"start_date",
unique=True,
postgresql_where=sa.text("policy_id IS NULL AND dynamic_id IS NULL"),
sqlite_where=sa.text("policy_id IS NULL AND dynamic_id IS NULL"),
postgresql_where=sa.text("policy_id IS NULL"),
sqlite_where=sa.text("policy_id IS NULL"),
),
)

Expand All @@ -506,13 +485,6 @@ class ParameterValue(IdentifiedModel, table=True):
foreign_key="policies.id",
ondelete="CASCADE",
)
# In the table but left out of the mapper (``exclude_properties``) until a
# revision drops it.
dynamic_id: UUID | None = Field(
default=None,
foreign_key="dynamics.id",
ondelete="CASCADE",
)

parameter: Parameter = Relationship(back_populates="values")
policy: Optional["Policy"] = Relationship(back_populates="parameter_values")
Expand Down
Loading
Loading