Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
9a93c25
Add failing tests for the one-time saved-record migration command
anth-volk Nov 27, 2026
cf54eb4
Add a failing test that CI runs the saved-record migration's tests
anth-volk Nov 27, 2026
6956971
Add the one-time command that migrates saved records' API v1 references
anth-volk Nov 27, 2026
b82d621
Add failing tests for the migration's sample comparison
anth-volk Nov 27, 2026
256a6c2
Add the migration's sample comparison of reports' results with API v1's
anth-volk Nov 27, 2026
4051b36
Name API v1 and API v2 in full in the saved-record migration
anth-volk Nov 30, 2026
c311302
Add failing tests for the migration's --kind filter
anth-volk Nov 30, 2026
7b87054
Add the migration's --kind filter
anth-volk Nov 30, 2026
6978bd6
Add failing tests for review round 1's findings
anth-volk Nov 30, 2026
4532537
Fix review round 1's findings in the saved-record migration
anth-volk Nov 30, 2026
de660ac
Add failing tests for review round 2's quality findings
anth-volk Nov 30, 2026
5bd6345
Fix review round 2's quality findings in the saved-record migration
anth-volk Nov 30, 2026
4fd1abe
Merge remote-tracking branch 'origin/master' into v2plan/d4-1-migrati…
anth-volk Nov 30, 2026
16066db
Fix the three guard tests the saved-record migration failed in CI
anth-volk Nov 30, 2026
86e93e8
Add a failing test for read-only role sessions
anth-volk Nov 30, 2026
25812c6
Fold read-only role sessions into v2_role_sessions
anth-volk Nov 30, 2026
3efc5fe
Merge branch 'master' of https://github.com/PolicyEngine/policyengine…
anth-volk Nov 30, 2026
c94595c
Add failing tests for sending migrated reports to the simulation service
anth-volk Dec 1, 2026
0593250
Send migrated reports to the simulation service without starting a run
anth-volk Dec 1, 2026
586fb67
Add failing tests for review round 3's findings on the report client
anth-volk Dec 1, 2026
ef0f38e
Fix review round 3's findings on the report client
anth-volk Dec 1, 2026
cdd70d5
Add a failing test: API v1 loads without the run-free report create
anth-volk Dec 1, 2026
9c978c7
Revert "Add a failing test: API v1 loads without the run-free report …
anth-volk Dec 1, 2026
d33259f
Pin the simulation client release with the run-free report create
anth-volk Dec 1, 2026
0e274f8
Merge master into the migration command branch
anth-volk Dec 1, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/v2-integration-check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,8 @@ jobs:
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_dynamic_parameter_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, user types and published reports
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 tests/integration/test_v2_published_reports.py
- name: Test signed-in identity provisioning, user associations, saved detailed-save records, user types, published reports and the one-time migration of saved records
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 tests/integration/test_v2_published_reports.py tests/integration/test_v2_saved_record_migration.py tests/integration/test_v2_saved_record_migration_failures.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
run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_stage12_comparison_persistence.py tests/integration/test_v2_simulation_role_privileges.py tests/integration/test_v2_shared_report_rows.py tests/integration/test_v2_privilege_reconciliation.py tests/integration/test_v2_migration_target_persistent.py tests/integration/test_database_sessions.py
- name: Test v2 household persistence, immediate v1 copying, household calculation reads and household reports
Expand Down
1 change: 1 addition & 0 deletions changelog.d/saved-record-migration.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add API v1's one-time command that gives saved reforms, saved households and saved reports holding only an API v1 reference their API v2 records, splitting each API v1 policy's model assumptions into a dynamic, with a dry run, a mode that drops parameters the running catalog lacks, and a closing check. Each saved report's report is found or created through the simulation service's `POST /reports/without-run`, which starts no run.
2 changes: 1 addition & 1 deletion docs/engineering/skills/alembic-migrations.md
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ integration fixtures built on it (`tests/integration/conftest.py`):
| Function or fixture | What it gives or does |
| --- | --- |
| `v2_owner_sessions(url)`; fixture `v2_owner_sessions` | Session factories of the disposable v2 PostgreSQL database's owner, its superuser. |
| `v2_role_sessions(url, role)`; fixture `v2_sessions_as_role(role)` | Session factories whose every connection starts as `role` (PostgreSQL's `role` startup option), so every statement is checked against its privileges. |
| `v2_role_sessions(url, role, *, read_only=False)`; fixture `v2_sessions_as_role(role)` | Session factories whose every connection starts as `role` (PostgreSQL's `role` startup option), so every statement is checked against its privileges. With `read_only`, every transaction is READ ONLY, as in a command's `unpooled_v2_read_only_sessions`. |
| `v1_sessions(url)`; fixture `v1_sessions` | API v1's Session factories of the disposable MySQL database. |
| `sqlite_v2_sessions(foreign_keys=False)` | Session factories of a new in-memory SQLite copy of the v2 schema, whose savepoints behave as on PostgreSQL (Python 3.12's sqlite3 `autocommit=False`); with `foreign_keys`, SQLite enforces the foreign keys. |
| `sqlite_v1_sessions(json_serializer=None)` | API v1's Session factories of a new in-memory SQLite copy of its schema, with SQLite numbering policies. |
Expand Down
260 changes: 260 additions & 0 deletions policyengine_api/libs/simulation_reports_without_runs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,260 @@
"""Find or create the saved-record migration's reports, starting no run (D4 · 1).

The one-time saved-record migration gives each saved report that holds only
an API v1 report output the API v2 report the simulation service finds or
creates for that output's definition. ``SimulationServiceReportSubmitter``
sends the definition to the service's ``POST /reports/without-run``
(D4 · 0). The route looks the report up by the key ``POST /reports`` uses,
and creates the report and its simulations when none matches, but starts no
run: app v3 starts a report's first run through
``POST /v2/reports/{report_id}/runs`` when someone opens it.

The request body is the one API v1's ``POST /v2/reports`` sends the service
for the same report, built from the same creation inputs by
``policyengine_api.libs.simulation_reports``. An economy report asks for no
cliff impacts, which this route refuses.

The route finds a report it created by its definition, so sending the same
definition again creates nothing more. Every answer but a found or created
report and a refusal therefore raises ReportSubmissionUnavailableError, which
leaves the saved report on its API v1 reference for the command's next run to
send again: the service unreachable, unavailable or failing, a proxy's answer
in its place, an answer lost after the request was sent, or a created answer
that can't be read. Such an error names the status, and the service's code
when that is a fixed identifier, never the service's reason, which may be an
exception's text. A 400 or 422 raises ReportSubmissionRefusedError with that
code, or the status without one, and the service's reason. A definition the
creation inputs refuse is refused before anything is sent.
"""

from __future__ import annotations

from typing import TYPE_CHECKING, Any
from uuid import UUID

from pydantic import ValidationError

from policyengine_api.libs.simulation_service_answers import (
CREATED_STATUSES,
REFUSAL_STATUSES,
AnswerModel,
Refusal,
SimulationAnswer,
fixed_identifier_code,
parsed_body,
refusal_reason,
send_to_simulation_service,
simulation_service_http_client,
status_and_code,
)
from policyengine_api.libs.simulation_service_operations import (
post_report_without_run,
)
from policyengine_api.services.v2.saved_record_migration.types import (
ApiV2ReportKind,
)
from policyengine_api.services.v2.saved_record_migration.validators import (
ReportSubmissionRefusedError,
ReportSubmissionUnavailableError,
)
from policyengine_api.services.v2.simulation_service.types import (
BudgetWindowReportCreationInput,
EconomyReportCreationInput,
HouseholdReportCreationInput,
SimulationServiceAnswerUnreadableError,
SimulationServiceUnavailableError,
)

if TYPE_CHECKING:
import httpx

from policyengine_api.services.v2.saved_record_migration.types import (
ApiV2ReportDefinition,
PolicySide,
)

# The route's path, which tests check requests against. The generated
# operation holds its own copy, which it sends the request to.
REPORTS_WITHOUT_RUN_PATH = "/reports/without-run"
# The code of a definition the creation inputs refuse before it is sent.
INVALID_REPORT_DEFINITION = "invalid_report_definition"
# What to do after an answer lost once the request may have arrived.
SEND_AGAIN = "Running the command again finds the report it created by its definition."
NO_READABLE_REASON = "the simulation service gave no readable reason"


class _ReportWithoutRun(AnswerModel):
"""The found or created report's answer, of which only its ID is read."""

report_id: UUID


def _policy_choice(side: PolicySide) -> dict[str, UUID | None]:
return {"policy_id": side.policy_id, "dynamic_id": side.dynamic_id}


def _invalid_fields(error: ValidationError) -> str:
"""Return each field the creation input refuses and why, on one line.

A refusal of the whole definition, such as a budget window ending after
the last year stored, names the definition.
"""
return "; ".join(
f"{'.'.join(str(part) for part in detail['loc']) or 'definition'}: "
f"{detail['msg']}"
for detail in error.errors()
)


def _report_sides(
definition: ApiV2ReportDefinition,
) -> tuple[dict[str, UUID | None], dict[str, UUID | None]]:
"""Return an economy report's or budget window's baseline and reform.

Raise ValueError when it has no reform, which the migration never builds.
"""
if definition.reform is None:
msg = (
f"the {definition.kind.value} report has no reform; the migration "
"gives every economy report and budget window one"
)
raise ValueError(msg)
return _policy_choice(definition.baseline), _policy_choice(definition.reform)


def report_without_run_request(definition: ApiV2ReportDefinition) -> dict[str, Any]:
"""Return the request body for the definition, as ``POST /v2/reports`` builds it.

The definition is checked as API v1's report creation inputs check a
report a caller sends. Raise ValueError for an economy report or budget
window without a reform, which the migration never builds, and
ReportSubmissionRefusedError when the creation inputs refuse the
definition, such as a year outside the years the service stores.
"""
# The project bans importing simulation_reports at module level.
from policyengine_api.libs.simulation_reports import (
budget_window_request,
household_report_request,
report_request,
)

try:
if definition.kind is ApiV2ReportKind.HOUSEHOLD:
return household_report_request(
HouseholdReportCreationInput.model_validate(
{
"country_id": definition.country_id,
"kind": "household",
"household_id": definition.household_id,
"baseline": _policy_choice(definition.baseline),
"reform": (
None
if definition.reform is None
else _policy_choice(definition.reform)
),
}
)
)
baseline, reform = _report_sides(definition)
sides_and_place = {
"country_id": definition.country_id,
"year": definition.year,
"region_code": definition.region_code,
"baseline": baseline,
"reform": reform,
}
if definition.kind is ApiV2ReportKind.BUDGET_WINDOW:
return budget_window_request(
BudgetWindowReportCreationInput.model_validate(
{
**sides_and_place,
"kind": "budget_window",
"budget_window_size": definition.budget_window_size,
}
)
)
return report_request(
EconomyReportCreationInput.model_validate(
{**sides_and_place, "kind": "economy"}
)
)
except ValidationError as error:
msg = f"the report's definition isn't valid: {_invalid_fields(error)}"
raise ReportSubmissionRefusedError(INVALID_REPORT_DEFINITION, msg) from error


def _refusal_text(answer: SimulationAnswer) -> str:
try:
return refusal_reason(Refusal.model_validate_json(answer.content))
except ValidationError:
return NO_READABLE_REASON


def _found_or_created_report_id(answer: SimulationAnswer) -> UUID:
"""Return the ID the answer names, or raise for any other answer."""
if answer.status_code in CREATED_STATUSES:
try:
return _ReportWithoutRun.model_validate_json(answer.content).report_id
except ValidationError as error:
msg = (
f"its answer naming the report can't be read ({answer.status_code}); "
"running the command again finds the report by its definition"
)
raise ReportSubmissionUnavailableError(msg) from error
code = fixed_identifier_code(parsed_body(answer))
if answer.status_code in REFUSAL_STATUSES:
raise ReportSubmissionRefusedError(
code or str(answer.status_code), _refusal_text(answer)
)
msg = (
f"it answered {status_and_code(answer.status_code, code)}; running the "
"command again finds or creates the report by its definition"
)
raise ReportSubmissionUnavailableError(msg)


class SimulationServiceReportSubmitter:
"""Finds or creates the migration's reports through the simulation service."""

def __init__(self, http_client: httpx.Client) -> None:
"""Send requests on ``http_client``, which names the service's base URL."""
self._http_client = http_client

@classmethod
def from_environment(
cls, *, transport: httpx.BaseTransport | None = None
) -> SimulationServiceReportSubmitter:
"""Build the submitter on the configured Cloud Run simulation service.

Raise SimulationServiceUnavailableError when
``SIMULATION_ENTRYPOINT_URL`` is missing or invalid, or the gateway
credentials (``GATEWAY_AUTH_*``) are partly set, or required but
unset. ``transport`` replaces the simulation transport, for tests.
"""
return cls(simulation_service_http_client(transport=transport))

def close(self) -> None:
"""Close the HTTP client; the submitter sends nothing afterwards."""
self._http_client.close()

def find_or_create_report(self, definition: ApiV2ReportDefinition) -> UUID:
"""Return the ID of the report the service found or created; start no run.

Raise ReportSubmissionRefusedError when the definition is refused,
and ReportSubmissionUnavailableError for any other answer but a
found or created report.
"""
body = report_without_run_request(definition)
try:
answer = send_to_simulation_service(
post_report_without_run,
self._http_client,
body,
submit_again_sentence=SEND_AGAIN,
)
except (
SimulationServiceUnavailableError,
SimulationServiceAnswerUnreadableError,
) as error:
raise ReportSubmissionUnavailableError(str(error)) from error
return _found_or_created_report_id(answer)
6 changes: 3 additions & 3 deletions policyengine_api/libs/simulation_service_answers.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,9 +167,9 @@ def simulation_service_http_client(
def submit_again(submission: str, second: str) -> str:
"""Ask the caller to submit the ``submission`` again, which may create a second.

No route finds what a submission created by what it was submitted with,
so the caller cannot check whether the first request created a
``second``.
The routes whose clients use it don't find what a submission created by
what it was submitted with, so the caller cannot check whether the first
request created a ``second``.
"""
return (
f"Submit the {submission} again; if the first request went through, "
Expand Down
26 changes: 23 additions & 3 deletions policyengine_api/libs/simulation_service_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@

``tests/unit/libs/test_simulation_generated_client.py`` checks that each
request is the one API v1 builds by hand and the one the generated operation
builds; run those tests when moving the pin.
builds, and ``tests/unit/libs/test_simulation_reports_without_runs.py`` does
the same for ``POST /reports/without-run``; run those tests when moving the
pin.

To call another of the simulation service's routes, add a function here that
builds the request with that route's generated operation and request model,
Expand All @@ -61,6 +63,9 @@
from policyengine_api_simulation_client.api.default.create_report import (
_get_kwargs as report_request_arguments,
)
from policyengine_api_simulation_client.api.default.create_report_without_run import (
_get_kwargs as report_without_run_request_arguments,
)
from policyengine_api_simulation_client.api.default.create_simulation import (
_get_kwargs as simulation_request_arguments,
)
Expand All @@ -87,8 +92,8 @@

import httpx

# The generated model of each kind of report sent to POST /reports, by the
# body's report_type.
# The generated model of each kind of report sent to POST /reports and
# POST /reports/without-run, by the body's report_type.
REPORT_REQUEST_MODELS: dict[
str,
type[EconomyReportRequest | BudgetWindowReportRequest | HouseholdReportRequest],
Expand Down Expand Up @@ -191,6 +196,21 @@ def post_report(http_client: httpx.Client, body: dict[str, Any]) -> SimulationAn
)


def post_report_without_run(
http_client: httpx.Client, body: dict[str, Any]
) -> SimulationAnswer:
"""Find or create a report, starting no run (``POST /reports/without-run``).

The body is the one ``post_report`` sends for the same report, and its
``report_type`` selects its generated model. Raise what
``send_request_with_body`` raises.
"""
request = REPORT_REQUEST_MODELS[body["report_type"]].from_dict(body)
return send_request_with_body(
http_client, report_without_run_request_arguments(body=request), body
)


def post_report_rerun(
http_client: httpx.Client, report_id: UUID, body: dict[str, Any]
) -> SimulationAnswer:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""The one-time migration of saved records' API v1 references (D4 · 1)."""
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""The policy and household copies the one-time saved-record migration makes."""
Loading
Loading