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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/container-start-telemetry.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Each `run_simulation`, `run_simulation_segment` and `run_budget_window_batch` call's operation log record and span now carry `container_start` (`restored_from_snapshot`, `took_snapshot` or `no_snapshot`) and `container_call_number`, the call's number in its container. Cloud Logging and Cloud Trace can then tell calls in containers restored from a memory snapshot apart from others, and the spans of those containers' first calls show the setup time left after a restore.
66 changes: 66 additions & 0 deletions docs/engineering/skills/observability.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,72 @@ calls in turn. Each of those calls that was running writes an ERROR record,
so one coordinator preemption can write one for each simulation and each of
its running segments.

### Container start and call number

Each call of the versioned app's workers (`run_simulation` and
`run_simulation_segment`, as class methods and as plain functions) 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.

| 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_simulation` and `run_simulation_segment` functions and of `run_budget_window_batch`, which have no snapshot hook, 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:

- **Before the snapshot:** Modal runs the workers' snapshot hook
(`load_country_models`) in every container that isn't restored. It takes a
snapshot only when the Modal process that starts the container has set
`MODAL_ENABLE_SNAP_RESTORE` to `1`, for a class with memory snapshots
enabled (`maybe_snapshot` in `modal/_runtime/user_code_imports.py`). The
hook records that flag and the container's `MODAL_TASK_ID`.
- **On restore:** a restored container starts with that record in memory, but
Modal sets its `MODAL_TASK_ID` to its own task ID (`memory_restore` in
`modal/_runtime/task_lifecycle_manager.py`). A call reports
`restored_from_snapshot` when the two IDs differ, and `took_snapshot` when
they match.
- **Not documented by Modal:** neither variable's behaviour is, so check the
attribute against Modal's container logs, and again after a Modal upgrade.
A restored container logs "Restoring Function from memory snapshot." and a
snapshotting one "Creating CPU memory snapshot for Function.";
`modal app logs <app name> --env <environment> --search "memory snapshot"
--show-container-id` lists both. Match a log's container ID with the task
ID at the start of a record's `service.instance.id`. Modal's `TaskGetInfo`
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.
- **Never reported:** the recorded ID names the snapshotting container, not
the one serving the call.

Neither the restore nor the snapshot hook runs inside a call, so no span
measures them. Modal's container records (its `TaskGetInfo` call) give the
times each container was queued and became ready (`enqueued_at` and
`started_at`), which include scheduling as well as the restore. A call's spans show the setup still left
in it:

- In the first call of a container of the plain `run_simulation` or
`run_simulation_segment` function, which loads the models itself, most of
that setup is in the `country_module_load` span, which
imports policyengine.py's country model module, and, for a US run, in the
time from the operation's start to that span, which includes the SPM
capability check. A segmented national run's `run_simulation` call opens no
`country_module_load` span: its segment workers' calls do.
- In a container whose hook loaded the models, the first call's time there
should be close to later calls' (`container_call_number` above 1).
- A container's first `calculation` has also been slower than its later ones;
compare that span between first and later calls too.

Neither attribute reaches metrics: the package's operation metrics carry only
the service's identity and the operation's name, kind and outcome, and each
call number would make another series. `container_start` has three values.
Records from apps deployed before these attributes carry neither.

## Metric resource identity

Every process that emits OpenTelemetry metrics must have a unique
Expand Down
86 changes: 82 additions & 4 deletions projects/policyengine-simulation-executor/src/modal/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@
"""

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 @@ -316,10 +318,78 @@ 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()


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())


def _job_progress_reporter() -> "JobProgressReporter":
Expand Down Expand Up @@ -481,16 +551,24 @@ def _run_simulation_segment(
class _CountryModelsLoadedBeforeSnapshot:
"""Base of the simulation workers: loads the models before the snapshot.

Modal runs ``snap=True`` hooks once, in the container that takes the
memory snapshot; every container restored from it starts with the loaded
models in memory. ``snap=False`` hooks run after each restore.
Modal runs ``snap=True`` hooks in every container that isn't restored, and
takes the memory snapshot from such a container when it starts it with
snapshots enabled; every container restored from the snapshot starts with
the loaded models in memory. ``snap=False`` hooks run after each restore.
Observability is configured per call instead, after the restore, so each
restored container reports its own process identity.
"""

@modal.enter(snap=True)
def load_country_models(self) -> None:
"""Load both countries' models and the SPM capability into the snapshot."""
"""Load both countries' models and the SPM capability into the snapshot.

First records whether Modal snapshots this container, and its task ID,
so each call can report how its container started (``_ContainerCalls``).
Telemetry is non-fatal: a failed record must never stop the preload.
"""
with contextlib.suppress(Exception):
_CONTAINER_CALLS.record_snapshot_hook()
preload_country_models()

@modal.enter(snap=False)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

``SimulationWorker`` and ``SimulationSegmentWorker`` in ``src/modal/app.py``
run :func:`preload_country_models` in their ``@modal.enter(snap=True)`` hook.
Modal runs that hook once, in the container that takes the snapshot, and
every container restored from the snapshot starts with its results already in
memory:
Modal runs that hook in every container that isn't restored, and takes the
memory snapshot from such a container when it starts it with snapshots
enabled. Every container restored from the snapshot starts with the hook's
results already in memory:

- the country packages, whose import builds each country's tax-benefit
system;
Expand Down
Loading