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
1 change: 1 addition & 0 deletions changelog.d/v2-coordinator-report-fields.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
API v2's report coordinator now names each report's country, region, breakdown, scope, simulation year and report type on its run record, with the Modal app and the .py version serving it, under the attribute names API v1's run records use. The simulation service names each year of a budget window `budget_window_year` in the coordinator's request, as API v1's budget-window batch does, and later years carry it.
54 changes: 53 additions & 1 deletion docs/engineering/skills/observability.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,10 @@ US segment worker, each a class method) also says which
deployment served it, as the versioned app's workers do: its operation's
`modal_app_name` names the v2 app, and its records' `service.version` is the
bundle's policyengine.py version. Its `service.name` stays the worker's, such
as `policyengine-stage12-us-worker`. The v2 coordinator's and household
as `policyengine-stage12-us-worker`. A v2 coordinator's call names its app and
.py version the same way, under the service name
`policyengine-stage12-coordinator`, and its operation also names the report it
runs (see "API v2 coordinator report fields" below). The v2 household
functions' records still carry the observability package's fallback version.

`observability_id` is a canonical UUID string and has diagnostic meaning only.
Expand Down Expand Up @@ -245,6 +248,55 @@ report the job belongs to:
budget-window year shows only as a request with `segmented: false` and no
`job_queue_seconds`.

### API v2 coordinator report fields

A v2 coordinator's call (`coordinate_report`) records the report it runs, read
from its own request (`ReportExecutionInput`), under the attribute names and
values API v1's `run_simulation` records use
(`report_record_attributes` in `stage12_runtime`):

- **`country` and `region`:** the request's country, `us` or `uk`, and its
region code, such as `us`, `state/ca` or `uk`.
- **`scope`:** `macro` for a report on a dataset. A request naming one
household records `household`, but the coordinator's simulation workers
refuse it, so that value appears only on failed calls.
- **`simulation_year`:** the request's year, an integer. API v1's segmented
national runs record it as a string, so cast it before comparing.
- **`report_type`:** `budget_window_year` for one year of a budget window,
otherwise `single_year`. The simulation service sets the request's
`report_type` field on a window's first year, and every later year's request
is copied from an earlier year's (`year_calculation`), so it keeps the
value. The request's JSON leaves the field out when it is `single_year`, so
a v2 app deployed before the field still accepts every single-year report.
This is the run record's report type, not the report's own `type` on API
v2's `reports` row, which names the kind of report.
- **`breakdown`:** `local_areas` for a UK-wide or nation report on the dataset
the release routes the constituency and local-authority regions to,
otherwise absent. The work it names differs between the APIs: an API v1
`local_areas` job computes only the constituency and local-authority
results, with the UK or nation result as a separate job, while an API v2
call on that dataset computes the full report and both area levels. Run
times grouped by `breakdown` compare different work across the two APIs.
- **Which calls are API v2 reports:** shadow calls (`execution_mode: shadow`,
a second calculation of an API v1 job) and operator direct submissions
(`execution_mode: authoritative` with no `database_table`) carry the same
fields, with `single_year`. Household report runs also name
`database_table = report_runs`. Select API v2 report runs by the operation
name `stage12_coordinator_execution` together with
`database_table = report_runs`, not by `execution_mode`.
- **More than one record per report run:** a call that finds its report run
already held by another call, or already finished, returns `deduplicated`
within seconds and writes a successful record with the same fields; a
preempted call's retry writes its own record too. Nothing marks the
deduplicated call's record, so a summary of run times keeps the longest
successful record of each report run (`database_row_id`).
- **Calls without them:** calls served by a v2 app deployed before these
attributes name none of them, and their `service.version` is the
observability package's fallback. A budget window whose first year was
requested before the simulation service sent the field records every year
as `single_year`, including years that run after the deploy, because each
later year's request is copied from an earlier year's.

### Preemptions

Modal delivers a preemption to a running synchronous function, which every
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,23 @@
each year it starts ``budget_window_year``; the worker names every other
request ``single_year``. Callers can't send the field: the gateway's request
models refuse fields they don't declare.

API v2's coordinator request (``ReportExecutionInput``) carries the same
field and values: the simulation service names each year of a budget window
``budget_window_year``, and the coordinator records the request's value on
its run record, ``single_year`` when the request names none.
"""

from __future__ import annotations

from typing import Final, Literal

# The report types a run record names.
ReportType = Literal["single_year", "budget_window_year"]

REPORT_TYPE_PARAM = "report_type"

# One year inside a multi-year (budget-window) report.
BUDGET_WINDOW_YEAR_REPORT_TYPE = "budget_window_year"
BUDGET_WINDOW_YEAR_REPORT_TYPE: Final[ReportType] = "budget_window_year"
# Any other annual simulation: a single-year report.
SINGLE_YEAR_REPORT_TYPE = "single_year"
SINGLE_YEAR_REPORT_TYPE: Final[ReportType] = "single_year"
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@

from pydantic import Field, field_validator, model_validator

from policyengine_simulation_contract.report_type import (
SINGLE_YEAR_REPORT_TYPE,
ReportType,
)

# Models subclass these bases through the package's path, which ruff.toml
# lists as runtime-evaluated; base.py binds them in the package first.
from policyengine_simulation_contract.stage12_execution import (
Expand Down Expand Up @@ -164,13 +169,26 @@ class ReportExecutionInput(StrictContractModel):
roles, and differ only in their policy. Their execution IDs differ, except
in a report that names one simulation run on both sides, whose two inputs
are then the same simulation, policy included.

``report_type`` says whether the report is one year of a budget window
(``budget_window_year``) or a report on its own (``single_year``), as
API v1's run records do; the coordinator records it on its run record.
"""

contract_version: Literal[1] = 1
evaluation_id: UUID
baseline: SimulationExecutionInput
reform: SimulationExecutionInput
requested_aggregates: Annotated[tuple[ReportAggregate, ...], Field(min_length=1)]
# The simulation service names a budget window's first year
# ``budget_window_year``, and every later year's request is copied from
# an earlier year's (``year_calculation``). Left out of the JSON when
# ``single_year``: a v2 application deployed before the field refuses it,
# even with that value, so every other report keeps its JSON.
report_type: ReportType = Field(
default=SINGLE_YEAR_REPORT_TYPE,
exclude_if=lambda value: value == SINGLE_YEAR_REPORT_TYPE,
)

@model_validator(mode="after")
def require_aligned_simulations(self) -> ReportExecutionInput:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@
from uuid import UUID

import pytest
from policyengine_simulation_contract.report_type import (
BUDGET_WINDOW_YEAR_REPORT_TYPE,
SINGLE_YEAR_REPORT_TYPE,
)
from policyengine_simulation_contract.stage12_execution import (
BundleProvenance,
DatasetArtifactMediaType,
Expand Down Expand Up @@ -174,6 +178,50 @@ def test_a_later_years_context_names_no_cliff_result_in_its_json() -> None:
assert "cliff_result_id" not in later_context.model_dump(mode="json")


def test_a_report_naming_no_report_type_is_a_single_year_report() -> None:
"""As API v1's worker names a request without one; its JSON stays as it was.

A v2 application deployed before the field refuses it, even as
``single_year``, so only a budget window's year sends it.
"""
report, _ = _first_year()

assert getattr(report, "report_type", None) == SINGLE_YEAR_REPORT_TYPE
assert "report_type" not in report.model_dump(mode="json")


def test_a_budget_window_years_report_type_reaches_every_later_year() -> None:
"""The simulation service names the first year; every later year copies it."""
report, context = _first_year()
first_year = ReportExecutionInput.model_validate(
{
**report.model_dump(mode="json"),
"report_type": BUDGET_WINDOW_YEAR_REPORT_TYPE,
}
)

later_report, _ = year_calculation(
first_year,
context,
year=2029,
run_ids=LATER_YEAR_RUNS,
created_at=LATER_CREATED_AT,
)

assert later_report.model_dump(mode="json").get("report_type") == (
BUDGET_WINDOW_YEAR_REPORT_TYPE
)


def test_a_report_type_other_than_api_v1s_two_is_refused() -> None:
report, _ = _first_year()

with pytest.raises(ValueError, match="report_type"):
ReportExecutionInput.model_validate(
{**report.model_dump(mode="json"), "report_type": "economy"}
)


def test_nothing_else_differs_between_the_years() -> None:
report, context = _first_year()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@
and their calls recorded. Each year's coordinator starts the next ones when
its year ends. A joined window run is answered as it is.

The first year's coordinator input is built as a single-year report's is;
every later year's is derived from it (``year_calculation``), so all years
are calculated alike. A year Modal refuses fails the window, and so does
The first year's coordinator input is built as a single-year report's is,
naming its report type ``budget_window_year`` as API v1's budget-window batch
names each year; every later year's is derived from it
(``year_calculation``), so all years are calculated alike and carry that
report type. A year Modal refuses fails the window, and so does
the first year when Modal doesn't confirm it in time; the request is then
answered 503 naming the report, as an economy report whose run Modal
refused is. The first years share one wait for Modal, and a later year not
Expand All @@ -32,6 +34,9 @@
from typing import TYPE_CHECKING, Any, Protocol
from uuid import UUID, uuid4

from policyengine_simulation_contract.report_type import (
BUDGET_WINDOW_YEAR_REPORT_TYPE,
)
from policyengine_simulation_contract.stage12_execution import (
ReportExecutionInput,
ReportRunIds,
Expand Down Expand Up @@ -271,6 +276,7 @@ def first_year_calculation(run_ids: ReportRunIds) -> RunCalculation:
run_ids=run_ids,
baseline_policy=inputs.baseline.reform,
reform_policy=inputs.reform.reform,
report_type=BUDGET_WINDOW_YEAR_REPORT_TYPE,
)

proposed_first_year = window.years[0]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
from datetime import datetime
from uuid import UUID

from policyengine_simulation_contract.report_type import ReportType
from policyengine_simulation_contract.stage12_bundle import Stage12Dataset
from policyengine_simulation_contract.stage12_execution import CountryId

Expand Down Expand Up @@ -209,8 +210,13 @@ def report_run_calculation( # noqa: PLR0913 # the runs, both policies and what
run_ids: ReportRunIds,
baseline_policy: dict[str, Any],
reform_policy: dict[str, Any],
report_type: ReportType,
) -> RunCalculation:
"""Return the coordinator's report and context for the report run."""
"""Return the coordinator's report and context for the report run.

``report_type`` is ``budget_window_year`` for a budget window's first
year, whose later years copy it, and ``single_year`` for any other report.
"""
report_run_id = run_ids.report_run_id
report = ReportExecutionInput(
evaluation_id=report_run_id,
Expand All @@ -231,6 +237,7 @@ def report_run_calculation( # noqa: PLR0913 # the runs, both policies and what
policy=reform_policy,
),
requested_aggregates=REPORT_AGGREGATES,
report_type=report_type,
)
context = _context(worker, origin, runs=run_ids)
return RunCalculation(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@
from typing import TYPE_CHECKING, Any, Final, Protocol
from uuid import uuid4

from policyengine_simulation_contract.report_type import (
BUDGET_WINDOW_YEAR_REPORT_TYPE,
SINGLE_YEAR_REPORT_TYPE,
)
from policyengine_simulation_contract.stage12_execution import ReportRunIds
from policyengine_simulation_persistence import (
EconomyRequest,
Expand Down Expand Up @@ -371,6 +375,7 @@ async def rerun_report(
),
baseline_policy=inputs.baseline.reform,
reform_policy=inputs.reform.reform,
report_type=SINGLE_YEAR_REPORT_TYPE,
),
report_id=report_id,
run_id=rerun.run_id,
Expand Down Expand Up @@ -545,6 +550,7 @@ async def _rerun_window(
run_ids=year_run_ids(rerun.years[0]),
baseline_policy=inputs.baseline.reform,
reform_policy=inputs.reform.reform,
report_type=BUDGET_WINDOW_YEAR_REPORT_TYPE,
)
found = await self._create_rerun(
_REPORT,
Expand All @@ -563,6 +569,7 @@ async def _rerun_window(
run_ids=year_run_ids(found_first_year),
baseline_policy=inputs.baseline.reform,
reform_policy=inputs.reform.reform,
report_type=BUDGET_WINDOW_YEAR_REPORT_TYPE,
),
report_id=stored.report_id,
window_run_id=found.window_run.id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
from typing import TYPE_CHECKING, Any, Protocol
from uuid import UUID, uuid4

from policyengine_simulation_contract.report_type import SINGLE_YEAR_REPORT_TYPE
from policyengine_simulation_contract.stage12_execution import ReportRunIds
from policyengine_simulation_observability.log_records import (
database_row_attributes,
Expand Down Expand Up @@ -326,6 +327,7 @@ async def submit_report(
),
baseline_policy=inputs.baseline.reform,
reform_policy=inputs.reform.reform,
report_type=SINGLE_YEAR_REPORT_TYPE,
)
status = await self._start_report_run(
worker,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,18 @@ def test_each_later_year_is_derived_from_the_first() -> None:
assert context == derived_context.model_dump(mode="json")


def test_every_year_of_a_window_is_started_as_a_budget_window_year() -> None:
"""As API v1's batch names each year it starts; later years copy the first's."""
store = FakeWindowStore()
caller = FakeCaller()

_submit(_service(store, caller=caller), budget_window_size=3)

assert [
payload.get("report_type") for (_, payload, _, _) in caller.report_runs
] == ["budget_window_year"] * 3


def test_a_year_names_its_own_years_run_another_report_created() -> None:
"""Answer 8: a window year and a single-year report share runs."""
store = FakeWindowStore(joined_year_runs={(2027, "baseline"): JOINED_RUN_IN_2027})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from economy_fixtures import STATE_DATASET, economy_manifest
from economy_service_fakes import CATALOG, report_request
from household_fixtures import POLICYENGINE_VERSION
from policyengine_simulation_contract.report_type import SINGLE_YEAR_REPORT_TYPE
from policyengine_simulation_contract.stage12_execution import (
ReportAggregate,
ReportExecutionInput,
Expand Down Expand Up @@ -126,6 +127,7 @@ def test_a_report_run_is_named_by_its_run_ids_with_no_evaluation_record() -> Non
run_ids=RUN_IDS,
baseline_policy={},
reform_policy=REFORM,
report_type=SINGLE_YEAR_REPORT_TYPE,
)

report = ReportExecutionInput.model_validate(calculation.payload)
Expand Down Expand Up @@ -179,6 +181,7 @@ def test_the_contexts_the_service_sends_name_no_cliff_result() -> None:
run_ids=RUN_IDS,
baseline_policy={},
reform_policy=REFORM,
report_type=SINGLE_YEAR_REPORT_TYPE,
)
standalone = simulation_run_calculation(
worker,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,19 @@ def test_a_report_with_no_keys_is_rerun_as_forced_runs_on_the_current_versions()
}


def test_a_report_rerun_is_started_as_a_single_year_report() -> None:
"""Its request names no report type, which the coordinator reads as single-year."""
store = FakeRerunStore()
caller = FakeCaller()

_rerun_report(rerun_service(store, caller=caller))

((_, payload, _, _),) = caller.report_runs
assert "report_type" not in payload
report = ReportExecutionInput.model_validate(payload)
assert getattr(report, "report_type", None) == "single_year"


def test_a_forced_rerun_recalculates_both_simulations() -> None:
store = FakeRerunStore()

Expand Down Expand Up @@ -946,6 +959,17 @@ def test_a_budget_window_is_rerun_as_a_new_window_run_and_its_first_years_starte
}


def test_every_year_of_a_window_rerun_is_started_as_a_budget_window_year() -> None:
store = FakeRerunStore(report_definition=STORED_WINDOW)
caller = FakeCaller()

_rerun_report(rerun_service(store, caller=caller, advancer=FakeAdvancer(store)))

assert [
payload.get("report_type") for (_, payload, _, _) in caller.report_runs
] == ["budget_window_year"] * 3


def test_a_forced_window_rerun_recalculates_every_year() -> None:
store = FakeRerunStore(report_definition=STORED_WINDOW)

Expand Down
Loading
Loading