From 55f1046cf563bf4beb2c4d07e90a54050ababc90 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:20:03 +0400 Subject: [PATCH 01/11] Add failing tests for a container start module both Modal apps share The v2 workers need the restore detection and call counter the run_simulation app's workers have. These tests cover that logic as a module both apps can import: each container_start value, the call counter, and a failure to set the attributes raising nothing. Co-Authored-By: Claude Opus 5.5 --- .../tests/test_container_calls.py | 186 ++++++++++++++++++ 1 file changed, 186 insertions(+) create mode 100644 projects/policyengine-simulation-executor/tests/test_container_calls.py diff --git a/projects/policyengine-simulation-executor/tests/test_container_calls.py b/projects/policyengine-simulation-executor/tests/test_container_calls.py new file mode 100644 index 000000000..d2fed0967 --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_container_calls.py @@ -0,0 +1,186 @@ +"""Tests for ``src.modal.container_calls``, which both Modal apps' workers use. + +Each worker call's operation says how the container serving it started +(``container_start``) and which call it is in that container +(``container_call_number``). The module reads both from Modal's environment +variables, as the snapshot hook and each call see them; these tests set those +variables as Modal 1.6.4 does. +""" + +from __future__ import annotations + +import pytest +from conftest import NoOpObservabilityRuntime +from src.modal.container_calls import ContainerCalls, ContainerStart + +# The Modal task IDs of the container that takes the snapshot, and of a +# container restored from it. +SNAPSHOT_TASK_ID = "ta-01SNAPSHOTTING" +RESTORED_TASK_ID = "ta-01RESTORED" +CONTAINER_START_KEYS = {"container_start", "container_call_number"} + + +class _AttributeRecordingRuntime(NoOpObservabilityRuntime): + """Keeps every attribute set on its operation.""" + + def __init__(self) -> None: + self.attributes: dict[str, object] = {} + + def set_context(self, **attributes: object) -> None: + self.attributes.update(attributes) + + +class _AttributeRefusingRuntime(NoOpObservabilityRuntime): + """Fails every attempt to set an attribute, as a broken exporter might.""" + + def set_context(self, **_attributes: object) -> None: + msg = "attribute export failed" + raise RuntimeError(msg) + + +@pytest.fixture(autouse=True) +def _container_without_modal_variables(monkeypatch): + monkeypatch.delenv("MODAL_TASK_ID", raising=False) + monkeypatch.delenv("MODAL_ENABLE_SNAP_RESTORE", raising=False) + + +def _calls_after_snapshot_hook( + monkeypatch, *, snapshot_flag: str | None = "1" +) -> ContainerCalls: + """Run the snapshot hook's record step, as Modal does in a new container. + + Modal's worker sets ``MODAL_ENABLE_SNAP_RESTORE`` to ``1`` in a container + it takes a snapshot from, and leaves it unset in a container of the same + class that starts without snapshots. + """ + monkeypatch.setenv("MODAL_TASK_ID", SNAPSHOT_TASK_ID) + if snapshot_flag is not None: + monkeypatch.setenv("MODAL_ENABLE_SNAP_RESTORE", snapshot_flag) + container_calls = ContainerCalls() + container_calls.record_snapshot_hook() + return container_calls + + +def _restore_into_another_container(monkeypatch) -> None: + """Act as a restore: Modal 1.6.4 sets MODAL_TASK_ID to the new container's ID.""" + monkeypatch.setenv("MODAL_TASK_ID", RESTORED_TASK_ID) + + +def test_a_container_whose_snapshot_hook_never_ran_reports_no_snapshot(monkeypatch): + # A plain Modal function has no snapshot hook. + monkeypatch.setenv("MODAL_TASK_ID", SNAPSHOT_TASK_ID) + + assert ContainerCalls().container_start() is ContainerStart.NO_SNAPSHOT + + +@pytest.mark.parametrize("snapshot_flag", [None, "0", ""]) +def test_a_container_started_without_snapshots_reports_no_snapshot( + monkeypatch, snapshot_flag +): + container_calls = _calls_after_snapshot_hook( + monkeypatch, snapshot_flag=snapshot_flag + ) + + assert container_calls.container_start() is ContainerStart.NO_SNAPSHOT + + +def test_the_container_that_ran_the_snapshot_hook_reports_took_snapshot( + monkeypatch, +): + container_calls = _calls_after_snapshot_hook(monkeypatch) + + assert container_calls.container_start() is ContainerStart.TOOK_SNAPSHOT + + +def test_a_restored_container_reports_restored_from_snapshot(monkeypatch): + container_calls = _calls_after_snapshot_hook(monkeypatch) + _restore_into_another_container(monkeypatch) + + assert container_calls.container_start() is ContainerStart.RESTORED_FROM_SNAPSHOT + + +def test_the_attribute_values_are_the_ones_both_apps_report(): + assert {start.value for start in ContainerStart} == { + "restored_from_snapshot", + "took_snapshot", + "no_snapshot", + } + + +def test_each_call_takes_the_next_call_number(monkeypatch): + container_calls = _calls_after_snapshot_hook(monkeypatch) + _restore_into_another_container(monkeypatch) + + attributes_by_call = [container_calls.next_call_attributes() for _call in range(3)] + + assert attributes_by_call == [ + {"container_start": "restored_from_snapshot", "container_call_number": 1}, + {"container_start": "restored_from_snapshot", "container_call_number": 2}, + {"container_start": "restored_from_snapshot", "container_call_number": 3}, + ] + + +def test_set_call_attributes_sets_both_attributes_on_the_operation(monkeypatch): + container_calls = _calls_after_snapshot_hook(monkeypatch) + _restore_into_another_container(monkeypatch) + first_call_runtime = _AttributeRecordingRuntime() + second_call_runtime = _AttributeRecordingRuntime() + + container_calls.set_call_attributes(first_call_runtime) + container_calls.set_call_attributes(second_call_runtime) + + assert first_call_runtime.attributes == { + "container_start": "restored_from_snapshot", + "container_call_number": 1, + } + assert second_call_runtime.attributes == { + "container_start": "restored_from_snapshot", + "container_call_number": 2, + } + + +def test_a_runtime_refusing_the_attributes_raises_nothing_and_the_call_counts( + monkeypatch, +): + container_calls = _calls_after_snapshot_hook(monkeypatch) + + container_calls.set_call_attributes(_AttributeRefusingRuntime()) + + next_call_runtime = _AttributeRecordingRuntime() + container_calls.set_call_attributes(next_call_runtime) + assert next_call_runtime.attributes["container_call_number"] == 2 + + +def test_an_unreadable_container_start_raises_nothing_and_the_call_counts( + monkeypatch, +): + container_calls = _calls_after_snapshot_hook(monkeypatch) + read_container_start = container_calls.container_start + + def fail_to_read_the_container_start() -> ContainerStart: + msg = "container start unreadable" + raise RuntimeError(msg) + + monkeypatch.setattr( + container_calls, "container_start", fail_to_read_the_container_start + ) + failed_call_runtime = _AttributeRecordingRuntime() + container_calls.set_call_attributes(failed_call_runtime) + monkeypatch.setattr(container_calls, "container_start", read_container_start) + next_call_runtime = _AttributeRecordingRuntime() + container_calls.set_call_attributes(next_call_runtime) + + assert not CONTAINER_START_KEYS & set(failed_call_runtime.attributes) + assert next_call_runtime.attributes == { + "container_start": "took_snapshot", + "container_call_number": 2, + } + + +def test_separate_containers_number_their_calls_separately(monkeypatch): + first_container_calls = _calls_after_snapshot_hook(monkeypatch) + second_container_calls = _calls_after_snapshot_hook(monkeypatch) + + first_container_calls.next_call_attributes() + + assert second_container_calls.next_call_attributes()["container_call_number"] == 1 From 6336b6eb8d622e4879a488eb62b439260d646a5d Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:21:10 +0400 Subject: [PATCH 02/11] Add a container start module both Modal apps can share ContainerCalls holds the restore detection and call counter that src/modal/app.py's workers use today: the snapshot hook records the container's MODAL_TASK_ID and whether MODAL_ENABLE_SNAP_RESTORE is 1, and each call compares the recorded ID with the current one. Its set_call_attributes sets container_start and container_call_number on the call's operation and never raises, so the v2 workers can call it once per call. Co-Authored-By: Claude Opus 5.5 --- .../src/modal/container_calls.py | 93 +++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 projects/policyengine-simulation-executor/src/modal/container_calls.py diff --git a/projects/policyengine-simulation-executor/src/modal/container_calls.py b/projects/policyengine-simulation-executor/src/modal/container_calls.py new file mode 100644 index 000000000..9139e65ee --- /dev/null +++ b/projects/policyengine-simulation-executor/src/modal/container_calls.py @@ -0,0 +1,93 @@ +"""How the container serving a Modal worker call started, and the call's number. + +Both Modal apps' workers set two attributes on each call's operation: +``container_start`` (a ``ContainerStart`` value) and +``container_call_number``. Each app keeps one ``ContainerCalls`` at module +level: a Modal container serves one worker class or function, so that state +is the container's. ``docs/engineering/skills/observability.md`` describes +both attributes. +""" + +from __future__ import annotations + +import contextlib +import itertools +import os +from enum import StrEnum +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from policyengine_observability import ObservabilityRuntime + + +class ContainerStart(StrEnum): + """How the container serving a worker call started: its ``container_start``.""" + + RESTORED_FROM_SNAPSHOT = "restored_from_snapshot" + TOOK_SNAPSHOT = "took_snapshot" + NO_SNAPSHOT = "no_snapshot" + + +class ContainerCalls: + """Says how this container started, and numbers the worker calls it serves. + + The workers' snapshot hook records whether Modal snapshots the container + it runs in, and that container's ``MODAL_TASK_ID``, before Modal takes the + snapshot. A container restored from the snapshot starts with that record + in memory, but Modal 1.6.4 sets its ``MODAL_TASK_ID`` to its own task ID + (``memory_restore`` in ``modal/_runtime/task_lifecycle_manager.py``), so + the two IDs differ. The recorded ID is only compared, never reported: it + names the snapshotting container, not the one serving the call. + + The call counter is in the snapshot too, but no call runs before Modal + takes it, so every container's first call is number 1. + """ + + def __init__(self) -> None: + """Start as a container no snapshot hook has run in, with no calls yet.""" + self._snapshot_taken_here = False + self._snapshot_task_id: str | None = None + self._call_numbers = itertools.count(1) + + def record_snapshot_hook(self) -> None: + """Record, from the snapshot hook, whether Modal snapshots this container. + + Modal 1.6.4 runs the hook in every container that isn't restored, and + takes a snapshot only when the Modal process that starts the container + has set ``MODAL_ENABLE_SNAP_RESTORE`` to ``1`` (``maybe_snapshot`` in + ``modal/_runtime/user_code_imports.py``). The flag is set last, so a + failure partway leaves the container reporting ``no_snapshot``. + """ + self._snapshot_task_id = os.environ.get("MODAL_TASK_ID") + self._snapshot_taken_here = os.environ.get("MODAL_ENABLE_SNAP_RESTORE") == "1" + + def container_start(self) -> ContainerStart: + """Compare this container's task ID with the snapshotting container's.""" + if not self._snapshot_taken_here: + return ContainerStart.NO_SNAPSHOT + if os.environ.get("MODAL_TASK_ID") == self._snapshot_task_id: + return ContainerStart.TOOK_SNAPSHOT + return ContainerStart.RESTORED_FROM_SNAPSHOT + + def next_call_attributes(self) -> dict[str, str | int]: + """Return the next call's two container attributes, numbering the call. + + The call takes its number first, so it counts even if reading the + container start fails. + """ + call_number = next(self._call_numbers) + return { + "container_start": self.container_start().value, + "container_call_number": call_number, + } + + def set_call_attributes(self, runtime: ObservabilityRuntime) -> None: + """Set the next call's two attributes on the operation open in ``runtime``. + + Call it once per worker call, as the call's operation opens, so a call + that fails or is preempted carries them too. Telemetry is non-fatal: + a failure to read or set them raises nothing, and the call still + counts. + """ + with contextlib.suppress(Exception): + runtime.set_context(**self.next_call_attributes()) From c52e96c4a6fad0e5f837541e2915de1936e256c0 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:55:56 +0400 Subject: [PATCH 03/11] Add failing tests for the v2 workers' container start attributes Each call of SimulationWorkerUS, SimulationWorkerUK and SimulationSegmentWorkerUS, and of the plain functions kept for callers on older code, should carry container_start and container_call_number on its operation record and span, as the run_simulation app's workers do. The tests cover the three values, the call counter, failed and preempted calls, and failures to read or set the attributes leaving the result unchanged. Co-Authored-By: Claude Opus 5.5 --- .../tests/test_stage12_modal_app.py | 8 +- .../tests/test_v2_container_start.py | 424 ++++++++++++++++++ 2 files changed, 431 insertions(+), 1 deletion(-) create mode 100644 projects/policyengine-simulation-executor/tests/test_v2_container_start.py diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_modal_app.py b/projects/policyengine-simulation-executor/tests/test_stage12_modal_app.py index 037932a9c..d9c7689bd 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_modal_app.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_modal_app.py @@ -481,7 +481,13 @@ def test_stage12_functions_propagate_identifier_and_close_runtime( result = _invoke(monkeypatch, module, function_name, lambda *_, **__: {"ok": True}) assert result == {"ok": True} - assert runtime.contexts == [] + # A simulation worker's call sets only its container start and call number + # (tests/test_v2_container_start.py); the plain functions have no snapshot. + assert runtime.contexts == ( + [] + if function_name == "coordinate_report" + else [{"container_start": "no_snapshot", "container_call_number": 1}] + ) assert runtime.operations[0]["remote_context"]["observability_id"] == ( OBSERVABILITY_ID ) diff --git a/projects/policyengine-simulation-executor/tests/test_v2_container_start.py b/projects/policyengine-simulation-executor/tests/test_v2_container_start.py new file mode 100644 index 000000000..d80b83d23 --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_v2_container_start.py @@ -0,0 +1,424 @@ +"""Tests for the container start attributes of the v2 simulation workers' calls. + +Each call of a v2 simulation worker (``SimulationWorkerUS``, +``SimulationWorkerUK`` and ``SimulationSegmentWorkerUS``, and the plain +functions kept for callers on older code) says on its operation how the +container serving it started (``container_start``) and which call it is in +that container (``container_call_number``), as the run_simulation app's +workers do (``tests/test_modal_container_start.py``). +""" + +from __future__ import annotations + +import importlib +import sys + +import pytest +from conftest import NoOpObservabilityRuntime +from fixtures.fake_modal import install_fake_modal +from policyengine_simulation_contract.stage12_simulation_workers import ( + SEGMENT_WORKER_METHOD, + worker_class_name, +) +from policyengine_simulation_executor import stage12_runtime + +WORKER_RESULT = {"ok": True} +# The Modal task IDs of the container that takes the snapshot, of a container +# restored from it, and of a container that serves a plain function. +SNAPSHOT_TASK_ID = "ta-01SNAPSHOTTING" +RESTORED_TASK_ID = "ta-01RESTORED" +PLAIN_FUNCTION_TASK_ID = "ta-01PLAINFUNCTION" +CONTAINER_START_KEYS = {"container_start", "container_call_number"} +# Each worker class's method has the name of the plain function it replaces. +WORKER_METHOD_NAMES = ( + "run_single_simulation_us", + "run_single_simulation_uk", + "run_single_simulation_segment_us", +) + + +class _AttributeRecordingRuntime(NoOpObservabilityRuntime): + """Keeps every attribute a call sets on its operation.""" + + def __init__(self) -> None: + self.attributes: dict[str, object] = {} + + def set_context(self, **attributes: object) -> None: + self.attributes.update(attributes) + + def shutdown(self) -> None: + return None + + +class _AttributeRefusingRuntime(NoOpObservabilityRuntime): + """Fails every attempt to set an attribute, as a broken exporter might.""" + + def set_context(self, **_attributes: object) -> None: + msg = "attribute export failed" + raise RuntimeError(msg) + + def shutdown(self) -> None: + return None + + +class _SegmentResult: + """Stands in for a segment's artifact descriptor.""" + + def __init__(self, result: dict) -> None: + self._result = result + + def model_dump(self, *, mode: str) -> dict: + assert mode == "python" + return self._result + + +def _replace_worker_jobs(monkeypatch, job) -> None: + """Make every v2 worker call run ``job`` instead of its calculation.""" + + def run_single_simulation(_payload, _context, **_keywords): + return job() + + def calculate_segment(_payload, **_keywords): + return _SegmentResult(job()) + + monkeypatch.setattr(stage12_runtime, "run_single_simulation", run_single_simulation) + monkeypatch.setattr(stage12_runtime, "calculate_segment", calculate_segment) + + +@pytest.fixture +def v2_app(monkeypatch): + """Import the v2 app afresh, as a new container does, with stubbed jobs.""" + install_fake_modal(monkeypatch) + monkeypatch.delenv("MODAL_TASK_ID", raising=False) + monkeypatch.delenv("MODAL_ENABLE_SNAP_RESTORE", raising=False) + sys.modules.pop("src.modal.v2_images", None) + sys.modules.pop("src.modal.v2_app", None) + app = importlib.import_module("src.modal.v2_app") + # The real preload imports the country's models. + monkeypatch.setattr(app, "preload_country_models", lambda _countries: None) + monkeypatch.setattr(app.modal, "current_function_call_id", lambda: "fc-call") + _replace_worker_jobs(monkeypatch, lambda: WORKER_RESULT) + yield app + sys.modules.pop("src.modal.v2_images", None) + sys.modules.pop("src.modal.v2_app", None) + + +def _call_worker(worker, method_name: str) -> dict: + """Call a worker method or plain function with the arguments its callers pass.""" + if method_name == SEGMENT_WORKER_METHOD: + return worker( + {"simulation": {"role": "baseline"}, "segment_index": 0}, + observability_context=None, + ) + return worker({"role": "baseline"}, {}, observability_context=None) + + +def _record_call_attributes(v2_app, monkeypatch) -> list[dict[str, object]]: + """Give each call its own recording runtime, as each call configures its own. + + Returns the attributes each call set, in call order. + """ + attributes_by_call: list[dict[str, object]] = [] + + def configure_recording_runtime(**_identity: object) -> NoOpObservabilityRuntime: + runtime = _AttributeRecordingRuntime() + attributes_by_call.append(runtime.attributes) + return runtime + + monkeypatch.setattr( + v2_app, "init_process_observability", configure_recording_runtime + ) + return attributes_by_call + + +def _worker_after_snapshot_hook( + v2_app, monkeypatch, method_name: str, *, snapshots_enabled: bool = True +): + """Create a worker and run its snapshot hook, as Modal does in a new container. + + Returns the worker's method. Modal's worker sets + ``MODAL_ENABLE_SNAP_RESTORE`` to ``1`` in containers it takes snapshots + from or restores, and leaves it unset in a container of the same class + that starts without snapshots. + """ + monkeypatch.setenv("MODAL_TASK_ID", SNAPSHOT_TASK_ID) + if snapshots_enabled: + monkeypatch.setenv("MODAL_ENABLE_SNAP_RESTORE", "1") + worker = getattr(v2_app, worker_class_name(method_name))() + worker.load_country_models() + return getattr(worker, method_name) + + +def _restore_into_another_container(monkeypatch, worker_method) -> None: + """Act as a restore: the memory stays, and MODAL_TASK_ID names the new container. + + Modal 1.6.4's ``memory_restore`` sets ``MODAL_TASK_ID`` to the task ID of + the restored container, then Modal runs the ``snap=False`` hooks. + """ + monkeypatch.setenv("MODAL_TASK_ID", RESTORED_TASK_ID) + worker_method.__self__.reseed_random_after_restore() + + +@pytest.mark.parametrize("method_name", WORKER_METHOD_NAMES) +def test_a_call_in_the_container_that_ran_the_snapshot_hook_reports_took_snapshot( + v2_app, monkeypatch, method_name +): + worker_method = _worker_after_snapshot_hook(v2_app, monkeypatch, method_name) + attributes_by_call = _record_call_attributes(v2_app, monkeypatch) + + assert _call_worker(worker_method, method_name) == WORKER_RESULT + + [call_attributes] = attributes_by_call + assert call_attributes["container_start"] == "took_snapshot" + assert call_attributes["container_call_number"] == 1 + + +@pytest.mark.parametrize("method_name", WORKER_METHOD_NAMES) +def test_a_call_in_a_restored_container_reports_restored_from_snapshot( + v2_app, monkeypatch, method_name +): + worker_method = _worker_after_snapshot_hook(v2_app, monkeypatch, method_name) + _restore_into_another_container(monkeypatch, worker_method) + attributes_by_call = _record_call_attributes(v2_app, monkeypatch) + + assert _call_worker(worker_method, method_name) == WORKER_RESULT + + [call_attributes] = attributes_by_call + assert call_attributes["container_start"] == "restored_from_snapshot" + assert call_attributes["container_call_number"] == 1 + + +@pytest.mark.parametrize("method_name", WORKER_METHOD_NAMES) +def test_a_worker_container_started_without_snapshots_reports_no_snapshot( + v2_app, monkeypatch, method_name +): + worker_method = _worker_after_snapshot_hook( + v2_app, monkeypatch, method_name, snapshots_enabled=False + ) + attributes_by_call = _record_call_attributes(v2_app, monkeypatch) + + assert _call_worker(worker_method, method_name) == WORKER_RESULT + + # The hook loaded the models, but Modal took no snapshot from this container. + [call_attributes] = attributes_by_call + assert call_attributes["container_start"] == "no_snapshot" + assert call_attributes["container_call_number"] == 1 + + +@pytest.mark.parametrize("method_name", WORKER_METHOD_NAMES) +def test_a_plain_function_call_reports_a_container_started_without_a_snapshot( + v2_app, monkeypatch, method_name +): + # The plain functions kept for callers on older code have no snapshot hook. + monkeypatch.setenv("MODAL_TASK_ID", PLAIN_FUNCTION_TASK_ID) + attributes_by_call = _record_call_attributes(v2_app, monkeypatch) + + assert _call_worker(getattr(v2_app, method_name), method_name) == WORKER_RESULT + + [call_attributes] = attributes_by_call + assert call_attributes["container_start"] == "no_snapshot" + assert call_attributes["container_call_number"] == 1 + + +@pytest.mark.parametrize("method_name", WORKER_METHOD_NAMES) +def test_each_call_in_a_container_reports_the_next_call_number( + v2_app, monkeypatch, method_name +): + worker_method = _worker_after_snapshot_hook(v2_app, monkeypatch, method_name) + _restore_into_another_container(monkeypatch, worker_method) + attributes_by_call = _record_call_attributes(v2_app, monkeypatch) + + for _call in range(3): + assert _call_worker(worker_method, method_name) == WORKER_RESULT + + assert [ + call_attributes["container_call_number"] + for call_attributes in attributes_by_call + ] == [1, 2, 3] + assert { + call_attributes["container_start"] for call_attributes in attributes_by_call + } == {"restored_from_snapshot"} + + +@pytest.mark.parametrize("method_name", WORKER_METHOD_NAMES) +def test_both_attributes_reach_the_operation_record_and_span_but_no_metric( + v2_app, monkeypatch, recorded_observability_runtime, method_name +): + runtime, written_records = recorded_observability_runtime + # The runtime sets attributes on the operation's span through this method + # alone; OpenTelemetry is disabled in the recorded runtime. + span_attributes: dict[str, object] = {} + set_span_attributes = runtime._otel.set_span_attributes + + def record_span_attributes(attributes): + span_attributes.update(attributes) + set_span_attributes(attributes) + + monkeypatch.setattr(runtime._otel, "set_span_attributes", record_span_attributes) + # Every attribute the operation hands to its metrics, before the package + # filters them. + metric_attribute_sets: list[dict] = [] + for metric_method_name in ("record_operation", "record_error"): + record_metric = getattr(runtime._otel, metric_method_name) + + def record_metric_attributes( + duration_or_attributes, *more, record=record_metric + ): + attributes = more[0] if more else duration_or_attributes + metric_attribute_sets.append(dict(attributes)) + return record(duration_or_attributes, *more) + + monkeypatch.setattr(runtime._otel, metric_method_name, record_metric_attributes) + monkeypatch.setattr(v2_app, "init_process_observability", lambda **_: runtime) + worker_method = _worker_after_snapshot_hook(v2_app, monkeypatch, method_name) + _restore_into_another_container(monkeypatch, worker_method) + + assert _call_worker(worker_method, method_name) == WORKER_RESULT + + [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. + assert completion["attributes"]["container_start"] == "restored_from_snapshot" + assert completion["attributes"]["container_call_number"] == 1 + assert span_attributes["container_start"] == "restored_from_snapshot" + assert span_attributes["container_call_number"] == 1 + # Metrics carry neither: each call number would make another series. + assert metric_attribute_sets + for metric_attributes in metric_attribute_sets: + assert not CONTAINER_START_KEYS & set(metric_attributes) + + +@pytest.mark.parametrize("method_name", WORKER_METHOD_NAMES) +def test_both_attributes_are_set_before_the_calculation_runs( + v2_app, monkeypatch, method_name +): + worker_method = _worker_after_snapshot_hook(v2_app, monkeypatch, method_name) + _restore_into_another_container(monkeypatch, worker_method) + attributes_by_call = _record_call_attributes(v2_app, monkeypatch) + attributes_when_the_calculation_started: list[dict[str, object]] = [] + + def calculation_reading_its_operation_attributes(): + attributes_when_the_calculation_started.append(dict(attributes_by_call[-1])) + return WORKER_RESULT + + _replace_worker_jobs(monkeypatch, calculation_reading_its_operation_attributes) + + assert _call_worker(worker_method, method_name) == WORKER_RESULT + + [calculation_attributes] = attributes_when_the_calculation_started + assert calculation_attributes["container_start"] == "restored_from_snapshot" + assert calculation_attributes["container_call_number"] == 1 + + +# Each calculation failure with the outcome its operation record reports. +CALCULATION_FAILURES = [ + (RuntimeError("model failed"), "error"), + (KeyboardInterrupt(), "interrupted"), +] + + +@pytest.mark.parametrize("failure_and_outcome", CALCULATION_FAILURES) +@pytest.mark.parametrize("method_name", WORKER_METHOD_NAMES) +def test_a_failed_or_preempted_call_still_reports_both_attributes( + v2_app, + monkeypatch, + recorded_observability_runtime, + method_name, + failure_and_outcome, +): + calculation_failure, expected_outcome = failure_and_outcome + runtime, written_records = recorded_observability_runtime + monkeypatch.setattr(v2_app, "init_process_observability", lambda **_: runtime) + worker_method = _worker_after_snapshot_hook(v2_app, monkeypatch, method_name) + _restore_into_another_container(monkeypatch, worker_method) + + def failing_calculation(): + raise calculation_failure + + _replace_worker_jobs(monkeypatch, failing_calculation) + + with pytest.raises(type(calculation_failure)): + _call_worker(worker_method, method_name) + + [completion] = [ + record + for record in written_records + if record.get("event.name") == "operation.completed" + ] + assert completion["outcome"] == expected_outcome + assert completion["attributes"]["container_start"] == "restored_from_snapshot" + assert completion["attributes"]["container_call_number"] == 1 + + +@pytest.mark.parametrize("method_name", WORKER_METHOD_NAMES) +def test_a_runtime_refusing_the_attributes_leaves_the_call_result_unchanged( + v2_app, monkeypatch, method_name +): + worker_method = _worker_after_snapshot_hook(v2_app, monkeypatch, method_name) + _restore_into_another_container(monkeypatch, worker_method) + monkeypatch.setattr( + v2_app, "init_process_observability", lambda **_: _AttributeRefusingRuntime() + ) + + assert _call_worker(worker_method, method_name) == WORKER_RESULT + # The call still counts in the container, so the next call is number 2. + attributes_by_call = _record_call_attributes(v2_app, monkeypatch) + assert _call_worker(worker_method, method_name) == WORKER_RESULT + [call_attributes] = attributes_by_call + assert call_attributes["container_start"] == "restored_from_snapshot" + assert call_attributes["container_call_number"] == 2 + + +@pytest.mark.parametrize("method_name", WORKER_METHOD_NAMES) +def test_a_failure_to_read_the_container_start_leaves_the_call_unchanged( + v2_app, monkeypatch, method_name +): + worker_method = _worker_after_snapshot_hook(v2_app, monkeypatch, method_name) + attributes_by_call = _record_call_attributes(v2_app, monkeypatch) + + def fail_to_read_the_container_start(): + msg = "container start unreadable" + raise RuntimeError(msg) + + monkeypatch.setattr( + v2_app._CONTAINER_CALLS, "container_start", fail_to_read_the_container_start + ) + + assert _call_worker(worker_method, method_name) == WORKER_RESULT + + [call_attributes] = attributes_by_call + assert not CONTAINER_START_KEYS & set(call_attributes) + + +@pytest.mark.parametrize("method_name", WORKER_METHOD_NAMES) +def test_a_failure_to_record_the_snapshot_hook_still_loads_the_models( + v2_app, monkeypatch, method_name +): + preloaded_countries: list[tuple[str, ...]] = [] + monkeypatch.setattr( + v2_app, + "preload_country_models", + lambda countries: preloaded_countries.append(tuple(countries)), + ) + + def fail_to_record_the_snapshot_hook(): + msg = "environment unreadable" + raise RuntimeError(msg) + + monkeypatch.setattr( + v2_app._CONTAINER_CALLS, + "record_snapshot_hook", + fail_to_record_the_snapshot_hook, + ) + + worker_method = _worker_after_snapshot_hook(v2_app, monkeypatch, method_name) + + # The container starts with its models, and its calls report no_snapshot. + assert len(preloaded_countries) == 1 + attributes_by_call = _record_call_attributes(v2_app, monkeypatch) + assert _call_worker(worker_method, method_name) == WORKER_RESULT + [call_attributes] = attributes_by_call + assert call_attributes["container_start"] == "no_snapshot" From 4d21da56a3e47e4846188ccbe0246bf0f01dc2a8 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:57:21 +0400 Subject: [PATCH 04/11] Report container start and call number on each v2 worker call The v2 workers' snapshot hook records whether Modal snapshots the container and its MODAL_TASK_ID, and each call of SimulationWorkerUS, SimulationWorkerUK and SimulationSegmentWorkerUS, and of the plain functions kept for callers on older code, sets container_start and container_call_number on its operation as it opens. The run_simulation app's workers now use the same shared module, with no change in what they report. Co-Authored-By: Claude Opus 5.5 --- .../src/modal/app.py | 72 ++----------------- .../src/modal/v2_app.py | 10 +++ 2 files changed, 15 insertions(+), 67 deletions(-) diff --git a/projects/policyengine-simulation-executor/src/modal/app.py b/projects/policyengine-simulation-executor/src/modal/app.py index 106a0e2f5..40f497b66 100644 --- a/projects/policyengine-simulation-executor/src/modal/app.py +++ b/projects/policyengine-simulation-executor/src/modal/app.py @@ -10,10 +10,8 @@ """ import contextlib -import itertools import os import random -from enum import StrEnum from pathlib import Path from typing import TYPE_CHECKING @@ -45,6 +43,7 @@ from src.modal._image_setup import check_country_models_build, fetch_artifacts from src.modal.bundle_data import bundle_data_install_command from src.modal.ca_certificates import GRPC_CA_BUNDLE_ENV, OPERATING_SYSTEM_CA_PACKAGE +from src.modal.container_calls import ContainerCalls from src.modal.country_model_preload import preload_country_models from src.modal.logging_redaction import redact_params_for_logging from src.modal.modal_client_version import require_secret_reloading_modal_client @@ -307,69 +306,9 @@ def _configure_modal_observability( ) -class ContainerStart(StrEnum): - """How the container serving a worker call started: its ``container_start``.""" - - RESTORED_FROM_SNAPSHOT = "restored_from_snapshot" - TOOK_SNAPSHOT = "took_snapshot" - NO_SNAPSHOT = "no_snapshot" - - -class _ContainerCalls: - """Says how this container started, and numbers the worker calls it serves. - - A Modal container serves one worker class or function, so this module's - state is the container's. The workers' snapshot hook records whether - Modal snapshots the container it runs in, and that container's - ``MODAL_TASK_ID``, before Modal takes the snapshot. A container restored - from the snapshot starts with that record in memory, but Modal 1.6.4 sets - its ``MODAL_TASK_ID`` to its own task ID, so the two IDs differ. The - recorded ID is only compared, never reported: it names the snapshotting - container, not the one serving the call. - - The call counter is in the snapshot too, but no call runs before Modal - takes it, so every container's first call is number 1. - """ - - def __init__(self) -> None: - self._snapshot_taken_here = False - self._snapshot_task_id: str | None = None - self._call_numbers = itertools.count(1) - - def record_snapshot_hook(self) -> None: - """Record, from the snapshot hook, whether Modal snapshots this container. - - Modal 1.6.4 runs the hook in every container that isn't restored, and - takes a snapshot only when the Modal process that starts the container - has set ``MODAL_ENABLE_SNAP_RESTORE`` to ``1`` (``maybe_snapshot`` in - ``modal/_runtime/user_code_imports.py``). The flag is set last, so a - failure partway leaves the container reporting ``no_snapshot``. - """ - self._snapshot_task_id = os.environ.get("MODAL_TASK_ID") - self._snapshot_taken_here = os.environ.get("MODAL_ENABLE_SNAP_RESTORE") == "1" - - def container_start(self) -> ContainerStart: - """Compare this container's task ID with the snapshotting container's.""" - if not self._snapshot_taken_here: - return ContainerStart.NO_SNAPSHOT - if os.environ.get("MODAL_TASK_ID") == self._snapshot_task_id: - return ContainerStart.TOOK_SNAPSHOT - return ContainerStart.RESTORED_FROM_SNAPSHOT - - def next_call_attributes(self) -> dict[str, str | int]: - """Return the next call's two container attributes, numbering the call. - - The call takes its number first, so it counts even if reading the - container start fails. - """ - call_number = next(self._call_numbers) - return { - "container_start": self.container_start().value, - "container_call_number": call_number, - } - - -_CONTAINER_CALLS = _ContainerCalls() +# How this container started and how many worker calls it has served +# (src/modal/container_calls.py): each Modal container serves one worker. +_CONTAINER_CALLS = ContainerCalls() def _set_modal_call_attributes(runtime: "ObservabilityRuntime") -> None: @@ -377,8 +316,7 @@ def _set_modal_call_attributes(runtime: "ObservabilityRuntime") -> None: # Each attribute set is attempted on its own, so one failure keeps the other. with contextlib.suppress(Exception): runtime.set_context(function_call_id=modal.current_function_call_id()) - with contextlib.suppress(Exception): - runtime.set_context(**_CONTAINER_CALLS.next_call_attributes()) + _CONTAINER_CALLS.set_call_attributes(runtime) def _job_progress_reporter() -> "JobProgressReporter": diff --git a/projects/policyengine-simulation-executor/src/modal/v2_app.py b/projects/policyengine-simulation-executor/src/modal/v2_app.py index c0490b205..c8c7b0586 100644 --- a/projects/policyengine-simulation-executor/src/modal/v2_app.py +++ b/projects/policyengine-simulation-executor/src/modal/v2_app.py @@ -23,6 +23,7 @@ from __future__ import annotations +import contextlib import os import random from typing import TYPE_CHECKING, Any, ClassVar @@ -58,6 +59,7 @@ from policyengine_simulation_observability.telemetry import ( normalize_observability_context, ) +from src.modal.container_calls import ContainerCalls from src.modal.country_model_preload import preload_country_models from src.modal.v2_images import ( BUNDLE_VALUES, @@ -136,6 +138,8 @@ required_keys=[MODAL_WORKER_DATABASE_URL_ENV], ) report_run_writer_secrets = [*worker_secrets, modal_worker_database_secret] +# How this container started, and its calls' numbers: one worker per container. +_CONTAINER_CALLS = ContainerCalls() def _validate(country: CountryId) -> dict: @@ -249,6 +253,7 @@ def _run_single_simulation_segment_us( }, remote_context=propagated, ): + _CONTAINER_CALLS.set_call_attributes(runtime) return stage12_runtime.calculate_segment( payload, runtime=runtime ).model_dump(mode="python") @@ -307,6 +312,7 @@ def segmented_calculator( }, remote_context=propagated, ): + _CONTAINER_CALLS.set_call_attributes(runtime) return stage12_runtime.run_single_simulation( payload, context, @@ -355,6 +361,7 @@ def _run_single_simulation_uk( }, remote_context=propagated, ): + _CONTAINER_CALLS.set_call_attributes(runtime) return stage12_runtime.run_single_simulation( payload, context, @@ -387,6 +394,9 @@ class _V2CountryModelsLoadedBeforeSnapshot: @modal.enter(snap=True) def load_country_models(self) -> None: """Load the class's country models, and for the US the SPM capability.""" + # For each call's container_start; a failed record never stops the preload. + with contextlib.suppress(Exception): + _CONTAINER_CALLS.record_snapshot_hook() preload_country_models(self.snapshot_countries) @modal.enter(snap=False) From 6c952b71e8184d6e399150736492acdceb46f97b Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:58:04 +0400 Subject: [PATCH 05/11] Document the container start attributes on the v2 workers' calls The observability skill's section now covers the v2 app's simulation workers and their plain functions, the services their records come from, and the shared ContainerCalls module, and says the v2 workers' attribute hasn't been checked on Modal yet. Co-Authored-By: Claude Opus 5.5 --- changelog.d/v2-restore-telemetry.added.md | 1 + docs/engineering/skills/observability.md | 35 ++++++++++++++++------- 2 files changed, 26 insertions(+), 10 deletions(-) create mode 100644 changelog.d/v2-restore-telemetry.added.md diff --git a/changelog.d/v2-restore-telemetry.added.md b/changelog.d/v2-restore-telemetry.added.md new file mode 100644 index 000000000..145ebb3a8 --- /dev/null +++ b/changelog.d/v2-restore-telemetry.added.md @@ -0,0 +1 @@ +Each call of the v2 app's simulation workers, `SimulationWorkerUS`, `SimulationWorkerUK` and `SimulationSegmentWorkerUS`, and of the plain functions kept for callers on older code, now carries `container_start` (`restored_from_snapshot`, `took_snapshot` or `no_snapshot`) and `container_call_number` on its operation log record and span, as the run_simulation app's workers already do, so one query shows both apps' restores. diff --git a/docs/engineering/skills/observability.md b/docs/engineering/skills/observability.md index b763b0981..84bb8d821 100644 --- a/docs/engineering/skills/observability.md +++ b/docs/engineering/skills/observability.md @@ -187,17 +187,31 @@ its running segments. ### Container start and call number -Each call of the versioned app's workers (the `SimulationWorker.run_simulation` -and `SimulationSegmentWorker.run_simulation_segment` methods) and of -`run_budget_window_batch` sets two attributes on its operation, so on its -`operation.completed` log record and its span. Only the operation's span -carries them, not its child spans such as `country_module_load`. -`_set_modal_call_attributes` in `src/modal/app.py` sets them when the -operation opens, so a call that fails or is preempted carries them too. +Two attributes are set on the operation of each call of: + +- the versioned app's workers (the `SimulationWorker.run_simulation` and + `SimulationSegmentWorker.run_simulation_segment` methods) and + `run_budget_window_batch`, in `src/modal/app.py`; +- the v2 app's simulation workers (the + `SimulationWorkerUS.run_single_simulation_us`, + `SimulationWorkerUK.run_single_simulation_uk` and + `SimulationSegmentWorkerUS.run_single_simulation_segment_us` methods, and + the plain functions of the same names kept for callers on older code), in + `src/modal/v2_app.py`. Their records come from the services + `policyengine-stage12-us-worker`, `policyengine-stage12-uk-worker` and + `policyengine-stage12-us-segment-worker`. The v2 coordinator and household + functions set neither attribute. + +The attributes reach the call's `operation.completed` log record and its span. +Only the operation's span carries them, not its child spans such as +`country_module_load`. Both apps use `ContainerCalls` in +`src/modal/container_calls.py`, one per app module, since each Modal container +serves one worker. Its `set_call_attributes` sets them when the operation +opens, so a call that fails or is preempted carries them too. | Attribute | Values | |---|---| -| `container_start` | `restored_from_snapshot`: the container was restored from a memory snapshot, so it started with the country models loaded. `took_snapshot`: Modal took the snapshot from this container, after the snapshot hook loaded the models in it. `no_snapshot`: the container neither took a snapshot nor was restored from one. That is every container of the plain `run_budget_window_batch` function, which has no snapshot hook, and a worker class container that Modal started without snapshots, whose hook loaded the models before its first call. | +| `container_start` | `restored_from_snapshot`: the container was restored from a memory snapshot, so it started with the country models loaded. `took_snapshot`: Modal took the snapshot from this container, after the snapshot hook loaded the models in it. `no_snapshot`: the container neither took a snapshot nor was restored from one. That is every container of a plain function, which has no snapshot hook (`run_budget_window_batch`, and the v2 app's plain worker functions), and a worker class container that Modal started without snapshots, whose hook loaded the models before its first call. | | `container_call_number` | The call's place among the container's calls that opened their operation: 1 for the first, 2 for the second, and so on. A call counts even when reading or setting these attributes fails. | How a call tells them apart, in Modal 1.6.4: @@ -223,8 +237,9 @@ How a call tells them apart, in Modal 1.6.4: call doesn't tell them apart: on 2026-11-25 its `snapshot_behavior` field was `UNSPECIFIED` for every production container, restored ones included. - **Checked on Modal:** on 2026-11-25, in a measurement on Modal `testing` - with Modal 1.6.4, every restored container reported a `MODAL_TASK_ID` - different from the one its snapshot hook had recorded. + with Modal 1.6.4, every restored container of the versioned app's worker + classes reported a `MODAL_TASK_ID` different from the one its snapshot hook + had recorded. The v2 workers' attribute hasn't been checked on Modal yet. - **Never reported:** the recorded ID names the snapshotting container, not the one serving the call. From 2b65f444ef5b8df55294860965f0a4ecffd544b4 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:00:59 +0400 Subject: [PATCH 06/11] Add failing tests for the v2 workers naming their app and .py version Each call of the three v2 simulation workers, through its class method or its plain function, should configure its telemetry with the .py version as service version and name the Modal app in its operation's modal_app_name, as the run_simulation app's workers do, while keeping the service names existing queries select by. Co-Authored-By: Claude Opus 5.5 --- .../tests/test_v2_worker_app_and_version.py | 146 ++++++++++++++++++ 1 file changed, 146 insertions(+) create mode 100644 projects/policyengine-simulation-executor/tests/test_v2_worker_app_and_version.py diff --git a/projects/policyengine-simulation-executor/tests/test_v2_worker_app_and_version.py b/projects/policyengine-simulation-executor/tests/test_v2_worker_app_and_version.py new file mode 100644 index 000000000..a5f8bb385 --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_v2_worker_app_and_version.py @@ -0,0 +1,146 @@ +"""Tests that each v2 simulation worker call names the app and .py version serving it. + +The v2 workers' records say which worker served a call through their service +name, but not which deployed v2 app or which policyengine.py version did. As +the run_simulation app's workers do, each call's runtime carries the .py +version as its service version, and its operation names the Modal app in +``modal_app_name``. +""" + +from __future__ import annotations + +import importlib +import sys +from contextlib import contextmanager + +import pytest +from fixtures.fake_modal import install_fake_modal +from policyengine_simulation_contract.stage12_simulation_workers import ( + SEGMENT_WORKER_METHOD, + worker_class_name, +) +from policyengine_simulation_executor import stage12_runtime + +WORKER_RESULT = {"ok": True} +# Each worker with the service name its records carry today; existing queries +# select the workers' records by these names. +WORKER_SERVICE_NAMES = { + "run_single_simulation_us": "policyengine-stage12-us-worker", + "run_single_simulation_uk": "policyengine-stage12-uk-worker", + "run_single_simulation_segment_us": "policyengine-stage12-us-segment-worker", +} + + +class _SegmentResult: + """Stands in for a segment's artifact descriptor.""" + + def model_dump(self, *, mode: str) -> dict: + assert mode == "python" + return WORKER_RESULT + + +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 every worker's calculation 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, "preload_country_models", lambda _countries: None) + monkeypatch.setattr(app.modal, "current_function_call_id", lambda: "fc-call") + monkeypatch.setattr( + stage12_runtime, + "run_single_simulation", + lambda _payload, _context, **_keywords: WORKER_RESULT, + ) + monkeypatch.setattr( + stage12_runtime, "calculate_segment", lambda _payload, **_: _SegmentResult() + ) + yield app + sys.modules.pop("src.modal.v2_images", None) + sys.modules.pop("src.modal.v2_app", None) + + +def _call_worker(worker, method_name: str) -> dict: + """Call a worker method or plain function with the arguments its callers pass.""" + if method_name == SEGMENT_WORKER_METHOD: + return worker( + {"simulation": {"role": "baseline"}, "segment_index": 0}, + observability_context=None, + ) + return worker({"role": "baseline"}, {}, observability_context=None) + + +def _worker(v2_app, method_name: str, worker_kind: str): + """Return the class method or the plain function serving one worker's calls.""" + if worker_kind == "class_method": + return getattr(getattr(v2_app, worker_class_name(method_name))(), method_name) + return getattr(v2_app, method_name) + + +@pytest.mark.parametrize("worker_kind", ["class_method", "plain_function"]) +@pytest.mark.parametrize("method_name", sorted(WORKER_SERVICE_NAMES)) +def test_each_v2_worker_call_names_its_app_and_py_version( + v2_app, monkeypatch, method_name, worker_kind +): + 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 + ) + + worker = _worker(v2_app, method_name, worker_kind) + assert _call_worker(worker, method_name) == WORKER_RESULT + + [identity] = runtime_identities + assert identity["service_version"] == ( + v2_app.RESOLVED_BUNDLE.bundle.policyengine_version + ) + # The service name stays the worker's, as existing queries expect. + assert identity["service_name"] == WORKER_SERVICE_NAMES[method_name] + [attributes] = runtime.operation_attributes + assert attributes["modal_app_name"] == v2_app.APP_NAME + + +@pytest.mark.parametrize("method_name", sorted(WORKER_SERVICE_NAMES)) +def test_the_app_name_reaches_the_operation_record( + v2_app, monkeypatch, recorded_observability_runtime, method_name +): + runtime, written_records = recorded_observability_runtime + monkeypatch.setattr(v2_app, "init_process_observability", lambda **_: runtime) + + assert _call_worker(getattr(v2_app, method_name), method_name) == WORKER_RESULT + + [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. + assert completion["attributes"]["modal_app_name"] == v2_app.APP_NAME From 25dac99c35131f2100a1ff53c246b1d07f9b6664 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:01:29 +0400 Subject: [PATCH 07/11] Name the v2 app and .py version on each v2 worker call Each call of the three v2 simulation workers configures its telemetry with the bundle's policyengine.py version as service version, in place of the observability package's fallback 0.1.0, and its operation's modal_app_name names the v2 app, as the run_simulation app's workers do. The service names stay the workers', which existing queries select by. Co-Authored-By: Claude Opus 5.5 --- .../policyengine-simulation-executor/src/modal/v2_app.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/projects/policyengine-simulation-executor/src/modal/v2_app.py b/projects/policyengine-simulation-executor/src/modal/v2_app.py index c8c7b0586..ca6eef835 100644 --- a/projects/policyengine-simulation-executor/src/modal/v2_app.py +++ b/projects/policyengine-simulation-executor/src/modal/v2_app.py @@ -138,7 +138,6 @@ required_keys=[MODAL_WORKER_DATABASE_URL_ENV], ) report_run_writer_secrets = [*worker_secrets, modal_worker_database_secret] -# How this container started, and its calls' numbers: one worker per container. _CONTAINER_CALLS = ContainerCalls() @@ -235,6 +234,7 @@ def _run_single_simulation_segment_us( service_role="stage12_segment_worker", platform="modal", environment=os.getenv("MODAL_ENVIRONMENT", "local"), + service_version=RESOLVED_BUNDLE.bundle.policyengine_version, ) try: @@ -243,6 +243,7 @@ def _run_single_simulation_segment_us( STAGE12_SEGMENT_STAGES.name(Stage.STAGE12_SEGMENT_EXECUTION), attributes={ "runner_name": "stage12", + "modal_app_name": APP_NAME, "simulation_role": payload.get("simulation", {}).get("role"), "segment_index": payload.get("segment_index"), **stage12_runtime.operation_record_attributes( @@ -280,6 +281,7 @@ def _run_single_simulation_us( service_role="stage12_simulation_worker", platform="modal", environment=os.getenv("MODAL_ENVIRONMENT", "local"), + service_version=RESOLVED_BUNDLE.bundle.policyengine_version, ) # Read inside ``try``, so the runtime is shut down whatever happens. @@ -305,6 +307,7 @@ def segmented_calculator( STAGE12_SIMULATION_STAGES.name(Stage.STAGE12_SIMULATION_EXECUTION), attributes={ "runner_name": "stage12", + "modal_app_name": APP_NAME, "simulation_role": payload.get("role"), **stage12_runtime.simulation_worker_record_attributes( context, modal_call_id @@ -346,6 +349,7 @@ def _run_single_simulation_uk( service_role="stage12_simulation_worker", platform="modal", environment=os.getenv("MODAL_ENVIRONMENT", "local"), + service_version=RESOLVED_BUNDLE.bundle.policyengine_version, ) try: modal_call_id = modal.current_function_call_id() @@ -354,6 +358,7 @@ def _run_single_simulation_uk( STAGE12_SIMULATION_STAGES.name(Stage.STAGE12_SIMULATION_EXECUTION), attributes={ "runner_name": "stage12", + "modal_app_name": APP_NAME, "simulation_role": payload.get("role"), **stage12_runtime.simulation_worker_record_attributes( context, modal_call_id @@ -394,7 +399,6 @@ class _V2CountryModelsLoadedBeforeSnapshot: @modal.enter(snap=True) def load_country_models(self) -> None: """Load the class's country models, and for the US the SPM capability.""" - # For each call's container_start; a failed record never stops the preload. with contextlib.suppress(Exception): _CONTAINER_CALLS.record_snapshot_hook() preload_country_models(self.snapshot_countries) From 8f79878312354fec02b6704935fdf39afe81e9de Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:01:42 +0400 Subject: [PATCH 08/11] Document the v2 workers' app name and .py version Co-Authored-By: Claude Opus 5.5 --- changelog.d/v2-restore-telemetry.added.md | 2 +- docs/engineering/skills/observability.md | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/changelog.d/v2-restore-telemetry.added.md b/changelog.d/v2-restore-telemetry.added.md index 145ebb3a8..6e8dab7ea 100644 --- a/changelog.d/v2-restore-telemetry.added.md +++ b/changelog.d/v2-restore-telemetry.added.md @@ -1 +1 @@ -Each call of the v2 app's simulation workers, `SimulationWorkerUS`, `SimulationWorkerUK` and `SimulationSegmentWorkerUS`, and of the plain functions kept for callers on older code, now carries `container_start` (`restored_from_snapshot`, `took_snapshot` or `no_snapshot`) and `container_call_number` on its operation log record and span, as the run_simulation app's workers already do, so one query shows both apps' restores. +Each call of the v2 app's simulation workers, `SimulationWorkerUS`, `SimulationWorkerUK` and `SimulationSegmentWorkerUS`, and of the plain functions kept for callers on older code, now carries `container_start` (`restored_from_snapshot`, `took_snapshot` or `no_snapshot`) and `container_call_number` on its operation log record and span, as the run_simulation app's workers already do, so one query shows both apps' restores. Each such call also names the v2 app in `modal_app_name` and the policyengine.py version in its records' `service.version`, which was the observability package's fallback `0.1.0`. diff --git a/docs/engineering/skills/observability.md b/docs/engineering/skills/observability.md index 84bb8d821..6ca9102b3 100644 --- a/docs/engineering/skills/observability.md +++ b/docs/engineering/skills/observability.md @@ -33,6 +33,14 @@ contains `household`, `reform`, `payload` or `person`, among others, so no key for these IDs names one. Do not use `job_id` for a v2 call: it names one annual Modal invocation of the v1 executor. +A v2 simulation worker's call (the US and UK single-simulation workers and the +US segment worker, as class methods or plain functions) 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 +functions' records still carry the observability package's fallback version. + `observability_id` is a canonical UUID string and has diagnostic meaning only. Do not use it for idempotency, authorization, database identity, routing, or business logic. Do not create one for health checks, version queries, invalid From 8c01fca36184d9682cbf7fc993bb5667fc8d8c80 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:08:19 +0400 Subject: [PATCH 09/11] Name the shared ContainerCalls class in two docstrings Co-Authored-By: Claude Opus 5.5 --- projects/policyengine-simulation-executor/src/modal/app.py | 2 +- .../src/modal/snapshot_warm_up.py | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/projects/policyengine-simulation-executor/src/modal/app.py b/projects/policyengine-simulation-executor/src/modal/app.py index 40f497b66..46488930c 100644 --- a/projects/policyengine-simulation-executor/src/modal/app.py +++ b/projects/policyengine-simulation-executor/src/modal/app.py @@ -491,7 +491,7 @@ def load_country_models(self) -> None: """Load the models and SPM capability, then warm up, before the snapshot. First records whether Modal snapshots this container, and its task ID, - so each call can report how its container started (``_ContainerCalls``). + so each call can report how its container started (``ContainerCalls``). Telemetry is non-fatal: a failed record must never stop the preload. Then, in a container Modal snapshots, runs one warm-up calculation (``src/modal/snapshot_warm_up.py``), so restored containers start with diff --git a/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py b/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py index 40cf61010..fc4520999 100644 --- a/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py +++ b/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py @@ -45,7 +45,8 @@ ``country_model_preload`` says.) - **No telemetry.** It configures no observability and gives the calculation a runtime that records and sends nothing, so it writes no - operation record or span and no call number (``_ContainerCalls``). + operation record or span and no call number (``ContainerCalls`` in + ``src/modal/container_calls.py``). - **Nothing left for a request.** It removes the simulations it added to .py's in-process cache and the output files it saved in the prebuilt folder, so a later call loads its baseline from the image as it would From 75e5da8984e1107394fc3ae12fc602266acc8176 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:19:02 +0400 Subject: [PATCH 10/11] Check the v2 workers' version against the installed .py package Review round 2 found the test compared the version with the same expression the code passes. It now compares it with the installed policyengine distribution's version. The service.version change gets its own "changed" changelog fragment, since it alters a value existing records already carry. Co-Authored-By: Claude Opus 5.5 --- changelog.d/v2-restore-telemetry.added.md | 2 +- changelog.d/v2-worker-service-version.changed.md | 1 + .../tests/test_v2_worker_app_and_version.py | 6 +++--- 3 files changed, 5 insertions(+), 4 deletions(-) create mode 100644 changelog.d/v2-worker-service-version.changed.md diff --git a/changelog.d/v2-restore-telemetry.added.md b/changelog.d/v2-restore-telemetry.added.md index 6e8dab7ea..58139c494 100644 --- a/changelog.d/v2-restore-telemetry.added.md +++ b/changelog.d/v2-restore-telemetry.added.md @@ -1 +1 @@ -Each call of the v2 app's simulation workers, `SimulationWorkerUS`, `SimulationWorkerUK` and `SimulationSegmentWorkerUS`, and of the plain functions kept for callers on older code, now carries `container_start` (`restored_from_snapshot`, `took_snapshot` or `no_snapshot`) and `container_call_number` on its operation log record and span, as the run_simulation app's workers already do, so one query shows both apps' restores. Each such call also names the v2 app in `modal_app_name` and the policyengine.py version in its records' `service.version`, which was the observability package's fallback `0.1.0`. +Each call of the v2 app's simulation workers, `SimulationWorkerUS`, `SimulationWorkerUK` and `SimulationSegmentWorkerUS`, and of the plain functions kept for callers on older code, now carries `container_start` (`restored_from_snapshot`, `took_snapshot` or `no_snapshot`) and `container_call_number` on its operation log record and span, as the run_simulation app's workers already do, so one query shows both apps' restores. Each such call's operation also names the v2 app in `modal_app_name`. diff --git a/changelog.d/v2-worker-service-version.changed.md b/changelog.d/v2-worker-service-version.changed.md new file mode 100644 index 000000000..3a0c50284 --- /dev/null +++ b/changelog.d/v2-worker-service-version.changed.md @@ -0,0 +1 @@ +The v2 app's simulation workers' log records, spans and metrics now carry the policyengine.py version that served the call as `service.version`, in place of the observability package's fallback `0.1.0`. Their `service.name` values are unchanged. diff --git a/projects/policyengine-simulation-executor/tests/test_v2_worker_app_and_version.py b/projects/policyengine-simulation-executor/tests/test_v2_worker_app_and_version.py index a5f8bb385..6db7c0144 100644 --- a/projects/policyengine-simulation-executor/tests/test_v2_worker_app_and_version.py +++ b/projects/policyengine-simulation-executor/tests/test_v2_worker_app_and_version.py @@ -10,6 +10,7 @@ from __future__ import annotations import importlib +import importlib.metadata import sys from contextlib import contextmanager @@ -119,9 +120,8 @@ def configure_recording_runtime(**identity): assert _call_worker(worker, method_name) == WORKER_RESULT [identity] = runtime_identities - assert identity["service_version"] == ( - v2_app.RESOLVED_BUNDLE.bundle.policyengine_version - ) + # The .py version installed in the worker's image, which serves the call. + assert identity["service_version"] == importlib.metadata.version("policyengine") # The service name stays the worker's, as existing queries expect. assert identity["service_name"] == WORKER_SERVICE_NAMES[method_name] [attributes] = runtime.operation_attributes From 5eb3cba82daaa6fafb4c9428123d551da2731d37 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:34:26 +0400 Subject: [PATCH 11/11] Name the changelog fragments after their issue, #1139 Co-Authored-By: Claude Opus 5.5 --- changelog.d/{v2-restore-telemetry.added.md => 1139.added.md} | 0 .../{v2-worker-service-version.changed.md => 1139.changed.md} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename changelog.d/{v2-restore-telemetry.added.md => 1139.added.md} (100%) rename changelog.d/{v2-worker-service-version.changed.md => 1139.changed.md} (100%) diff --git a/changelog.d/v2-restore-telemetry.added.md b/changelog.d/1139.added.md similarity index 100% rename from changelog.d/v2-restore-telemetry.added.md rename to changelog.d/1139.added.md diff --git a/changelog.d/v2-worker-service-version.changed.md b/changelog.d/1139.changed.md similarity index 100% rename from changelog.d/v2-worker-service-version.changed.md rename to changelog.d/1139.changed.md