Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/1139.added.md
Original file line number Diff line number Diff line change
@@ -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. Each such call's operation also names the v2 app in `modal_app_name`.
1 change: 1 addition & 0 deletions changelog.d/1139.changed.md
Original file line number Diff line number Diff line change
@@ -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.
43 changes: 33 additions & 10 deletions docs/engineering/skills/observability.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -235,17 +243,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:
Expand All @@ -271,8 +293,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.

Expand Down
74 changes: 6 additions & 68 deletions projects/policyengine-simulation-executor/src/modal/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -49,6 +47,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
Expand Down Expand Up @@ -311,78 +310,17 @@ 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:
# Telemetry is non-fatal: a failed attribute must never fail the Modal call.
# 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":
Expand Down Expand Up @@ -598,7 +536,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
Expand Down
Original file line number Diff line number Diff line change
@@ -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())
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions projects/policyengine-simulation-executor/src/modal/v2_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

from __future__ import annotations

import contextlib
import os
import random
from typing import TYPE_CHECKING, Any, ClassVar
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -136,6 +138,7 @@
required_keys=[MODAL_WORKER_DATABASE_URL_ENV],
)
report_run_writer_secrets = [*worker_secrets, modal_worker_database_secret]
_CONTAINER_CALLS = ContainerCalls()


def _validate(country: CountryId) -> dict:
Expand Down Expand Up @@ -231,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:
Expand All @@ -239,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(
Expand All @@ -249,6 +254,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")
Expand All @@ -275,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.
Expand All @@ -300,13 +307,15 @@ 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
),
},
remote_context=propagated,
):
_CONTAINER_CALLS.set_call_attributes(runtime)
return stage12_runtime.run_single_simulation(
payload,
context,
Expand Down Expand Up @@ -340,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()
Expand All @@ -348,13 +358,15 @@ 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
),
},
remote_context=propagated,
):
_CONTAINER_CALLS.set_call_attributes(runtime)
return stage12_runtime.run_single_simulation(
payload,
context,
Expand Down Expand Up @@ -387,6 +399,8 @@ 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."""
with contextlib.suppress(Exception):
_CONTAINER_CALLS.record_snapshot_hook()
preload_country_models(self.snapshot_countries)

@modal.enter(snap=False)
Expand Down
Loading
Loading