Skip to content
Draft
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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,6 @@ gha-creds-*.json
.coverage
.coverage.*
coverage.xml

# Hypothesis example database
.hypothesis/
1 change: 1 addition & 0 deletions changelog.d/final-simulation-report-results.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v1 simulation and report updates now preserve complete household results verified against server calculations. Changes to a final result return 409 and repeats leave its saved result and run history unchanged. The server records the producer's version at calculation time, so an older result saved during a rollout remains correctable by the new revision. Unverified results, stale-SPM simulation results, and reports with an active server-started rerun remain correctable. A valid US economy completion can replace malformed historical output. Simulation updates require an integer ID, and report updates also accept decimal-string IDs. Both require non-null output on completion.
40 changes: 33 additions & 7 deletions docs/canonical-spm.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,9 +259,11 @@ the full calculation envelope inside `output`, including its
`spm_provenance`. A JSON-encoded output string is also accepted. This endpoint
validates the one compact SPM receipt strictly before storage. Completed output
that includes the former sibling `spm_config`, an old receipt or a rich receipt
is rejected rather than translated. Null update fields are ignored. The legacy `api_version` input
is ignored; writes record the installed country model version. Top-level `spm`,
even null, returns HTTP 400 `SPM_SETTINGS_UNSUPPORTED` on POST and PATCH.
is rejected rather than translated. Null update fields, and output that decodes
to null, are ignored, and `id` must be an integer. The legacy `api_version` input
is ignored. When the server verifies an output, the saved version comes from the
producing calculation. Top-level `spm`, even null, returns HTTP 400
`SPM_SETTINGS_UNSUPPORTED` on POST and PATCH.

POST, PATCH and `GET /us/simulation/{id}` return the simulation record inside
`result`. Non-string JSON `output` and `simulation_spec_json` are returned as
Expand All @@ -276,10 +278,34 @@ response shapes, has been removed; this section describes them.

HTTP response cache identity includes the normalized selection and model/bundle
versions, and validates certification before reading the cache. The stored
calculated-household cache uses schema version 4, includes the selection in
identity, and stores provenance atomically with the result and its
warnings. Missing, old, rich or mismatched canonical receipts are cache misses
and are recalculated rather than translated.
calculated-household cache uses schema version 5. Its key includes the
producing runtime and the SPM selection. It stores provenance atomically with
the result and its warnings. Older cache entries miss and are recalculated.
Missing, old, rich or mismatched canonical receipts also trigger recalculation.

`PATCH /us/report` accepts an integer report ID or a decimal string and
requires non-null output on completion, including after JSON decoding. An
outdated ID writes to the current report. A successful response keeps the
requested ID.

The server records a digest of the output and the producing revision's versions
when it calculates a saved household. A complete household simulation can
become final when its output matches that evidence and its runtime is current
or newer. The server compares the country model version first, then the
calculation core and bundle versions. A household report can become final when
its output matches every linked simulation's verified result and all results
were produced for the report's cache version. Concurrent requests that create
the same current report reuse one row. Reading a report leaves an active
server-started rerun available to complete. A simulation with stale SPM output
remains correctable.

Once a result is final, an ordinary PATCH cannot correct it. A repeat leaves
the result and its runs unchanged. A change to a final result returns HTTP 409.
Historical results without evidence, economy reports, and outputs the server
cannot verify remain correctable. A proposed US economy completion with invalid
SPM provenance returns HTTP 400 before the conflict check. A valid US economy
completion can replace a historical completed output that fails current
provenance validation.

## Errors

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""Record verified v1 simulation and report outputs

Revision ID: 46dd192b009c
Revises: 7811e0c49301
Create Date: 2026-12-01 01:51:18.999206
"""

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


revision: str = '46dd192b009c'
down_revision: Union[str, None] = '7811e0c49301'
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.add_column('report_outputs', sa.Column('output_verification', sa.JSON(none_as_null=True), nullable=True))
op.add_column('simulations', sa.Column('output_verification', sa.JSON(none_as_null=True), nullable=True))
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('simulations', 'output_verification')
op.drop_column('report_outputs', 'output_verification')
# ### end Alembic commands ###
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""Reserve one v1 report per current identity

Revision ID: c680227beffd
Revises: 46dd192b009c
Create Date: 2026-12-01 02:16:30.875431
"""

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


revision: str = 'c680227beffd'
down_revision: Union[str, None] = '46dd192b009c'
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.add_column('report_outputs', sa.Column('creation_key', sa.CHAR(length=64), nullable=True))
op.create_unique_constraint('uq_report_outputs_creation_key', 'report_outputs', ['creation_key'])
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint('uq_report_outputs_creation_key', 'report_outputs', type_='unique')
op.drop_column('report_outputs', 'creation_key')
# ### end Alembic commands ###
16 changes: 15 additions & 1 deletion policyengine_api/data/v1_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,9 @@ class UserProfile(V1Base):
user_since: Mapped[int] = mapped_column(BigInteger)


LEGACY_SIMULATION_VERSION_LENGTH = 10


class Simulation(V1Base):
"""A v1 simulation of one policy on a household or geography population.

Expand All @@ -304,12 +307,15 @@ class Simulation(V1Base):
__tablename__ = "simulations"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
country_id: Mapped[str] = mapped_column(String(3))
api_version: Mapped[str] = mapped_column(String(10))
api_version: Mapped[str] = mapped_column(String(LEGACY_SIMULATION_VERSION_LENGTH))
population_id: Mapped[str] = mapped_column(String(255))
population_type: Mapped[str] = mapped_column(String(50))
policy_id: Mapped[int]
status: Mapped[str] = mapped_column(String(32), server_default=text("'pending'"))
output: Mapped[Any | None] = mapped_column(JSON(none_as_null=True))
output_verification: Mapped[dict[str, str] | None] = mapped_column(
JSON(none_as_null=True)
)
error_message: Mapped[str | None] = mapped_column(Text)
simulation_spec_json: Mapped[Any | None] = mapped_column(JSON(none_as_null=True))
simulation_spec_schema_version: Mapped[int | None]
Expand All @@ -325,13 +331,21 @@ class ReportOutput(V1Base):
"""

__tablename__ = "report_outputs"
__table_args__ = (
UniqueConstraint("creation_key", name="uq_report_outputs_creation_key"),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
country_id: Mapped[str] = mapped_column(String(3))
simulation_1_id: Mapped[int]
simulation_2_id: Mapped[int | None]
api_version: Mapped[str] = mapped_column(String(10))
# New rows reserve their lookup identity. Historical rows retain their IDs.
creation_key: Mapped[str | None] = mapped_column(CHAR(64))
status: Mapped[str] = mapped_column(String(32), server_default=text("'pending'"))
output: Mapped[Any | None] = mapped_column(JSON(none_as_null=True))
output_verification: Mapped[dict[str, str] | None] = mapped_column(
JSON(none_as_null=True)
)
error_message: Mapped[str | None] = mapped_column(Text)
year: Mapped[str | None] = mapped_column(String(255), server_default=text("'2025'"))
report_kind: Mapped[str | None] = mapped_column(String(64))
Expand Down
58 changes: 41 additions & 17 deletions policyengine_api/routes/report_output_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@

import json
import logging
from contextlib import suppress

import jsonschema
import pydantic
from flask import Blueprint, Response, current_app, request
from werkzeug.exceptions import BadRequest, HTTPException, NotFound
from werkzeug.exceptions import BadRequest, Conflict, HTTPException, NotFound

from policyengine_api.constants import CURRENT_YEAR
from policyengine_api.data.v1_models import ReportOutput
from policyengine_api.services.report_output_service import (
ReportOutputAlreadyCompleteError,
ReportOutputService,
ReportOutputView,
)
Expand All @@ -28,6 +30,7 @@ def _serialize_v1_report_output(view: ReportOutputView) -> dict:
result = {
attribute.key: getattr(report_output, attribute.key)
for attribute in ReportOutput.__mapper__.column_attrs
if attribute.key not in {"output_verification", "creation_key"}
}
if view.response_id is not None:
result["id"] = view.response_id
Expand Down Expand Up @@ -171,19 +174,48 @@ def get_report_output(country_id: str, report_id: int) -> Response:
)


def _normalize_report_update_id(report_id: object) -> int:
"""Read an integer ID or its legacy decimal string spelling."""
if isinstance(report_id, str) and report_id.isascii() and report_id.isdecimal():
with suppress(ValueError):
report_id = int(report_id)
if isinstance(report_id, bool) or not isinstance(report_id, int):
msg = "id must be an integer or a decimal string"
raise BadRequest(msg)
return report_id


def _require_report_update(status: object, output: object) -> None:
"""Raise BadRequest when the update's status and output do not agree."""
if status is not None and status not in [
"pending",
"running",
"complete",
"error",
]:
msg = "status must be 'pending', 'running', 'complete', or 'error'"
raise BadRequest(msg)

if status == "complete" and output is None:
msg = "output is required when status is 'complete'"
raise BadRequest(msg)


@report_output_bp.route("/<country_id>/report", methods=["PATCH"])
@validate_country
def update_report_output(country_id: str) -> Response:
"""Update a report output record with results or error.

An ID stored under an outdated cache version updates the current report that
GET serves for that ID, and the response keeps the requested ID.
A complete household result verified for the report's cache version is final
unless a server-started rerun is active.

Args:
country_id (str): The country ID.

Request body can contain:
- id (int): The report output ID.
- id (int or decimal string): The report output ID.
- status (str): The new status ('pending', 'running', 'complete', or 'error')
- output (dict): The result output (for complete status)
- api_version (str): The API version of the report
Expand All @@ -194,28 +226,18 @@ def update_report_output(country_id: str) -> Response:
if payload is None:
msg = "Payload missing from request"
raise BadRequest(msg)
if not isinstance(payload, dict):
msg = "Update payload must be a JSON object"
raise BadRequest(msg)

# Extract optional fields
status = payload.get("status")
report_id = payload.get("id")
report_id = _normalize_report_update_id(payload.get("id"))
output = payload.get("output")
error_message = payload.get("error_message")
logger.debug("Updating report #%s for country %s", report_id, country_id)

# Validate status if provided
if status is not None and status not in [
"pending",
"running",
"complete",
"error",
]:
msg = "status must be 'pending', 'running', 'complete', or 'error'"
raise BadRequest(msg)

# Validate that complete status has output
if status == "complete" and output is None:
msg = "output is required when status is 'complete'"
raise BadRequest(msg)
_require_report_update(status, output)

try:
view = _require_updated_report_output(
Expand Down Expand Up @@ -244,6 +266,8 @@ def update_report_output(country_id: str) -> Response:
except LookupError:
msg = f"Report #{report_id} not found."
raise NotFound(msg) from None
except ReportOutputAlreadyCompleteError as error:
raise Conflict(str(error)) from None
except HTTPException:
# Let explicit client-error responses (BadRequest/NotFound/etc.) pass
# through without being logged as "Unexpected error".
Expand Down
48 changes: 37 additions & 11 deletions policyengine_api/routes/simulation_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,14 @@
import jsonschema
import pydantic
from flask import Blueprint, Response, current_app, request
from werkzeug.exceptions import BadRequest, HTTPException, NotFound
from werkzeug.exceptions import BadRequest, Conflict, HTTPException, NotFound

from policyengine_api.data.v1_models import Simulation
from policyengine_api.response_factory import _make_error_response
from policyengine_api.services.simulation_service import SimulationService
from policyengine_api.services.simulation_service import (
SimulationAlreadyCompleteError,
SimulationService,
)
from policyengine_api.spm import SPMValidationError
from policyengine_api.utils.payload_validators import validate_country

Expand All @@ -36,6 +39,7 @@ def _serialize_v1_simulation(simulation: Simulation) -> dict:
response = {
attribute.key: getattr(simulation, attribute.key)
for attribute in Simulation.__mapper__.column_attrs
if attribute.key != "output_verification"
}
for field in ("output", "simulation_spec_json"):
value = response.get(field)
Expand Down Expand Up @@ -80,6 +84,23 @@ def _require_simulation_identity(
raise BadRequest(msg)


def _require_simulation_update(
simulation_id: object,
status: object,
output: object,
) -> None:
"""Raise BadRequest for the first invalid field of a simulation update."""
if isinstance(simulation_id, bool) or not isinstance(simulation_id, int):
msg = "id must be an integer"
raise BadRequest(msg)
if status is not None and status not in ["pending", "complete", "error"]:
msg = "status must be 'pending', 'complete', or 'error'"
raise BadRequest(msg)
if status == "complete" and output is None:
msg = "output is required when status is 'complete'"
raise BadRequest(msg)


@simulation_bp.route("/<country_id>/simulation", methods=["POST"])
@validate_country
def create_simulation(country_id: str) -> Response:
Expand Down Expand Up @@ -194,6 +215,9 @@ def get_simulation(country_id: str, simulation_id: int) -> Response:
def update_simulation(country_id: str) -> Response:
"""Update a simulation record with results or error.

A complete, verified household result from the current runtime or a newer
country model is final if its SPM output is current. A repeat leaves it unchanged.

Args:
country_id (str): The country ID.

Expand All @@ -209,6 +233,9 @@ def update_simulation(country_id: str) -> Response:
if payload is None:
msg = "Payload missing from request"
raise BadRequest(msg)
if not isinstance(payload, dict):
msg = "Update payload must be a JSON object"
raise BadRequest(msg)
if (response := _spm_override_response(payload)) is not None:
return response

Expand All @@ -219,15 +246,7 @@ def update_simulation(country_id: str) -> Response:
error_message = payload.get("error_message")
logger.debug("Updating simulation #%s for country %s", simulation_id, country_id)

# Validate status if provided
if status is not None and status not in ["pending", "complete", "error"]:
msg = "status must be 'pending', 'complete', or 'error'"
raise BadRequest(msg)

# Validate that complete status has output
if status == "complete" and output is None:
msg = "output is required when status is 'complete'"
raise BadRequest(msg)
_require_simulation_update(simulation_id, status, output)

try:
simulation = _require_updated_simulation(
Expand Down Expand Up @@ -257,6 +276,13 @@ def update_simulation(country_id: str) -> Response:
except LookupError:
msg = f"Simulation #{simulation_id} not found."
raise NotFound(msg) from None
except SimulationAlreadyCompleteError as error:
current_app.logger.warning(
"Refused to change complete simulation #%s for country %s",
simulation_id,
country_id,
)
raise Conflict(str(error)) from None
except HTTPException:
# Let explicit client-error responses (BadRequest/NotFound/etc.) pass
# through without being logged as "Unexpected error".
Expand Down
Loading
Loading