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
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
API v1 no longer reads or writes `parameter_values.dynamic_id`, which no row has set since dynamics' values moved to `dynamic_parameter_values`; the table keeps the column until a later release drops it, and this release keeps serving once it does.
15 changes: 9 additions & 6 deletions docs/engineering/skills/alembic-migrations.md
Original file line number Diff line number Diff line change
Expand Up @@ -310,8 +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
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` 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
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 @@ -712,7 +713,7 @@ publication advisory lock, reads the model's stored versions again, skips the
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;
parameters whose `policy_id` is 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);
Expand All @@ -725,8 +726,7 @@ never deletes or changes any other row: not `parameters` or
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`.
`policy_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.
Expand Down Expand Up @@ -1711,7 +1711,10 @@ 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. `tests/integration/test_alembic_v2_dynamic_parameter_tables.py`
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`
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`
Expand Down
4 changes: 2 additions & 2 deletions docs/migration/stage-9-v2-metadata.md
Original file line number Diff line number Diff line change
Expand Up @@ -641,8 +641,8 @@ of a new version took 17 to 20 minutes in production, inside the job's
`policyengine_api/data/v2/catalog/publication_pruning.py`.

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 current-law `dynamic_parameter_values` (rows of its
`parameter_values` (rows of its parameters with no `policy_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
Expand Down
2 changes: 0 additions & 2 deletions policyengine_api/data/v2/catalog/publication_inserts.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,6 @@ def _parameters_insert(
"start_date",
"end_date",
"policy_id",
"dynamic_id",
],
sa.select(
col(StagedParameterValue.id),
Expand All @@ -340,7 +339,6 @@ def _parameters_insert(
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(
Expand Down
5 changes: 2 additions & 3 deletions policyengine_api/data/v2/catalog/publication_pruning.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
release whose promotion failed, or a rollback to an older version, since the
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, and those of its dynamic parameters with no dynamic;
- its current-law parameter values: those of its parameters with no policy,
and those of its dynamic parameters with no dynamic;
- its parameter tree rows;
- its parameter search files;

Expand Down Expand Up @@ -284,7 +284,6 @@ def prune_catalog_version(session: Session, version_id: UUID) -> PrunedRows | No
sa.delete(ParameterValue).where(
col(ParameterValue.parameter_id).in_(version_parameter_ids),
col(ParameterValue.policy_id).is_(None),
col(ParameterValue.dynamic_id).is_(None),
),
)
version_dynamic_parameter_ids = sa.select(col(DynamicParameter.id)).where(
Expand Down
11 changes: 4 additions & 7 deletions policyengine_api/data/v2/catalog/publication_reconciliation.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,6 @@ def staged_parameter_values(*, dynamic: bool) -> Select:
.where(
selected_version,
col(ParameterValue.policy_id).is_(None),
col(ParameterValue.dynamic_id).is_(None),
)
)

Expand Down Expand Up @@ -579,15 +578,13 @@ 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, in
either table; each parameter may have only one per start date.
Current-law values are those with no policy in ``parameter_values`` and
those with no dynamic in ``dynamic_parameter_values``; each parameter may
have only one per start date.
"""
duplicates = (
sa.select(col(ParameterValue.parameter_id))
.where(
col(ParameterValue.policy_id).is_(None),
col(ParameterValue.dynamic_id).is_(None),
)
.where(col(ParameterValue.policy_id).is_(None))
.group_by(
col(ParameterValue.parameter_id),
col(ParameterValue.start_date),
Expand Down
6 changes: 6 additions & 0 deletions policyengine_api/data/v2/models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@
"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
18 changes: 13 additions & 5 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, Literal, Optional
from typing import TYPE_CHECKING, Any, ClassVar, Literal, Optional
from uuid import UUID

import sqlalchemy as sa
Expand Down Expand Up @@ -430,13 +430,19 @@ 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. ``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.
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.
"""

__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",
Expand Down Expand Up @@ -500,6 +506,8 @@ 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",
Expand Down
4 changes: 2 additions & 2 deletions policyengine_api/data/v2/privileges.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,8 +305,8 @@ def _run_table(
runtime=READ, catalog_writer=READ_INSERT_DELETE | _ANALYZE
),
# 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
# deletes an older version's current-law values (those with no policy),
# 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,12 +118,11 @@ def read_parameter_values(
) -> list[ParameterValue]:
"""Return a page of a model version's current-law parameter values.

Values tied to a policy or dynamic are excluded. The selection's
parameter_id keeps one parameter's values, its parameter_names the values
of the parameters with those names, and its selected_day those in effect
on that day. Rows are ordered by parameter name, then newest
first, and limit + 1 are fetched so the caller can tell whether another
page exists.
A policy's values are excluded. The selection's parameter_id keeps one
parameter's values, its parameter_names the values of the parameters with
those names, and its selected_day those in effect on that day. Rows are
ordered by parameter name, then newest first, and limit + 1 are fetched
so the caller can tell whether another page exists.
"""
parameter_id = selection.parameter_id
selected_day = selection.selected_day
Expand All @@ -133,7 +132,6 @@ def read_parameter_values(
.where(
col(Parameter.tax_benefit_model_version_id) == model_version_id,
col(ParameterValue.policy_id).is_(None),
col(ParameterValue.dynamic_id).is_(None),
)
)
if parameter_id is not None:
Expand Down Expand Up @@ -174,7 +172,6 @@ def read_parameter_value(
col(ParameterValue.id) == value_id,
col(Parameter.tax_benefit_model_version_id) == model_version_id,
col(ParameterValue.policy_id).is_(None),
col(ParameterValue.dynamic_id).is_(None),
),
)
return rows[0] if rows else None
Expand All @@ -185,8 +182,8 @@ def read_current_law_values_by_parameter_name(
) -> list[CurrentLawValueRow]:
"""Return the current-law values of the named parameters of a model version.

Values tied to a policy or dynamic are excluded. Rows are ordered by
parameter name, then start date.
A policy's values are excluded. Rows are ordered by parameter name, then
start date.
"""
if not parameter_names:
return []
Expand All @@ -203,7 +200,6 @@ def read_current_law_values_by_parameter_name(
col(Parameter.tax_benefit_model_version_id) == model_version_id,
col(Parameter.name).in_(sorted(parameter_names)),
col(ParameterValue.policy_id).is_(None),
col(ParameterValue.dynamic_id).is_(None),
)
.order_by(col(Parameter.name), col(ParameterValue.start_date)),
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ def create_parameter_values(
[
ParameterValue(
policy_id=policy_id,
dynamic_id=None,
parameter_id=value.parameter_id,
value_json=value.value,
start_date=value.start_date,
Expand Down
41 changes: 41 additions & 0 deletions tests/integration/parameter_values_with_dynamics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""``parameter_values`` as the revisions before 1c651058fac5 leave it.

Until revision 1c651058fac5 the table has ``dynamic_id``, a dynamic's values
were stored in it (until revision 7f7335f0eb31 moved them to
``dynamic_parameter_values``), and the downgrade through 7f7335f0eb31 copies
them back. ``ParameterValue`` no longer maps the column, so tests of those
revisions store and read such rows through this class, on a registry of its
own. No code creates a table from it: Alembic creates the table.
"""

# No ``from __future__ import annotations``: SQLAlchemy reads the class's
# ``Mapped`` annotations when it maps it, so their names stay imported at
# runtime.
from datetime import datetime
from typing import Any
from uuid import UUID

from sqlalchemy import DateTime
from sqlalchemy.dialects import postgresql
from sqlalchemy.orm import Mapped, mapped_column, registry

parameter_values_with_dynamics = registry()


@parameter_values_with_dynamics.mapped
class ParameterValueWithDynamic:
"""A ``parameter_values`` row with the ``dynamic_id`` it had before 1c651058fac5.

``created_at`` is filled in by the database when an insert leaves it out.
"""

__tablename__ = "parameter_values"

id: Mapped[UUID] = mapped_column(primary_key=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
parameter_id: Mapped[UUID]
value_json: Mapped[Any] = mapped_column(postgresql.JSONB)
start_date: Mapped[datetime] = mapped_column(DateTime(timezone=True))
end_date: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
policy_id: Mapped[UUID | None]
dynamic_id: Mapped[UUID | None]
18 changes: 13 additions & 5 deletions tests/integration/test_alembic_v2_dynamic_parameter_tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@
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.parameter_values_with_dynamics import (
ParameterValueWithDynamic,
)
from tests.integration.simulation_rows import add_row, refused

if TYPE_CHECKING:
Expand Down Expand Up @@ -284,7 +287,7 @@ def _store_country(session: Session, country_id: str) -> StoredCountry:
for name in DYNAMIC_PARAMETERS[country_id]:
add_row(
session,
ParameterValue,
ParameterValueWithDynamic,
id=uuid4(),
parameter_id=stored.parameter_ids[name],
dynamic_id=stored.dynamic_id,
Expand Down Expand Up @@ -415,7 +418,10 @@ def _parameter_rows(session: Session, model: Any, version_ids: list[UUID]) -> se


def _parameter_value_rows(session: Session, version_ids: list[UUID]) -> set:
"""Return ``parameter_values`` rows of the versions' parameters."""
"""Return ``parameter_values`` rows of the versions' parameters.

The table has ``dynamic_id`` at the revisions these tests read it at.
"""
return {
(
row.id,
Expand All @@ -428,8 +434,10 @@ def _parameter_value_rows(session: Session, version_ids: list[UUID]) -> set:
row.dynamic_id,
)
for row in session.scalars(
select(ParameterValue)
.join(Parameter, col(Parameter.id) == col(ParameterValue.parameter_id))
select(ParameterValueWithDynamic)
.join(
Parameter, col(Parameter.id) == ParameterValueWithDynamic.parameter_id
)
.where(col(Parameter.tax_benefit_model_version_id).in_(version_ids))
)
}
Expand Down Expand Up @@ -955,7 +963,7 @@ def test_the_upgrade_refuses_while_a_dynamic_value_names_a_policy_parameter(
with sessions.begin() as session:
add_row(
session,
ParameterValue,
ParameterValueWithDynamic,
id=value_id,
parameter_id=us.parameter_ids[US_POLICY_PARAMETER],
dynamic_id=us.dynamic_id,
Expand Down
16 changes: 12 additions & 4 deletions tests/integration/test_alembic_v2_dynamics.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,14 @@
Dynamic,
LegacyPolicyMapping,
Parameter,
ParameterValue,
Policy,
)
from tests.fixtures.database_sessions import schema_inspector
from tests.fixtures.integration.alembic_v2 import alembic_v2_config, table_columns
from tests.integration.alembic_version_rows import current_revision
from tests.integration.parameter_values_with_dynamics import (
ParameterValueWithDynamic,
)
from tests.integration.simulation_rows import (
PublicApiRows,
add_row,
Expand Down Expand Up @@ -252,6 +254,12 @@ def test_the_revision_changes_only_dynamics_their_values_and_mappings(
def test_a_dynamic_is_stored_once_and_sets_one_value_per_parameter_and_date(
session: Session,
) -> None:
"""A dynamic is unique by its content hash, and its values as a policy's are.

``parameter_values`` keeps ``dynamic_id`` and the revision's partial unique
index until C1 · 53 drops them; ``ParameterValue`` no longer maps the
column, so the values are written through ``ParameterValueWithDynamic``.
"""
rows = insert_public_api_rows(session)
parameter_id = _insert_parameter(session, rows)
dynamic_id = _insert_dynamic(session, rows)
Expand All @@ -267,14 +275,14 @@ def test_a_dynamic_is_stored_once_and_sets_one_value_per_parameter_and_date(
"value_json": 0.1,
"start_date": datetime(2026, 1, 1, tzinfo=UTC),
}
add_row(session, ParameterValue, id=uuid4(), **value)
add_row(session, ParameterValueWithDynamic, id=uuid4(), **value)
with refused(session, match="uq_parameter_values_dynamic_parameter_start_date"):
add_row(session, ParameterValue, id=uuid4(), **value)
add_row(session, ParameterValueWithDynamic, id=uuid4(), **value)
# Another dynamic may set the same parameter from the same date.
other_dynamic_id = _insert_dynamic(session, rows, content_hash="e" * 64)
add_row(
session,
ParameterValue,
ParameterValueWithDynamic,
id=uuid4(),
**{**value, "dynamic_id": other_dynamic_id},
)
Expand Down
Loading
Loading