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/job-queue-seconds.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Each annual job's `run_simulation` operation record now carries `job_queue_seconds`, the seconds from the gateway's submission of the job to its start in the worker. The gateway sends the submission time with the spawned job as the `_job_submitted_at` parameter; the worker leaves it out of its logged attributes and removes it before the calculation. Years that a budget-window batch spawns carry no queue time.
45 changes: 44 additions & 1 deletion docs/engineering/skills/observability.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,11 @@ call = function.spawn(payload, observability_context=context)
```

Keep `payload` limited to calculation inputs and functional metadata. Do not
add `_observability_context` to it.
add `_observability_context` to it. Two underscore-prefixed telemetry values
are the exceptions: API v1's `_telemetry` envelope, which
`split_internal_payload` removes before the calculation, and the annual job's
`_job_submitted_at` (see "Annual job queue time"), which the worker removes
when the call starts.

At the receiving function, validate the separate argument with
`normalize_observability_context` and pass the result to
Expand Down Expand Up @@ -158,6 +162,45 @@ Modal can run the same call again after a preemption, under the same call
id. A later attempt continues the stored stage record, so the durations add
up over attempts, and `job_attempts` counts them.

### Annual job queue time

`run_simulation` also sets `job_queue_seconds` on its operation: the seconds
from the gateway's submission of the job to the job's start in the worker.

- **Submission time:** the gateway sends it with the spawned job under the
`_job_submitted_at` parameter (`JOB_SUBMITTED_AT_PARAM` in
`policyengine_simulation_contract.job_progress`), the same value it stores
as the job metadata's `submitted_at`. The leading underscore keeps it out of
the operation's logged attributes (`redact_params_for_logging`), and the
worker removes it before the calculation, so segment children never get it.
- **Start time:** the stage record's `started_at`, which is the first
attempt's start and carries over to later attempts. While each later
attempt finds the earlier attempt's record, every attempt's record, a
preempted one's included, carries the same value, so the successful
attempt's record carries it too, and the value counts neither the earlier
attempts' running time nor the wait before a later attempt. When a later
attempt finds no earlier record, see "No earlier record" below.
- **Counting jobs:** a preempted job writes one record per attempt, each with
the same value, so a median or percentile over jobs takes one record per
`function_call_id`, such as the one whose `outcome` is `success`.
- **When it is set:** when the operation opens, so a failed or preempted call
carries it too.
- **Clocks:** the two times come from the gateway's and the worker's
machines. A start before the submission can only mean those clocks differ,
and is recorded as 0. Values are rounded to hundredths of a second.
- **Jobs without it:** the years that a budget-window batch spawns. The
gateway doesn't put the key in the batch's payload, whose top-level keys
`run_budget_window_batch` validates with `extra="forbid"` in apps of every
age, and the batch adds none to its years' payloads. Records from worker
apps deployed before this attribute, and from calls an older gateway
spawned, carry none either.
- **No earlier record:** a later attempt that finds no earlier attempt's
record starts a new one, so its value includes the earlier attempts' time.
That happens when reading the record fails, and when the earlier attempt's
writes failed or it was preempted before its first write.
- **Only ISO 8601 times:** the value must be a string with a time zone, as
the gateway sends it. Anything else, a number included, records nothing.

### Preemptions

Modal delivers a preemption to a running synchronous function, which every
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

from __future__ import annotations

from datetime import datetime
from enum import StrEnum
from types import MappingProxyType
from typing import TYPE_CHECKING, Any, Literal
Expand All @@ -29,11 +30,17 @@

if TYPE_CHECKING:
from collections.abc import Mapping
from datetime import datetime

JOB_PROGRESS_CAPABILITY_KEY = "job_progress"
JOB_PROGRESS_CAPABILITY_VERSION = 1

# The gateway sends an annual job's submission time with the job's parameters
# under this key, the same ISO 8601 value as the job metadata's
# ``submitted_at``, so the worker can record the job's queue time. The worker
# removes it before the calculation, and its log redaction leaves every key
# that starts with an underscore out of the logged attributes.
JOB_SUBMITTED_AT_PARAM = "_job_submitted_at"


class JobStage(StrEnum):
"""Coarse stages of an annual economy job, in the order they run.
Expand Down Expand Up @@ -156,6 +163,29 @@ def _parse_datetime(value: object) -> datetime | None:
return None


def job_queue_seconds(submitted_at: object, *, started_at: datetime) -> float | None:
"""Return the seconds from a job's submission to its start, or None.

``submitted_at`` is the value sent under ``JOB_SUBMITTED_AT_PARAM``: an
ISO 8601 string with a time zone. Anything else gives None, a number
included, so a value from another sender is never read as a Unix time.
``started_at`` is the job record's start, which is its first attempt's.

The gateway and the worker read different machines' clocks, so a start
before the submission can only mean the clocks differ; it counts as 0.
Seconds are rounded to hundredths, like stage durations.
"""
if not isinstance(submitted_at, str):
return None
try:
submitted = datetime.fromisoformat(submitted_at)
except ValueError:
return None
if submitted.utcoffset() is None:
return None
return round(max((started_at - submitted).total_seconds(), 0.0), 2)


def stage_progress_floor(execution: JobExecution | None, stage: JobStage) -> int:
"""Return the progress percent at which ``stage`` starts on ``execution``.

Expand Down
31 changes: 31 additions & 0 deletions libs/policyengine-simulation-contract/tests/test_job_progress.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
JobSegmentProgress,
JobStage,
job_progress_fields,
job_queue_seconds,
stage_progress_floor,
stage_progress_max,
supported_job_progress_capability,
Expand Down Expand Up @@ -328,6 +329,36 @@ def test__other_values_are_unsupported(self, value):
assert supported_job_progress_capability(value) is None


class TestJobQueueSeconds:
def test__seconds_from_the_submission_to_the_first_start(self):
assert job_queue_seconds(SUBMITTED, started_at=STARTED) == 30.0

def test__seconds_are_rounded_to_hundredths(self):
started_at = datetime(2026, 10, 13, 12, 0, 7, 254_000, tzinfo=UTC)

assert job_queue_seconds(SUBMITTED, started_at=started_at) == 7.25

def test__a_start_before_the_submission_counts_as_no_wait(self):
# Only the gateway's and the worker's clocks differing can cause it.
started_at = datetime(2026, 10, 13, 11, 59, 59, 800_000, tzinfo=UTC)

assert job_queue_seconds(SUBMITTED, started_at=started_at) == 0.0

@pytest.mark.parametrize(
"submitted_at",
[None, "not a time", "2026-10-13T12:00:00", {"at": SUBMITTED}],
)
def test__a_missing_or_unreadable_submission_time_gives_none(self, submitted_at):
assert job_queue_seconds(submitted_at, started_at=STARTED) is None

@pytest.mark.parametrize(
"submitted_at", [0, 1760356800, "1760356800", 1760356800.0]
)
def test__a_number_is_not_read_as_a_unix_time(self, submitted_at):
# The gateway sends an ISO 8601 time; a number means another sender.
assert job_queue_seconds(submitted_at, started_at=STARTED) is None


class TestJobProgressModels:
def test__completed_segments_cannot_exceed_total(self):
with pytest.raises(ValidationError):
Expand Down
45 changes: 45 additions & 0 deletions projects/policyengine-simulation-executor/src/modal/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
from pathlib import Path
from typing import TYPE_CHECKING

from policyengine_simulation_contract.job_progress import (
JOB_SUBMITTED_AT_PARAM,
job_queue_seconds,
)
from policyengine_simulation_executor.hf_access_validation import (
HF_MODAL_SECRET_NAME,
HF_RUNTIME_ENV_NAME,
Expand Down Expand Up @@ -431,6 +435,45 @@ def _record_stage_durations(
)


def _without_submission_time(params: dict) -> tuple[dict, object]:
"""Return ``params`` without the gateway's submission time, and that time.

The submission time is for telemetry only. The calculation, and the
segment children it copies its parameters to, never see it. Parameters
that aren't a dict pass through unchanged, for the calculation to report.
"""
if not isinstance(params, dict):
return params, None
submitted_at = params.get(JOB_SUBMITTED_AT_PARAM)
remaining = {
key: value for key, value in params.items() if key != JOB_SUBMITTED_AT_PARAM
}
return remaining, submitted_at


def _record_queue_seconds(
runtime: "ObservabilityRuntime",
progress: "JobProgressReporter",
submitted_at: object,
) -> None:
"""Attach the job's queue time to its operation telemetry.

It runs from the gateway's submission to the job record's start, which
is the first attempt's while each later attempt finds the earlier
attempt's record, so every attempt's record then carries the same value.
Jobs spawned without a submission time record none: a budget-window
batch's years, and jobs an older gateway spawned.
"""
# Telemetry is non-fatal.
with contextlib.suppress(Exception):
started_at = progress.started_at()
if started_at is None:
return
queue_seconds = job_queue_seconds(submitted_at, started_at=started_at)
if queue_seconds is not None:
runtime.set_context(job_queue_seconds=queue_seconds)


def _run_simulation(
params: dict,
*,
Expand All @@ -446,6 +489,7 @@ def _run_simulation(
"""
progress = _job_progress_reporter()
progress.start()
params, submitted_at = _without_submission_time(params)
runtime = _configure_modal_observability(service_role="simulation_worker")

# We deliberately avoid sending full ``params`` or ``result`` blobs to
Expand All @@ -467,6 +511,7 @@ def _run_simulation(
remote_context=propagated,
):
_set_modal_call_attributes(runtime)
_record_queue_seconds(runtime, progress, submitted_at)
from src.modal.segmented_national import ( # noqa: PLC0415 # Modal function body: loaded in the worker container, not at deploy time
dispatch_run_simulation,
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ def attempts(self) -> int:
"""Return how many times Modal has started this call."""
...

def started_at(self) -> datetime | None:
"""Return when the job's first attempt started, or None without a record."""
...


class NullJobProgressReporter:
"""Reports nothing."""
Expand Down Expand Up @@ -107,6 +111,10 @@ def attempts(self) -> int:
"""Return 1, since no earlier attempt is known."""
return 1

def started_at(self) -> datetime | None:
"""Return None, since no record is kept."""
return None


NULL_JOB_PROGRESS = NullJobProgressReporter()

Expand Down Expand Up @@ -275,6 +283,14 @@ def attempts(self) -> int:
"""Return this attempt's number, counting from 1."""
return 1 if self._record is None else self._record.attempts

def started_at(self) -> datetime | None:
"""Return the record's start, an earlier attempt's when this one continues it.

None before ``start()``. When reading the earlier attempt's record
failed, this attempt started a new record, so it is this attempt's.
"""
return None if self._record is None else self._record.started_at

def _earlier_attempt(self) -> JobProgressRecord | None:
if self._read is None:
return None
Expand Down
Loading