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 @@ -7,6 +7,7 @@ uv run --frozen --extra dev pytest -q \
tests/unit/v2/test_alembic_v2_revisions.py \
tests/unit/v2/test_alembic_v2_dynamic_revisions.py \
tests/unit/v2/test_alembic_v2_household_job_revisions.py \
tests/unit/v2/test_alembic_v2_report_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 @@ -23,4 +24,5 @@ uv run --frozen --extra dev pytest -q \
tests/integration/test_alembic_v2_published_reports.py \
tests/integration/test_alembic_v2_inline_household_jobs.py \
tests/integration/test_alembic_v2_published_report_images.py \
tests/integration/test_alembic_v2_saved_report_current_runs.py
tests/integration/test_alembic_v2_saved_report_current_runs.py \
tests/integration/test_alembic_v2_report_types.py
1 change: 1 addition & 0 deletions changelog.d/required-report-types.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Every API v2 report now names its type in `reports.type`: `economy`, `household` or `budget_window`. A v2 revision sets each stored report's type from whether it names a household or has a budget window (the simulation service stored budget windows as `economy` before), then makes the column required and adds the check `ck_reports_type`, which refuses a type that disagrees with those columns. API v1 reads the stored type to tell report types apart, and saving or updating a saved report reads the report it names once.
64 changes: 59 additions & 5 deletions docs/engineering/skills/alembic-migrations.md
Original file line number Diff line number Diff line change
Expand Up @@ -1832,8 +1832,8 @@ Alembic generated `uq_user_report_associations_id_report_id` after
refuses a foreign key to columns without a unique constraint. The upgrade
creates the constraint first, and the downgrade drops it after the tables.
The operations are otherwise as generated. The downgrade drops both tables
with their rows. `tests/unit/v2/test_alembic_v2_revisions.py` checks the
revision file and its one correction, and
with their rows. `tests/unit/v2/test_alembic_v2_report_revisions.py` checks
the revision file and its one correction, and
`tests/integration/test_alembic_v2_published_reports.py`, which the Alembic
v2 check runs, downgrades to the parent and upgrades again.
`tests/integration/test_v2_published_reports.py`, which the cross-database
Expand Down Expand Up @@ -1937,7 +1937,7 @@ research page's listing shows:
- `created_at` and `updated_at`.

The operations are exactly as generated. The downgrade drops the table with
its rows. `tests/unit/v2/test_alembic_v2_revisions.py` checks the
its rows. `tests/unit/v2/test_alembic_v2_report_revisions.py` checks the
revision file, and `tests/integration/test_alembic_v2_published_report_images.py`,
which the Alembic v2 check runs, downgrades to the parent and upgrades again.
`tests/integration/test_v2_published_reports.py`, which the cross-database
Expand Down Expand Up @@ -1990,10 +1990,64 @@ Deploying it:
report doesn't clear it, so the new key refuses the update. Nothing sets a
current run until app v3 sends one.

`tests/unit/v2/test_alembic_v2_revisions.py` checks the revision file.
`tests/integration/test_alembic_v2_saved_report_current_runs.py`, which the
`tests/unit/v2/test_alembic_v2_report_revisions.py` checks the revision
file. `tests/integration/test_alembic_v2_saved_report_current_runs.py`, which the
Alembic v2 check runs, compares the revision and its downgrade with the
parent schema and checks each refusal as the database's owner.
`tests/integration/test_v2_saved_report_current_runs.py`, which the
cross-database integration check runs, checks the routes as API v1's runtime
role.

### API v2 report types

Revision `24b571d7d079` (parent `7dcd2cd14330`, ID chosen with `--rev-id`)
was autogenerated after `Report.type`
(`policyengine_api/data/v2/models/reports.py`) became required. Every report
names its type (D1 · 8): `economy`, `household` or `budget_window`, and API v1
reads `reports.type` to tell them apart. The generated part:

- makes `reports.type` NOT NULL;
- adds `ck_reports_type`: the type is one of the three, it is `household`
exactly when `household_id` is set, and `budget_window` exactly when
`budget_window_size` is set. `ck_reports_budget_window_size` already
refuses a report with both.

It has one hand-written data step, before the generated operations: **the
user's explicit migration decision (D1 · 8, 2026-12-03)**, which "Mandatory
generation rule" and "V2 application-data migrations" require. Until D1 · 7a
the simulation service stored a budget window's type as `economy`, and some
reports have no type, so the step sets every report whose type differs from
the one its columns give: `household` with a `household_id`, `budget_window`
with a `budget_window_size`, `economy` otherwise. Any other stored type is
replaced. The operations are otherwise exactly as generated. The downgrade
drops the check and makes the column nullable again; the types the step set
stay, since the earlier schema allows them.

The step's `UPDATE` and the generated `SET NOT NULL` and `ADD CONSTRAINT` each
read the whole of `reports`, which stays locked until the migration
transaction commits, so the simulation service's writes and API v1's reads of
the table wait for them.

Deploying it:

- **The simulation service must write `budget_window` first.**
PolicyEngine/policyengine-sim-api writes every `reports` row. D1 · 7a makes
it store a budget window's type as `budget_window`; that change must be
deployed in an environment before this revision runs there, or the check
refuses the service's next budget window.
- **The simulation service's models.** Its `Report` in
`policyengine-simulation-persistence` keeps `type` nullable and has no
`ck_reports_type` until D1 · 9, which also moves its pinned commit of this
repository. Until then its weekly comparison with the tables this
repository's `master` builds (`public-api-schema-drift.yml`) reports both.
- **Releases from before the revision** work out a report's type from
`household_id` and `budget_window_size`, which the check keeps in agreement
with `type`, so one still serving during a deploy's traffic shift, or
restored by a rollback, answers the same.

`tests/unit/v2/test_alembic_v2_report_revisions.py` checks the revision file
and its one data step. `tests/integration/test_alembic_v2_report_types.py`,
which the Alembic v2 check runs, stores reports at the parent as the
simulation service stored them, checks the types the upgrade sets, compares
the revision and its downgrade with the parent schema, and checks each
refusal as the database's owner.
4 changes: 3 additions & 1 deletion docs/engineering/skills/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,8 @@ 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/v2/test_alembic_v2_dynamic_revisions.py \
tests/unit/v2/test_alembic_v2_household_job_revisions.py tests/unit/test_alembic_workflows.py -q
tests/unit/v2/test_alembic_v2_household_job_revisions.py \
tests/unit/v2/test_alembic_v2_report_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 @@ -645,6 +646,7 @@ uv run --frozen pytest \
tests/unit/v2/test_alembic_v2_revisions.py \
tests/unit/v2/test_alembic_v2_dynamic_revisions.py \
tests/unit/v2/test_alembic_v2_household_job_revisions.py \
tests/unit/v2/test_alembic_v2_report_revisions.py \
tests/unit/test_readiness.py \
tests/unit/test_cloud_run_deploy_scripts.py \
tests/unit/test_migration_contract_artifacts.py \
Expand Down
7 changes: 6 additions & 1 deletion docs/migration/stage-12a-user-login.md
Original file line number Diff line number Diff line change
Expand Up @@ -727,7 +727,12 @@ detailed-save `simulation_id` or `report_id` beside the v1
`budget_window_years`, or null for a report without a window of two or more
years (a saved report stores a one-year window as null). Anything else is
400, on create and on any update naming `report_id` or
`budget_window_years`; it is read in the write's transaction. A saved v1
`budget_window_years`. The write reads the report it names once, in its
transaction, and checks the window and any `current_run_id` against that
read: on create when it names one, and on an update that supplies
`report_id`, `budget_window_years` or `current_run_id`. An update that
supplies one of the last two without `report_id` reads the report the saved
report already names, and answers 404 if the country has none. A saved v1
report keeps the `budget_window_years` it is given.

`MeItem` is `{id, user_type, primary_country, first_name, last_name, email,
Expand Down
73 changes: 73 additions & 0 deletions migrations/v2/versions/24b571d7d079_require_each_report_s_type.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
"""require each report's type

Revision ID: 24b571d7d079
Revises: 7dcd2cd14330
Create Date: 2026-12-03 22:58:07.202943
Generation: uv run alembic -c alembic-v2.ini revision --autogenerate --rev-id 24b571d7d079

Makes every report name its type (D1 · 8): reports.type becomes NOT NULL,
and ck_reports_type requires it to be economy, household or budget_window,
with a household report naming its household and a budget window having a
size, of one year or more. The ID was chosen with --rev-id; the operations
are exactly as generated.

The data step before them is hand-written: the user's explicit migration
decision for D1 · 8 (2026-12-03), which the generated-only rule for revisions
requires. Until D1 · 7a the simulation service stored a budget window's type
as economy, and a report may have no type, so the step sets every report
whose type differs from the one its household_id and budget_window_size give
to that type. The simulation service writes budget_window from D1 · 7a on,
which must be deployed before this revision runs, or its next budget window
would fail the check. The downgrade drops the check and makes the column
optional again; the types the step set stay, since the earlier schema
allows them.
"""

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
import sqlmodel


revision: str = '24b571d7d079'
down_revision: Union[str, None] = '7dcd2cd14330'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
# Approved hand-written data step (the user's migration decision, D1 · 8,
# 2026-12-03): set each report's type from the columns its kind sets,
# before the generated operations require it and check it.
reports = sa.table(
"reports",
sa.column("type", sa.String),
sa.column("household_id", sa.Uuid),
sa.column("budget_window_size", sa.Integer),
)
type_from_columns = sa.case(
(reports.c.household_id.is_not(None), "household"),
(reports.c.budget_window_size.is_not(None), "budget_window"),
else_="economy",
)
op.execute(
reports.update()
.where(reports.c.type.is_distinct_from(type_from_columns))
.values(type=type_from_columns)
)
# ### commands auto generated by Alembic - please adjust! ###
op.alter_column('reports', 'type',
existing_type=sa.VARCHAR(length=128),
nullable=False)
op.create_check_constraint(op.f('ck_reports_type'), 'reports', "type IN ('economy', 'household', 'budget_window') AND (type = 'household') = (household_id IS NOT NULL) AND (type = 'budget_window') = (budget_window_size IS NOT NULL)")
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(op.f('ck_reports_type'), 'reports', type_='check')
op.alter_column('reports', 'type',
existing_type=sa.VARCHAR(length=128),
nullable=True)
# ### 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 = "7dcd2cd14330"
V2_ALEMBIC_HEAD_REVISION = "24b571d7d079"
DISPOSABLE_DATABASE_NAME = "policyengine_v2_alembic_test"
DISPOSABLE_HOSTS = frozenset({"localhost", "127.0.0.1", "::1", "postgres"})
MIGRATION_ROLE = "policyengine_v2_migrator"
Expand Down
28 changes: 25 additions & 3 deletions policyengine_api/data/v2/models/reports.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@

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

import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from sqlmodel import Field, Relationship
from sqlmodel import AutoString, Field, Relationship

from policyengine_api.data.v2.models.base import (
UNFAILED_UNFORCED_RUNS,
Expand Down Expand Up @@ -45,6 +45,13 @@
WithheldAreaCode,
)

# What a report compares, as ``reports.type`` names it: two economy
# simulations, two household simulations, or two economy simulations in each
# year of a budget window.
ReportType = Literal["economy", "household", "budget_window"]
# The SQL list of every report type, for ``ck_reports_type``.
REPORT_TYPES_SQL = ", ".join(f"'{report_type}'" for report_type in get_args(ReportType))

# A budget window compares at most this many years, none after LAST_YEAR.
MAX_BUDGET_WINDOW_YEARS = 75
LAST_YEAR = 2200
Expand Down Expand Up @@ -82,6 +89,12 @@ class Report(TimestampedModel, table=True):
A report is shared by everyone who asks for it, so it names no user. A
report's name and description are on each user's saved report.

``type`` says what the report compares (``ReportType``), and readers take
it from there. The simulation service sets it; ``ck_reports_type`` keeps
it in step with ``household_id`` and ``budget_window_size``. A budget
window's runs are its budget-window runs; any other report's, its report
runs.

The simulation service finds a report by ``definition_key``, the SHA-256
of what it compares (its country, type, each side's policy and dynamic,
the dataset name, region code, year and SPM selection both sides share,
Expand All @@ -104,6 +117,15 @@ class Report(TimestampedModel, table=True):
f"AND year IS NOT NULL AND year + budget_window_size - 1 <= {LAST_YEAR})",
name="ck_reports_budget_window_size",
),
# A report's type is one of the three, and agrees with the columns its
# kind sets: a household report names its household, and a budget
# window has a size (one year or more).
sa.CheckConstraint(
f"type IN ({REPORT_TYPES_SQL}) "
"AND (type = 'household') = (household_id IS NOT NULL) "
"AND (type = 'budget_window') = (budget_window_size IS NOT NULL)",
name="ck_reports_type",
),
sa.Index("ix_reports_country_type_created_at", "country", "type", "created_at"),
sa.UniqueConstraint("key_version", "definition_key"),
sa.CheckConstraint("key_version > 0", name="ck_reports_key_version"),
Expand All @@ -122,7 +144,7 @@ class Report(TimestampedModel, table=True):
)

country: str = Field(max_length=16)
type: str | None = Field(default=None, max_length=128)
type: ReportType = Field(sa_type=AutoString(length=128))
tax_benefit_model_id: UUID = Field(
foreign_key="tax_benefit_models.id",
ondelete="RESTRICT",
Expand Down
34 changes: 3 additions & 31 deletions policyengine_api/data/v2/report_runs.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""Durable report-definition and report-run operations for API v2-alpha.

``set_report_type`` and ``create_report_run`` lock ``reports`` rows with
``SELECT ... FOR UPDATE``, which needs ``UPDATE`` on ``reports``; no managed
role holds it, so none can run them. ``complete_report_run`` sets
``create_report_run`` locks ``reports`` rows with ``SELECT ... FOR
UPDATE``, which needs ``UPDATE`` on ``reports``; no managed role holds it,
so none can run it. ``complete_report_run`` sets
``markdown``, which no managed role may update either. The simulation API
creates and completes reports and report runs with its own code.
"""
Expand Down Expand Up @@ -37,10 +37,6 @@ class ReportRunNotFoundError(LookupError):
"""Raised when a requested durable report run does not exist."""


class ReportTypeImmutableError(ValueError):
"""Raised when a report type change would reinterpret existing runs."""


class ReportRunStateError(ValueError):
"""Raised when a worker transition is invalid for the durable run."""

Expand Down Expand Up @@ -83,30 +79,6 @@ def _locked_report(session: Session, report_id: UUID) -> Report:
return report


def set_report_type(
session: Session,
*,
report_id: UUID,
report_type: str | None,
) -> Report:
"""Set a report's optional type only while it has no execution history."""
report = _locked_report(session, report_id)
if report.type == report_type:
return report

existing_run_id = session.exec(
select(ReportRun.id).where(ReportRun.report_id == report_id).limit(1)
).first()
if existing_run_id is not None:
msg = "report type is immutable after the first report run"
raise ReportTypeImmutableError(msg)

report.type = report_type
session.add(report)
session.flush()
return report


def create_report_run(
session: Session,
*,
Expand Down
15 changes: 6 additions & 9 deletions policyengine_api/services/v2/published_reports/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,6 @@
require_unpublished,
require_versions,
)
from policyengine_api.services.v2.stored_reports.transformations import report_kind
from policyengine_api.services.v2.user_reports.database_connectors.reads import (
lock_owned_user_report_row,
read_owned_user_policy_row,
Expand Down Expand Up @@ -211,23 +210,21 @@ def _succeeded_run(session: Session, *, report_id: UUID, run_id: UUID) -> Publis
has no such run, and PublicationRunNotSucceededError unless it has
succeeded.
"""
kind = report_kind(
require_report_row(
publication_reads.read_report_row(session, report_id=report_id),
report_id=report_id,
)
)
report_type = require_report_row(
publication_reads.read_report_row(session, report_id=report_id),
report_id=report_id,
).type
read_status = (
publication_reads.read_budget_window_run_status
if kind == "budget_window"
if report_type == "budget_window"
else publication_reads.read_report_run_status
)
require_succeeded_run(
read_status(session, report_id=report_id, run_id=run_id),
report_id=report_id,
run_id=run_id,
)
return published_run(kind, run_id)
return published_run(report_type, run_id)


class V2PublishedReportService:
Expand Down
Loading
Loading