Skip to content
Open
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/report-type-in-run-records.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Every `run_simulation` log record names its report type in the attribute `report_type`: `budget_window_year` for a year that a budget-window batch starts, and `single_year` for any other request. The children of a segmented run copy it into their records.
23 changes: 23 additions & 0 deletions docs/engineering/skills/observability.md
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,29 @@ from the gateway's submission of the job to the job's start in the worker.
- **Only ISO 8601 times:** the value must be a string with a time zone, as
the gateway sends it. Anything else, a number included, records nothing.

### Annual job report type

`run_simulation` records its request's `report_type`, which names the kind of
report the job belongs to:

- **`budget_window_year`:** one year of a multi-year (budget-window) report.
`build_child_simulation_request` puts it on every year that
`run_budget_window_batch` spawns, for every country and region, whether or
not the year runs in segments.
- **`single_year`:** any other job. The worker adds it to a request that names
no report type, before it records the operation and runs the calculation.
- **A request parameter:** the label is a parameter (`REPORT_TYPE_PARAM` in
`policyengine_simulation_contract.report_type`), not only an attribute, so
the region-group children of a segmented run copy it into their
`run_simulation_segment` records. The calculation ignores it.
- **Callers can't set it:** the gateway's request models refuse fields they
don't declare, and they don't declare `report_type`, so only the batch can
name a job `budget_window_year`.
- **Jobs without it:** records from worker apps deployed before this
attribute, including the years their batches spawn. In those, a
budget-window year shows only as a request with `segmented: false` and no
`job_queue_seconds`.

### Preemptions

Modal delivers a preemption to a running synchronous function, which every
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"""The report type an annual simulation request names for its run record.

The ``run_simulation`` worker records a request's fields as its operation
attributes, so a request's ``report_type`` reaches its run record, and a
segmented run's children copy it into theirs. The budget-window batch names
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.
"""

from __future__ import annotations

REPORT_TYPE_PARAM = "report_type"

# One year inside a multi-year (budget-window) report.
BUDGET_WINDOW_YEAR_REPORT_TYPE = "budget_window_year"
# Any other annual simulation: a single-year report.
SINGLE_YEAR_REPORT_TYPE = "single_year"
19 changes: 19 additions & 0 deletions projects/policyengine-simulation-executor/src/modal/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@
from policyengine_simulation_contract.job_stage_telemetry import (
job_stage_seconds_attribute,
)
from policyengine_simulation_contract.report_type import (
REPORT_TYPE_PARAM,
SINGLE_YEAR_REPORT_TYPE,
)
from policyengine_simulation_executor.hf_access_validation import (
HF_MODAL_SECRET_NAME,
HF_RUNTIME_ENV_NAME,
Expand Down Expand Up @@ -394,6 +398,20 @@ def _without_submission_time(params: dict) -> tuple[dict, object]:
return remaining, submitted_at


def _with_report_type(params: dict) -> dict:
"""Return ``params`` naming its report type: ``single_year`` when it names none.

The budget-window batch names each year it starts ``budget_window_year``;
every other request arrives without a report type. The label goes into
the parameters, not only the run's record, so a segmented run's children
copy it into their records. Parameters that aren't a dict pass through
unchanged, for the calculation to report.
"""
if not isinstance(params, dict) or params.get(REPORT_TYPE_PARAM) is not None:
return params
return {**params, REPORT_TYPE_PARAM: SINGLE_YEAR_REPORT_TYPE}


def _record_queue_seconds(
runtime: "ObservabilityRuntime",
progress: "JobProgressReporter",
Expand Down Expand Up @@ -433,6 +451,7 @@ def _run_simulation(
progress = _job_progress_reporter()
progress.start()
params, submitted_at = _without_submission_time(params)
params = _with_report_type(params)
runtime = _configure_modal_observability(service_role="simulation_worker")

# We deliberately avoid sending full ``params`` or ``result`` blobs to
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
BudgetWindowBatchRequest,
PolicyEngineBundle,
)
from policyengine_simulation_contract.report_type import (
BUDGET_WINDOW_YEAR_REPORT_TYPE,
REPORT_TYPE_PARAM,
)
from src.modal.fanout import build_child_payload

BATCH_ONLY_FIELDS = {
Expand Down Expand Up @@ -105,6 +109,9 @@ def build_child_simulation_request(
context.raw_params,
strip_fields=BATCH_ONLY_FIELDS,
overrides={
# Recorded with the year's run, which the run-times summary then
# leaves out of the single-year rows.
REPORT_TYPE_PARAM: BUDGET_WINDOW_YEAR_REPORT_TYPE,
"time_period": simulation_year,
# Budget-window children stay monolithic for now: a national
# child would otherwise fan out again (years x 21 containers).
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Tests for budget-window batch context helpers."""

import pytest
from policyengine_simulation_contract.gateway_models import (
BudgetWindowBatchRequest,
PolicyEngineBundle,
Expand All @@ -10,10 +11,10 @@
)


def _build_parent_payload():
def _build_parent_payload(*, country="us", region="us"):
request = BudgetWindowBatchRequest(
country="us",
region="us",
country=country,
region=region,
start_year="2026",
window_size=3,
max_parallel=2,
Expand Down Expand Up @@ -92,3 +93,28 @@ def test_build_child_simulation_request_pins_children_monolithic():
)

assert child_request.payload["segmented"] is False


@pytest.mark.parametrize(
("country", "region"),
[("us", "us"), ("us", "state/ca"), ("uk", "uk")],
ids=["us-national", "us-state", "uk"],
)
def test_build_child_simulation_request_marks_every_year_as_a_budget_window_year(
country, region
):
"""Each year's run record names it a year of a multi-year report.

The worker records the request's ``report_type``, and the run-times
summary leaves ``budget_window_year`` records out, whatever the window's
country or region and whether or not the year runs in segments.
"""
_, payload = _build_parent_payload(country=country, region=region)
context = build_batch_context(payload, batch_job_id="parent-123")

child_request = build_child_simulation_request(
context,
simulation_year="2028",
)

assert child_request.payload.get("report_type") == "budget_window_year"
Original file line number Diff line number Diff line change
Expand Up @@ -1254,7 +1254,7 @@ def dispatch(params, *, app_name, runtime, progress):
{"country": "us", JOB_SUBMITTED_AT_PARAM: T0.isoformat()}
)

assert dispatched_params == [{"country": "us"}]
assert dispatched_params == [{"country": "us", "report_type": "single_year"}]

def test__the_operation_record_carries_the_queue_time(
self, modal_app, monkeypatch, recorded_observability_runtime
Expand Down Expand Up @@ -1289,6 +1289,64 @@ def dispatch(_params, *, app_name, runtime, progress):
assert completion["attributes"]["job_queue_seconds"] == 7.25
assert JOB_SUBMITTED_AT_PARAM not in completion["attributes"]

def _run_and_record(
self, modal_app, monkeypatch, recorded_observability_runtime, request
):
"""Run ``request``; return the dispatched parameters and completion record."""
runtime, written_records = recorded_observability_runtime
dispatched_params = []

def dispatch(params, *, app_name, runtime, progress):
dispatched_params.append(params)
return {"ok": True}

self._wire_reporter_started_at(modal_app, monkeypatch, dispatch, started_at=T0)
monkeypatch.setattr(
modal_app,
"_configure_modal_observability",
lambda *, service_role: runtime,
)

modal_app.SimulationWorker().run_simulation(request)

[completion] = [
record
for record in written_records
if record.get("event.name") == "operation.completed"
]
return dispatched_params, completion

def test__a_request_without_a_report_type_runs_as_a_single_year_report(
self, modal_app, monkeypatch, recorded_observability_runtime
):
# Gateway requests carry no report type. The label goes into the
# parameters, so a segmented run's children copy it into their records.
dispatched_params, completion = self._run_and_record(
modal_app,
monkeypatch,
recorded_observability_runtime,
{"country": "us"},
)

assert dispatched_params == [{"country": "us", "report_type": "single_year"}]
assert completion["attributes"]["report_type"] == "single_year"

def test__a_budget_window_year_keeps_its_report_type(
self, modal_app, monkeypatch, recorded_observability_runtime
):
# The budget-window batch labels each year's request.
request = {"country": "us", "report_type": "budget_window_year"}

dispatched_params, completion = self._run_and_record(
modal_app,
monkeypatch,
recorded_observability_runtime,
request,
)

assert dispatched_params == [request]
assert completion["attributes"]["report_type"] == "budget_window_year"

def test__no_call_id_means_no_reporting(self, modal_app, monkeypatch):
def missing_call_id():
msg = "not inside a Modal function call"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,14 @@ def test__strips_v1_style_region_us_from_children(self):
assert "region" not in payload
assert payload["region_group"] == ["state/ca"]

@pytest.mark.parametrize("report_type", ["single_year", "budget_window_year"])
def test__children_copy_the_parents_report_type(self, report_type):
# Each segment's record names the report type of the run it belongs to.
payload = sn.build_group_child_payload(
{**NATIONAL, "report_type": report_type}, ["state/ca"]
)
assert payload["report_type"] == report_type


class FakeCall:
"""A FunctionCall whose result resolves after N polls (or raises).
Expand Down