diff --git a/changelog.d/v2-coordinator-report-fields.added.md b/changelog.d/v2-coordinator-report-fields.added.md new file mode 100644 index 000000000..1e02054dd --- /dev/null +++ b/changelog.d/v2-coordinator-report-fields.added.md @@ -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. diff --git a/docs/engineering/skills/observability.md b/docs/engineering/skills/observability.md index 97a7725ca..71c34966b 100644 --- a/docs/engineering/skills/observability.md +++ b/docs/engineering/skills/observability.md @@ -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. @@ -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 diff --git a/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/report_type.py b/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/report_type.py index a60659a4e..95f994bb2 100644 --- a/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/report_type.py +++ b/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/report_type.py @@ -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" diff --git a/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/stage12_execution/report_inputs.py b/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/stage12_execution/report_inputs.py index da65cad2f..7ef95f1be 100644 --- a/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/stage12_execution/report_inputs.py +++ b/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/stage12_execution/report_inputs.py @@ -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 ( @@ -164,6 +169,10 @@ 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 @@ -171,6 +180,15 @@ class ReportExecutionInput(StrictContractModel): 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: diff --git a/libs/policyengine-simulation-contract/tests/test_stage12_budget_window_years.py b/libs/policyengine-simulation-contract/tests/test_stage12_budget_window_years.py index fded1c590..d1ba94469 100644 --- a/libs/policyengine-simulation-contract/tests/test_stage12_budget_window_years.py +++ b/libs/policyengine-simulation-contract/tests/test_stage12_budget_window_years.py @@ -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, @@ -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() diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/budget_window_submissions.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/budget_window_submissions.py index 59e42ebb3..c546417a1 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/budget_window_submissions.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/budget_window_submissions.py @@ -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 @@ -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, @@ -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] diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_calculation_inputs.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_calculation_inputs.py index 2d84713f0..861d740bc 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_calculation_inputs.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_calculation_inputs.py @@ -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 @@ -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, @@ -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( diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_reruns.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_reruns.py index 2f60b0461..4200a6aa2 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_reruns.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_reruns.py @@ -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, @@ -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, @@ -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, @@ -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, diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_submissions.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_submissions.py index aa0f3a6ae..10b65c9da 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_submissions.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_submissions.py @@ -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, @@ -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, diff --git a/projects/policyengine-simulation-entry/tests/test_budget_window_submissions.py b/projects/policyengine-simulation-entry/tests/test_budget_window_submissions.py index 38f0037c3..1b6bcc35e 100644 --- a/projects/policyengine-simulation-entry/tests/test_budget_window_submissions.py +++ b/projects/policyengine-simulation-entry/tests/test_budget_window_submissions.py @@ -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}) diff --git a/projects/policyengine-simulation-entry/tests/test_economy_calculation_inputs.py b/projects/policyengine-simulation-entry/tests/test_economy_calculation_inputs.py index c205612db..69b97f5d9 100644 --- a/projects/policyengine-simulation-entry/tests/test_economy_calculation_inputs.py +++ b/projects/policyengine-simulation-entry/tests/test_economy_calculation_inputs.py @@ -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, @@ -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) @@ -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, diff --git a/projects/policyengine-simulation-entry/tests/test_economy_reruns.py b/projects/policyengine-simulation-entry/tests/test_economy_reruns.py index cb523b1ea..a312135e2 100644 --- a/projects/policyengine-simulation-entry/tests/test_economy_reruns.py +++ b/projects/policyengine-simulation-entry/tests/test_economy_reruns.py @@ -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() @@ -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) diff --git a/projects/policyengine-simulation-entry/tests/test_economy_submissions.py b/projects/policyengine-simulation-entry/tests/test_economy_submissions.py index cbb85cccc..943b688e3 100644 --- a/projects/policyengine-simulation-entry/tests/test_economy_submissions.py +++ b/projects/policyengine-simulation-entry/tests/test_economy_submissions.py @@ -238,6 +238,21 @@ def test_a_side_whose_run_already_exists_is_named_and_answered_reused() -> None: assert created.baseline_simulation_run_id == REUSED.simulation_run_id +def test_a_report_is_started_as_a_single_year_report() -> None: + """Its request names no report type, which the coordinator reads as single-year.""" + store = FakeStore( + found_report=_found_report(run_inserted=True, status=ReportRunStatus.PENDING) + ) + caller = FakeCaller() + + _submit_report(service(store, caller=caller)) + + payload = caller.report_runs[0][1] + assert "report_type" not in payload + report = ReportExecutionInput.model_validate(payload) + assert getattr(report, "report_type", None) == "single_year" + + def test_the_same_policy_on_both_sides_names_one_simulation_run_twice() -> None: store = FakeStore() caller = FakeCaller() diff --git a/projects/policyengine-simulation-executor/src/modal/v2_app.py b/projects/policyengine-simulation-executor/src/modal/v2_app.py index e33649777..b769daaa8 100644 --- a/projects/policyengine-simulation-executor/src/modal/v2_app.py +++ b/projects/policyengine-simulation-executor/src/modal/v2_app.py @@ -507,7 +507,9 @@ def coordinate_report( record; a ``production_function_call_id`` in its ``context`` marks a shadow run whose result is compared with that production job's. A report run or evaluation record another call holds, or one already finished, - returns a ``deduplicated`` marker instead. + returns a ``deduplicated`` marker instead. Its record names the report's + country, region, breakdown, scope, year and report type, as API v1's run + records do, and the app and .py version serving it, as the workers' do. """ coordinator_invocation_id = modal.current_function_call_id() if coordinator_invocation_id is None: @@ -518,6 +520,7 @@ def coordinate_report( service_role="stage12_report_coordinator", platform="modal", environment=os.getenv("MODAL_ENVIRONMENT", "local"), + service_version=RESOLVED_BUNDLE.bundle.policyengine_version, ) stage_plan = ( STAGE12_SHADOW_REPORT_STAGES @@ -530,11 +533,13 @@ def coordinate_report( stage_plan.name(Stage.STAGE12_COORDINATOR_EXECUTION), attributes={ "runner_name": "stage12", + "modal_app_name": APP_NAME, "execution_mode": ( "shadow" if context.get("production_function_call_id") else "authoritative" ), + **stage12_runtime.report_record_attributes(payload), **stage12_runtime.operation_record_attributes( "report_runs", stage12_runtime.report_run_named_by(context), diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/__init__.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/__init__.py index f8b574159..5b84566c2 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/__init__.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/__init__.py @@ -30,6 +30,7 @@ from .household_report_recording import run_household_report from .operation_records import ( operation_record_attributes, + report_record_attributes, report_run_named_by, row_id_or_none, simulation_run_named_by, @@ -88,6 +89,7 @@ "merge_segment_results", "operation_record_attributes", "redacted_failure_detail", + "report_record_attributes", "report_run_named_by", "row_id_or_none", "run_household_job", diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/operation_records.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/operation_records.py index 366069de9..1c6c13ceb 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/operation_records.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/operation_records.py @@ -18,6 +18,11 @@ Modal call. So does a US region-group segment of a cliff calculation: the segment's record can name only a simulation run, and its cliff result is named by the simulation worker's operation, which its trace context leads to. + +A coordinator's operation also names the report it runs, read from its own +request, under the attribute names API v1's ``run_simulation`` records use: +``country``, ``region``, ``breakdown``, ``scope``, ``simulation_year`` and +``report_type`` (``report_record_attributes``). """ from __future__ import annotations @@ -26,10 +31,17 @@ from typing import Literal from uuid import UUID +from policyengine_simulation_contract.local_area_breakdown import ( + LOCAL_AREAS_BREAKDOWN, +) +from policyengine_simulation_contract.stage12_execution import ReportExecutionInput from policyengine_simulation_observability.log_records import ( MODAL_CALL_ID_ATTRIBUTE, database_row_attributes, ) +from pydantic import ValidationError + +from .local_area_datasets import is_local_area_report # The tables a v2 Modal function's call works on. OperationTable = Literal[ @@ -54,6 +66,44 @@ def operation_record_attributes( return attributes +def report_record_attributes(payload: object) -> dict[str, str | int]: + """Return what a coordinator call's record names about the report it runs. + + Read from the call's own request, under API v1's ``run_simulation`` + attribute names and values: the country, the region code (``us``, + ``state/ca``), the scope (``macro`` for a dataset's population, + ``household`` for one household), the simulation year, the report type + (``single_year``, or ``budget_window_year`` for one year of a budget + window) and, for a UK report on the local-area dataset, the + ``local_areas`` breakdown. A request that can't be read names none of + them: the coordinator refuses it itself, and telemetry never fails a + call. + """ + try: + report = ReportExecutionInput.model_validate(payload) + except ValidationError: + return {} + simulation = report.baseline + attributes: dict[str, str | int] = { + "country": simulation.geography.country, + "region": simulation.geography.region, + "scope": "macro" if simulation.population.kind == "dataset" else "household", + "simulation_year": simulation.year, + "report_type": report.report_type, + } + if _is_local_area_report(report): + attributes["breakdown"] = LOCAL_AREAS_BREAKDOWN + return attributes + + +def _is_local_area_report(report: ReportExecutionInput) -> bool: + """Whether ``report`` is on the local-area dataset; False if unreadable.""" + try: + return is_local_area_report(report) + except Exception: # noqa: BLE001 # telemetry never fails a call; aggregation decides it again + return False + + def row_id_or_none(value: object) -> UUID | None: """Return ``value`` as a UUID, or None when it is missing or not a UUID. diff --git a/projects/policyengine-simulation-executor/tests/test_v2_coordinator_record.py b/projects/policyengine-simulation-executor/tests/test_v2_coordinator_record.py new file mode 100644 index 000000000..90b1e358e --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_v2_coordinator_record.py @@ -0,0 +1,323 @@ +"""Tests that a v2 coordinator call's record names the report it runs. + +API v1's ``run_simulation`` records name each run's country, region, +breakdown, scope, simulation year, report type and .py version, which the +run-time tracker's weekly copy reads. A v2 coordinator call names the same, +under the same attribute names, from its own request: the report's year, +geography and dataset, and the request's ``report_type``, which the +simulation service sets on each year of a budget window. Its runtime carries +the app's .py version as its service version, and its operation names the +Modal app, as the v2 simulation workers' do. +""" + +from __future__ import annotations + +import importlib +import importlib.metadata +import sys +from contextlib import contextmanager +from uuid import UUID + +import pytest +from fixtures.fake_modal import install_fake_modal +from policyengine_simulation_contract.stage12_execution import ( + BundleProvenance, + CountryId, + DatasetArtifactMediaType, + DatasetArtifactReference, + DatasetPopulationInput, + DatasetProvenance, + GeographySelection, + ReportAggregate, + ReportExecutionInput, + SimulationExecutionInput, + SimulationRole, +) +from policyengine_simulation_executor import stage12_runtime +from policyengine_simulation_executor.stage12_runtime import ( + local_area_datasets, + operation_records, +) + +COORDINATOR_RESULT = {"ok": True} +REPORT_RUN_ID = UUID("00000000-0000-4000-8000-0000000000a1") +LOCAL_AREA_DATASET = "microcosm_uk_2024_25_dense" +# The attributes this change adds to the coordinator's record. +REPORT_ATTRIBUTE_NAMES = ( + "country", + "region", + "breakdown", + "scope", + "simulation_year", + "report_type", +) + + +class _OperationRecordingRuntime: + """Keeps the attributes each operation opens with.""" + + def __init__(self) -> None: + self.operation_attributes: list[dict] = [] + + def set_context(self, **_attributes: object) -> None: + return None + + def capture_context(self) -> dict: + return {} + + @contextmanager + def operation(self, _name, *, attributes, **_keywords): + self.operation_attributes.append(dict(attributes)) + yield + + def shutdown(self) -> None: + return None + + +@pytest.fixture +def v2_app(monkeypatch): + """Import the v2 app afresh, with the coordinator's work stubbed.""" + install_fake_modal(monkeypatch) + sys.modules.pop("src.modal.v2_images", None) + sys.modules.pop("src.modal.v2_app", None) + app = importlib.import_module("src.modal.v2_app") + monkeypatch.setattr(app.modal, "current_function_call_id", lambda: "fc-call") + monkeypatch.setattr( + stage12_runtime, + "coordinate_window_year", + lambda _coordinate, **_keywords: COORDINATOR_RESULT, + ) + yield app + sys.modules.pop("src.modal.v2_images", None) + sys.modules.pop("src.modal.v2_app", None) + + +def _side( + role: SimulationRole, *, country: CountryId, region: str, dataset: str +) -> SimulationExecutionInput: + dataset_uri = f"hf://policyengine/data/{dataset}.h5@revision" + return SimulationExecutionInput( + evaluation_id=REPORT_RUN_ID, + simulation_execution_id=UUID(int=1 if role is SimulationRole.BASELINE else 2), + role=role, + policy={}, + population=DatasetPopulationInput( + artifact=DatasetArtifactReference( + uri=dataset_uri, + media_type=DatasetArtifactMediaType.HDF5, + content_sha256="d" * 64, + ) + ), + year=2026, + geography=GeographySelection(country=country, region=region), + bundle=BundleProvenance( + policyengine_version="6.20.0", + country_package_name=f"policyengine-{country}", + country_package_version="1.0.0", + dataset=DatasetProvenance( + identity=dataset, + uri=dataset_uri, + artifact_revision="revision", + data_package_name=f"policyengine-{country}-data", + data_package_version="1.0.0", + ), + bundle_manifest_sha256="b" * 64, + ), + ) + + +def _report_payload( + *, + country: CountryId = "us", + region: str = "state/ca", + dataset: str = "enhanced_cps_2024", + report_type: str | None = None, +) -> dict: + """Return a coordinator request as the simulation service sends it.""" + payload = ReportExecutionInput( + evaluation_id=REPORT_RUN_ID, + baseline=_side( + SimulationRole.BASELINE, country=country, region=region, dataset=dataset + ), + reform=_side( + SimulationRole.REFORM, country=country, region=region, dataset=dataset + ), + requested_aggregates=tuple(ReportAggregate), + ).model_dump(mode="json") + if report_type is not None: + payload["report_type"] = report_type + return payload + + +def _report_run_context() -> dict: + return {"report_run": {"report_run_id": str(REPORT_RUN_ID)}} + + +def _coordinator_call(v2_app, monkeypatch, payload: dict): + """Call the coordinator; return its result, runtime identity and attributes.""" + runtime = _OperationRecordingRuntime() + runtime_identities: list[dict] = [] + + def configure_recording_runtime(**identity): + runtime_identities.append(identity) + return runtime + + monkeypatch.setattr( + v2_app, "init_process_observability", configure_recording_runtime + ) + result = v2_app.coordinate_report( + payload, _report_run_context(), observability_context=None + ) + [identity] = runtime_identities + [attributes] = runtime.operation_attributes + return result, identity, attributes + + +def test_the_coordinator_call_names_its_app_and_py_version(v2_app, monkeypatch): + _, identity, attributes = _coordinator_call(v2_app, monkeypatch, _report_payload()) + + # The .py version installed in the coordinator's image, as the workers'. + assert identity.get("service_version") == importlib.metadata.version("policyengine") + # The service name stays the coordinator's, as existing queries expect. + assert identity["service_name"] == "policyengine-stage12-coordinator" + assert attributes.get("modal_app_name") == v2_app.APP_NAME + + +def test_the_coordinator_record_names_the_reports_country_region_year_and_scope( + v2_app, monkeypatch +): + result, _, attributes = _coordinator_call(v2_app, monkeypatch, _report_payload()) + + assert result == COORDINATOR_RESULT + assert {name: attributes.get(name) for name in REPORT_ATTRIBUTE_NAMES} == { + "country": "us", + "region": "state/ca", + "breakdown": None, + "scope": "macro", + "simulation_year": 2026, + "report_type": "single_year", + } + # A report on a region's own dataset names no breakdown, as API v1's do. + assert "breakdown" not in attributes + # The attributes the record named before stay as they were. + assert attributes["runner_name"] == "stage12" + assert attributes["execution_mode"] == "authoritative" + assert attributes["database_row_id"] == str(REPORT_RUN_ID) + + +def test_a_budget_window_years_record_names_its_report_type(v2_app, monkeypatch): + _, _, attributes = _coordinator_call( + v2_app, monkeypatch, _report_payload(report_type="budget_window_year") + ) + + assert attributes.get("report_type") == "budget_window_year" + + +def _route_uk_areas_to_the_local_area_dataset(monkeypatch) -> None: + monkeypatch.setattr(local_area_datasets, "uk_area_regions_routed", lambda: True) + monkeypatch.setattr( + local_area_datasets, "routed_uk_area_dataset_name", lambda: LOCAL_AREA_DATASET + ) + + +def test_a_uk_local_area_reports_record_names_api_v1s_breakdown(v2_app, monkeypatch): + """A report on the local-area dataset is API v1's ``local_areas`` breakdown.""" + _route_uk_areas_to_the_local_area_dataset(monkeypatch) + + _, _, attributes = _coordinator_call( + v2_app, + monkeypatch, + _report_payload(country="uk", region="uk", dataset=LOCAL_AREA_DATASET), + ) + + assert ( + attributes.get("country"), + attributes.get("region"), + attributes.get("breakdown"), + ) == ("uk", "uk", "local_areas") + + +def test_a_uk_wide_report_on_its_own_dataset_names_no_breakdown(v2_app, monkeypatch): + _route_uk_areas_to_the_local_area_dataset(monkeypatch) + + _, _, attributes = _coordinator_call( + v2_app, + monkeypatch, + _report_payload(country="uk", region="uk", dataset="enhanced_frs_2023_24"), + ) + + assert (attributes.get("country"), attributes.get("region")) == ("uk", "uk") + assert "breakdown" not in attributes + + +def test_a_request_that_cannot_be_read_still_runs_naming_none_of_them( + v2_app, monkeypatch +): + """Telemetry never fails a call: the coordinator itself refuses the request.""" + result, _, attributes = _coordinator_call( + v2_app, monkeypatch, {"contract_version": 1} + ) + + assert result == COORDINATOR_RESULT + assert not set(REPORT_ATTRIBUTE_NAMES) & set(attributes) + assert attributes["runner_name"] == "stage12" + + +def test_a_local_area_check_that_fails_still_runs_naming_no_breakdown( + v2_app, monkeypatch +): + """The coordinator decides the local-area work again when it aggregates.""" + + def failing_local_area_check(_report): + message = "release manifest unreadable" + raise RuntimeError(message) + + monkeypatch.setattr( + operation_records, "is_local_area_report", failing_local_area_check + ) + + result, _, attributes = _coordinator_call( + v2_app, + monkeypatch, + _report_payload(country="uk", region="uk", dataset=LOCAL_AREA_DATASET), + ) + + assert result == COORDINATOR_RESULT + assert "breakdown" not in attributes + assert (attributes.get("country"), attributes.get("region")) == ("uk", "uk") + + +def test_the_report_attributes_reach_the_operation_record( + v2_app, monkeypatch, recorded_observability_runtime +): + runtime, written_records = recorded_observability_runtime + monkeypatch.setattr(v2_app, "init_process_observability", lambda **_: runtime) + _route_uk_areas_to_the_local_area_dataset(monkeypatch) + + v2_app.coordinate_report( + _report_payload( + country="uk", + region="uk", + dataset=LOCAL_AREA_DATASET, + report_type="budget_window_year", + ), + _report_run_context(), + observability_context=None, + ) + + [completion] = [ + record + for record in written_records + if record.get("event.name") == "operation.completed" + ] + # Read after the package's attribute filter, which drops some key names. + recorded = completion["attributes"] + assert {name: recorded.get(name) for name in REPORT_ATTRIBUTE_NAMES} == { + "country": "uk", + "region": "uk", + "breakdown": "local_areas", + "scope": "macro", + "simulation_year": 2026, + "report_type": "budget_window_year", + } + assert recorded.get("modal_app_name") == v2_app.APP_NAME