From a6dbfc780e9dbe1ca9e34734813e1c02ab13d311 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:09:54 +0400 Subject: [PATCH 1/6] Test that each annual job's run telemetry records its queue time The gateway is to send the job's submission time with the spawned annual job, under an underscore-prefixed key, and the worker to set job_queue_seconds on its run_simulation operation: the job record's started_at, which is the first attempt's start, minus that time. The tests cover the contract's calculation, the gateway's spawned payload, the stage reporter's start time, the worker's attribute on first and later attempts and on failures, the key's removal before the calculation, and the written operation record. A guard test keeps the key out of budget-window batch payloads, which run_budget_window_batch validates with extra="forbid" on apps of every age. Co-Authored-By: Claude Opus 5.5 --- .../tests/test_job_progress.py | 24 +++ .../tests/test_job_progress.py | 176 ++++++++++++++++++ .../tests/test_budget_window_endpoints.py | 33 ++++ .../tests/test_job_progress.py | 11 ++ 4 files changed, 244 insertions(+) diff --git a/libs/policyengine-simulation-contract/tests/test_job_progress.py b/libs/policyengine-simulation-contract/tests/test_job_progress.py index 600b6bf13..f0b0e8a7d 100644 --- a/libs/policyengine-simulation-contract/tests/test_job_progress.py +++ b/libs/policyengine-simulation-contract/tests/test_job_progress.py @@ -13,6 +13,7 @@ JobSegmentProgress, JobStage, job_progress_fields, + job_queue_seconds, stage_progress_floor, stage_progress_max, supported_job_progress_capability, @@ -328,6 +329,29 @@ 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 + + class TestJobProgressModels: def test__completed_segments_cannot_exceed_total(self): with pytest.raises(ValidationError): diff --git a/projects/policyengine-simulation-executor/tests/test_job_progress.py b/projects/policyengine-simulation-executor/tests/test_job_progress.py index d473bf689..80db4bf7e 100644 --- a/projects/policyengine-simulation-executor/tests/test_job_progress.py +++ b/projects/policyengine-simulation-executor/tests/test_job_progress.py @@ -14,6 +14,7 @@ from fixtures.macro_output import CURRENT_SINGLE_YEAR_MACRO_RESULT from fixtures.spm_doubles import installed_spm_selection, spm_capable_simulation from policyengine_simulation_contract.job_progress import ( + JOB_SUBMITTED_AT_PARAM, JobExecution, JobProgressRecord, JobSegmentProgress, @@ -232,6 +233,22 @@ def test__finish_without_start_writes_nothing(self): assert writer.writes == [] + def test__started_at_is_none_before_the_record_starts(self): + reporter, _, _ = _reporter() + + assert reporter.started_at() is None + + def test__started_at_is_when_the_record_started(self): + reporter, _, clock = _reporter() + reporter.start() + clock.advance(40) + reporter.enter(JobStage.BASELINE) + + assert reporter.started_at() == T0 + + def test__the_null_reporter_has_no_start(self): + assert NULL_JOB_PROGRESS.started_at() is None + def test__write_failures_are_logged_once_and_never_raised(self, caplog): calls = [] @@ -327,6 +344,13 @@ def test__restart_never_moves_progress_backwards(self): assert reform_starts[0] == T0 - timedelta(seconds=30) assert reform_starts[-1] == T0 + timedelta(seconds=30) + def test__started_at_stays_the_first_attempts_start(self): + earlier = _earlier_attempt() + reporter, _, _ = _restarted_reporter(earlier) + reporter.start() + + assert reporter.started_at() == earlier.started_at + def test__durations_add_up_over_attempts(self): reporter, writer, clock = _restarted_reporter(_earlier_attempt()) @@ -785,6 +809,14 @@ def shutdown(self): self.events.append("shutdown") +def _queue_time_attributes(events) -> list[tuple[int, dict]]: + return [ + (index, event[1]) + for index, event in enumerate(events) + if isinstance(event, tuple) and "job_queue_seconds" in event[1] + ] + + def _stage_attributes(events) -> list[tuple[int, dict]]: return [ (index, event[1]) @@ -969,6 +1001,150 @@ def failing_write(_job_id, _record): "ok": True } + def _wire_reporter_started_at( + self, app, monkeypatch, dispatch, *, started_at, earlier=None + ): + """Wire the call with a stage reporter whose clock reads ``started_at``.""" + events, writes = self._wire(app, monkeypatch, dispatch, earlier=earlier) + reporter = StoredJobProgressReporter( + "fc-job-1", + write=lambda job_id, record: writes.append((job_id, record)), + read=lambda _job_id: earlier, + clock=lambda: started_at, + ) + monkeypatch.setattr(app, "_job_progress_reporter", lambda: reporter) + return events, writes + + def test__records_the_queue_time_from_the_gateway_submission( + self, modal_app, monkeypatch + ): + def dispatch(_params, *, app_name, runtime, progress): + return {"ok": True} + + events, _ = self._wire_reporter_started_at( + modal_app, + monkeypatch, + dispatch, + started_at=T0 + timedelta(seconds=7.25), + ) + + modal_app.SimulationWorker().run_simulation( + {"country": "us", JOB_SUBMITTED_AT_PARAM: T0.isoformat()} + ) + + [(index, attributes)] = _queue_time_attributes(events) + assert attributes == {"job_queue_seconds": 7.25} + assert events.index("operation_start") < index < events.index("operation_end") + + def test__a_later_attempt_records_the_queue_time_to_the_first_start( + self, modal_app, monkeypatch + ): + # The record's started_at carries over from the first attempt, so the + # successful attempt's record carries the job's queue time too. + earlier = _earlier_attempt() + submitted_at = earlier.started_at - timedelta(seconds=12) + + def dispatch(_params, *, app_name, runtime, progress): + return {"ok": True} + + events, _ = self._wire_reporter_started_at( + modal_app, monkeypatch, dispatch, started_at=T0, earlier=earlier + ) + + modal_app.SimulationWorker().run_simulation( + {"country": "us", JOB_SUBMITTED_AT_PARAM: submitted_at.isoformat()} + ) + + [(_, attributes)] = _queue_time_attributes(events) + assert attributes == {"job_queue_seconds": 12.0} + + def test__a_failed_job_records_its_queue_time_too(self, modal_app, monkeypatch): + def dispatch(_params, *, app_name, runtime, progress): + msg = "model failed" + raise RuntimeError(msg) + + events, _ = self._wire_reporter_started_at( + modal_app, + monkeypatch, + dispatch, + started_at=T0 + timedelta(seconds=3), + ) + + with pytest.raises(RuntimeError, match="model failed"): + modal_app.SimulationWorker().run_simulation( + {"country": "us", JOB_SUBMITTED_AT_PARAM: T0.isoformat()} + ) + + [(_, attributes)] = _queue_time_attributes(events) + assert attributes == {"job_queue_seconds": 3.0} + + def test__a_job_without_a_submission_time_records_no_queue_time( + self, modal_app, monkeypatch + ): + # Jobs that budget-window batches, smoke checks and older gateways + # spawn carry no submission time. + def dispatch(_params, *, app_name, runtime, progress): + return {"ok": True} + + events, _ = self._wire_reporter_started_at( + modal_app, monkeypatch, dispatch, started_at=T0 + ) + + modal_app.SimulationWorker().run_simulation({"country": "us"}) + + assert _queue_time_attributes(events) == [] + + def test__the_calculation_never_sees_the_submission_time( + self, modal_app, monkeypatch + ): + # Segment children copy the parameters they are given. + dispatched_params = [] + + def dispatch(params, *, app_name, runtime, progress): + dispatched_params.append(params) + return {"ok": True} + + self._wire_reporter_started_at(modal_app, monkeypatch, dispatch, started_at=T0) + + modal_app.SimulationWorker().run_simulation( + {"country": "us", JOB_SUBMITTED_AT_PARAM: T0.isoformat()} + ) + + assert dispatched_params == [{"country": "us"}] + + def test__the_operation_record_carries_the_queue_time( + self, modal_app, monkeypatch, recorded_observability_runtime + ): + runtime, written_records = recorded_observability_runtime + + def dispatch(_params, *, app_name, runtime, progress): + return {"ok": True} + + self._wire_reporter_started_at( + modal_app, + monkeypatch, + dispatch, + started_at=T0 + timedelta(seconds=7.25), + ) + monkeypatch.setattr( + modal_app, + "_configure_modal_observability", + lambda *, service_role: runtime, + ) + + modal_app.SimulationWorker().run_simulation( + {"country": "us", JOB_SUBMITTED_AT_PARAM: T0.isoformat()} + ) + + [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"]["job_queue_seconds"] == 7.25 + assert JOB_SUBMITTED_AT_PARAM not in completion["attributes"] + def test__no_call_id_means_no_reporting(self, modal_app, monkeypatch): def missing_call_id(): msg = "not inside a Modal function call" diff --git a/projects/policyengine-simulation-gateway/tests/test_budget_window_endpoints.py b/projects/policyengine-simulation-gateway/tests/test_budget_window_endpoints.py index 36ccf4261..0d786034c 100644 --- a/projects/policyengine-simulation-gateway/tests/test_budget_window_endpoints.py +++ b/projects/policyengine-simulation-gateway/tests/test_budget_window_endpoints.py @@ -94,6 +94,39 @@ def test__given_no_dataset_override__then_parent_batch_omits_dataset( assert response.status_code == 200 assert "data" not in mock_modal["func"].last_payload + def test__given_budget_window_submission__then_sends_no_job_submission_time( + self, mock_modal, client: TestClient + ): + """The batch refuses unknown keys, on apps of every age. + + ``run_budget_window_batch`` validates its parameters with + ``BudgetWindowBatchRequest``, whose ``extra="forbid"`` would refuse + the annual jobs' submission-time key. + """ + from policyengine_simulation_contract.gateway_models import ( + BudgetWindowBatchRequest, + ) + from policyengine_simulation_contract.job_progress import ( + JOB_SUBMITTED_AT_PARAM, + ) + + response = client.post( + "/simulate/economy/budget-window", + json={ + "country": "us", + "region": "us", + "scope": "macro", + "reform": {}, + "start_year": "2026", + "window_size": 2, + }, + ) + + assert response.status_code == 200 + spawned_payload = mock_modal["func"].last_payload + assert JOB_SUBMITTED_AT_PARAM not in spawned_payload + BudgetWindowBatchRequest.model_validate(spawned_payload) + def test__given_budget_window_submission__then_returns_parent_batch_job_id( self, mock_modal, client: TestClient ): diff --git a/projects/policyengine-simulation-gateway/tests/test_job_progress.py b/projects/policyengine-simulation-gateway/tests/test_job_progress.py index 0b62dc8d2..757839e24 100644 --- a/projects/policyengine-simulation-gateway/tests/test_job_progress.py +++ b/projects/policyengine-simulation-gateway/tests/test_job_progress.py @@ -11,6 +11,7 @@ from fastapi.testclient import TestClient from policyengine_simulation_contract.job_progress import ( JOB_PROGRESS_CAPABILITY_VERSION, + JOB_SUBMITTED_AT_PARAM, JobExecution, JobProgressRecord, JobSegmentProgress, @@ -86,6 +87,16 @@ def test__worker_without_capability_is_recorded_as_none( metadata = mock_modal["dicts"][JOB_METADATA_DICT_NAME][job_id] assert metadata["job_progress"] is None + def test__the_spawned_job_carries_its_submission_time( + self, mock_modal, client: TestClient + ): + # The worker records the job's queue time from it. + job_id = _submit(client) + + metadata = mock_modal["dicts"][JOB_METADATA_DICT_NAME][job_id] + spawned_payload = mock_modal["func"].last_payload + assert spawned_payload[JOB_SUBMITTED_AT_PARAM] == metadata["submitted_at"] + class TestStageReportingWorker: def test__running_job_without_record_is_queued( From 15203e106b7da36bff01e5ac89d9d5887cde05fa Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:21:37 +0400 Subject: [PATCH 2/6] Record each annual job's queue time in its run telemetry The gateway now sends the job's submission time with every annual job it spawns, as the _job_submitted_at parameter, the same value it stores as the job metadata's submitted_at. The worker removes it before the calculation and sets job_queue_seconds on its run_simulation operation when the operation opens: the stage record's started_at, which is the first attempt's start and carries over to later attempts, minus the submission time. Every attempt's record carries the value, so a preempted job's successful attempt carries it too. A start before the submission, which only a difference between the two machines' clocks can cause, counts as 0. Only apps that define the SimulationWorker class receive annual jobs, and every such app passes unknown underscore-prefixed parameters through and leaves them out of its logged attributes, so the gateway sends the key to every route. Budget-window batch payloads don't get it, since run_budget_window_batch validates them with extra="forbid", so the years a batch spawns record no queue time. Co-Authored-By: Claude Opus 5.5 --- changelog.d/job-queue-seconds.added.md | 1 + docs/engineering/skills/observability.md | 29 ++++++++++++++++ .../job_progress.py | 25 ++++++++++++++ .../src/modal/app.py | 33 +++++++++++++++++++ .../job_progress.py | 16 +++++++++ .../tests/test_job_progress.py | 4 +-- .../policyengine-simulation-gateway/README.md | 6 +++- .../job_creation_routes.py | 3 ++ 8 files changed, 114 insertions(+), 3 deletions(-) create mode 100644 changelog.d/job-queue-seconds.added.md diff --git a/changelog.d/job-queue-seconds.added.md b/changelog.d/job-queue-seconds.added.md new file mode 100644 index 000000000..35929d7de --- /dev/null +++ b/changelog.d/job-queue-seconds.added.md @@ -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. diff --git a/docs/engineering/skills/observability.md b/docs/engineering/skills/observability.md index b763b0981..a8b3dfe9f 100644 --- a/docs/engineering/skills/observability.md +++ b/docs/engineering/skills/observability.md @@ -158,6 +158,35 @@ 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. Every attempt's record, + a preempted one's included, carries the same value, so the successful + attempt's record carries it too. It never counts the time between a + preemption and the next attempt. +- **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, whose + batch payload can't take the key (`run_budget_window_batch` validates it + with `extra="forbid"`). Records from worker apps deployed before this + attribute, and from calls an older gateway spawned, carry none either. +- **A failed read:** a later attempt whose stage reporter couldn't read the + earlier attempt's record starts a new one, so its value includes the + earlier attempts' time. + ### Preemptions Modal delivers a preemption to a running synchronous function, which every diff --git a/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/job_progress.py b/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/job_progress.py index ca823cb09..00d6c2457 100644 --- a/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/job_progress.py +++ b/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/job_progress.py @@ -34,6 +34,13 @@ 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. @@ -156,6 +163,24 @@ 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``, + read as the gateway's job status reads the stored ``submitted_at``. It + gives None when it is missing or isn't a time with a time zone. + ``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. + """ + submitted = _parse_datetime(submitted_at) + if submitted 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``. diff --git a/projects/policyengine-simulation-executor/src/modal/app.py b/projects/policyengine-simulation-executor/src/modal/app.py index 106a0e2f5..c2eceed2c 100644 --- a/projects/policyengine-simulation-executor/src/modal/app.py +++ b/projects/policyengine-simulation-executor/src/modal/app.py @@ -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, @@ -431,6 +435,28 @@ def _record_stage_durations( ) +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, so every attempt's record 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, *, @@ -446,6 +472,12 @@ def _run_simulation( """ progress = _job_progress_reporter() progress.start() + # The submission time is for telemetry only. The calculation, and the + # segment children it copies its parameters to, never see it. + submitted_at = params.get(JOB_SUBMITTED_AT_PARAM) + params = { + key: value for key, value in params.items() if key != JOB_SUBMITTED_AT_PARAM + } runtime = _configure_modal_observability(service_role="simulation_worker") # We deliberately avoid sending full ``params`` or ``result`` blobs to @@ -467,6 +499,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, ) diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/job_progress.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/job_progress.py index 81f5c25f7..74fd48268 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/job_progress.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/job_progress.py @@ -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.""" @@ -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() @@ -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 diff --git a/projects/policyengine-simulation-executor/tests/test_job_progress.py b/projects/policyengine-simulation-executor/tests/test_job_progress.py index 80db4bf7e..88adf6d9e 100644 --- a/projects/policyengine-simulation-executor/tests/test_job_progress.py +++ b/projects/policyengine-simulation-executor/tests/test_job_progress.py @@ -1081,8 +1081,8 @@ def dispatch(_params, *, app_name, runtime, progress): def test__a_job_without_a_submission_time_records_no_queue_time( self, modal_app, monkeypatch ): - # Jobs that budget-window batches, smoke checks and older gateways - # spawn carry no submission time. + # Jobs that budget-window batches and older gateways spawn carry no + # submission time. def dispatch(_params, *, app_name, runtime, progress): return {"ok": True} diff --git a/projects/policyengine-simulation-gateway/README.md b/projects/policyengine-simulation-gateway/README.md index 433d2b651..569d45ae9 100644 --- a/projects/policyengine-simulation-gateway/README.md +++ b/projects/policyengine-simulation-gateway/README.md @@ -87,7 +87,11 @@ statistics exist for each country and region type (#780, phase 2). The worker also adds `job_stage_seconds_` attributes to its `run_simulation` operation, so telemetry can split the baseline from the -reform calculation. +reform calculation, and `job_queue_seconds`, the time from the gateway's +submission to the job's start. The gateway sends the submission time with +the spawned job as the `_job_submitted_at` parameter, which the worker leaves +out of its logged attributes and removes before the calculation; see +"Annual job queue time" in `docs/engineering/skills/observability.md`. ## UK local-area breakdowns diff --git a/projects/policyengine-simulation-gateway/src/policyengine_simulation_gateway/job_creation_routes.py b/projects/policyengine-simulation-gateway/src/policyengine_simulation_gateway/job_creation_routes.py index 6ed10a898..e222d5c1a 100644 --- a/projects/policyengine-simulation-gateway/src/policyengine_simulation_gateway/job_creation_routes.py +++ b/projects/policyengine-simulation-gateway/src/policyengine_simulation_gateway/job_creation_routes.py @@ -23,6 +23,7 @@ from policyengine_simulation_contract.hf_dataset import HuggingFaceDatasetReferenceError from policyengine_simulation_contract.job_progress import ( JOB_PROGRESS_CAPABILITY_KEY, + JOB_SUBMITTED_AT_PARAM, supported_job_progress_capability, ) from policyengine_simulation_contract.json_types import JsonObject @@ -311,7 +312,9 @@ async def submit_simulation( # Spawn the job (returns immediately). The worker lookup's control-plane # RPCs and the spawn live under one span to time the real network cost. + # The worker records the job's queue time from the submission time. submitted_at = datetime.now(UTC) + payload[JOB_SUBMITTED_AT_PARAM] = submitted_at.isoformat() with runtime.span(ANNUAL_IMPACT_STAGES.name(Stage.MODAL_FUNCTION_SPAWN)): call = _spawn_annual_simulation( route.app_name, From 37c7aba8e6022375013b8307c9823994847402a2 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:33:00 +0400 Subject: [PATCH 3/6] Test that a number isn't read as a submission time, and that non-dict parameters still run job_queue_seconds reads its value as the gateway's job status does, which takes a number or a numeric string as a Unix time, so 0 gives a queue time of decades. And the worker now reads the submission time with params.get before its operation opens, so parameters that aren't a dict fail there, with no operation record and the stage record left running, where before the calculation reported them. Also cover a preempted attempt, whose record carries the queue time like a failed one's. Co-Authored-By: Claude Opus 5.5 --- .../tests/test_job_progress.py | 7 +++ .../tests/test_job_progress.py | 45 +++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/libs/policyengine-simulation-contract/tests/test_job_progress.py b/libs/policyengine-simulation-contract/tests/test_job_progress.py index f0b0e8a7d..2964c3170 100644 --- a/libs/policyengine-simulation-contract/tests/test_job_progress.py +++ b/libs/policyengine-simulation-contract/tests/test_job_progress.py @@ -351,6 +351,13 @@ def test__a_start_before_the_submission_counts_as_no_wait(self): 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): diff --git a/projects/policyengine-simulation-executor/tests/test_job_progress.py b/projects/policyengine-simulation-executor/tests/test_job_progress.py index 88adf6d9e..71b5510f2 100644 --- a/projects/policyengine-simulation-executor/tests/test_job_progress.py +++ b/projects/policyengine-simulation-executor/tests/test_job_progress.py @@ -1078,6 +1078,51 @@ def dispatch(_params, *, app_name, runtime, progress): [(_, attributes)] = _queue_time_attributes(events) assert attributes == {"job_queue_seconds": 3.0} + def test__a_preempted_attempt_records_its_queue_time_too( + self, modal_app, monkeypatch + ): + def dispatch(_params, *, app_name, runtime, progress): + raise KeyboardInterrupt + + events, _ = self._wire_reporter_started_at( + modal_app, + monkeypatch, + dispatch, + started_at=T0 + timedelta(seconds=4), + ) + + with pytest.raises(KeyboardInterrupt): + modal_app.SimulationWorker().run_simulation( + {"country": "us", JOB_SUBMITTED_AT_PARAM: T0.isoformat()} + ) + + [(index, attributes)] = _queue_time_attributes(events) + assert attributes == {"job_queue_seconds": 4.0} + assert index < events.index("operation_end") + + def test__parameters_that_are_not_a_dict_still_reach_the_calculation( + self, modal_app, monkeypatch + ): + # Reading the submission time must not fail a call before its + # operation opens; the calculation reports malformed parameters. + dispatched_params = [] + + def dispatch(params, *, app_name, runtime, progress): + dispatched_params.append(params) + return {"ok": True} + + events, _ = self._wire_reporter_started_at( + modal_app, monkeypatch, dispatch, started_at=T0 + ) + malformed_params = ["country", "us"] + + assert modal_app.SimulationWorker().run_simulation(malformed_params) == { + "ok": True + } + + assert dispatched_params == [malformed_params] + assert _queue_time_attributes(events) == [] + def test__a_job_without_a_submission_time_records_no_queue_time( self, modal_app, monkeypatch ): From 31d6a2ca50d74530a882155897a396586aad9bd4 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:34:10 +0400 Subject: [PATCH 4/6] Read only ISO 8601 submission times, and pass non-dict parameters through job_queue_seconds now takes only an ISO 8601 string with a time zone, as the gateway sends it, so a number from another sender records nothing instead of a queue time of decades. The worker reads and removes the submission time only from a dict, so parameters of another type reach the calculation, inside the operation, as before. The observability guide now says that a later attempt starts a new stage record, and so counts the earlier attempts' time, whenever it finds no earlier record (a failed read, failed writes, or a preemption before the first write), and that the gateway keeps the key out of the batch payload's top-level keys. Co-Authored-By: Claude Opus 5.5 --- docs/engineering/skills/observability.md | 24 ++++++++++++------- .../job_progress.py | 17 ++++++++----- .../src/modal/app.py | 23 +++++++++++++----- 3 files changed, 43 insertions(+), 21 deletions(-) diff --git a/docs/engineering/skills/observability.md b/docs/engineering/skills/observability.md index a8b3dfe9f..54147618e 100644 --- a/docs/engineering/skills/observability.md +++ b/docs/engineering/skills/observability.md @@ -172,20 +172,26 @@ from the gateway's submission of the job to the job's start in the worker. - **Start time:** the stage record's `started_at`, which is the first attempt's start and carries over to later attempts. Every attempt's record, a preempted one's included, carries the same value, so the successful - attempt's record carries it too. It never counts the time between a - preemption and the next attempt. + attempt's record carries it too, unless a later attempt finds no earlier + record (below). It never counts the time between a preemption and the next + attempt. - **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, whose - batch payload can't take the key (`run_budget_window_batch` validates it - with `extra="forbid"`). Records from worker apps deployed before this - attribute, and from calls an older gateway spawned, carry none either. -- **A failed read:** a later attempt whose stage reporter couldn't read the - earlier attempt's record starts a new one, so its value includes the - earlier attempts' time. +- **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 diff --git a/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/job_progress.py b/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/job_progress.py index 00d6c2457..a03ecf4cf 100644 --- a/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/job_progress.py +++ b/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/job_progress.py @@ -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 @@ -29,7 +30,6 @@ if TYPE_CHECKING: from collections.abc import Mapping - from datetime import datetime JOB_PROGRESS_CAPABILITY_KEY = "job_progress" JOB_PROGRESS_CAPABILITY_VERSION = 1 @@ -166,17 +166,22 @@ def _parse_datetime(value: object) -> datetime | 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``, - read as the gateway's job status reads the stored ``submitted_at``. It - gives None when it is missing or isn't a time with a time zone. + ``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. """ - submitted = _parse_datetime(submitted_at) - if submitted is None: + 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) diff --git a/projects/policyengine-simulation-executor/src/modal/app.py b/projects/policyengine-simulation-executor/src/modal/app.py index c2eceed2c..cf0ed98ed 100644 --- a/projects/policyengine-simulation-executor/src/modal/app.py +++ b/projects/policyengine-simulation-executor/src/modal/app.py @@ -435,6 +435,22 @@ 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", @@ -472,12 +488,7 @@ def _run_simulation( """ progress = _job_progress_reporter() progress.start() - # The submission time is for telemetry only. The calculation, and the - # segment children it copies its parameters to, never see it. - submitted_at = params.get(JOB_SUBMITTED_AT_PARAM) - params = { - key: value for key, value in params.items() if key != JOB_SUBMITTED_AT_PARAM - } + 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 From 6570191211ec78468f03a5190e845b0a9d20450f Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:48:25 +0400 Subject: [PATCH 5/6] Test that a failing queue time record leaves the job's result unchanged A failing read of the stage record's start time, or a failing attribute write, must not change a calculation result (rule sim.observability.failures-never-break-requests). The worker already suppresses both; these tests show it. Co-Authored-By: Claude Opus 5.5 --- .../tests/test_job_progress.py | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/projects/policyengine-simulation-executor/tests/test_job_progress.py b/projects/policyengine-simulation-executor/tests/test_job_progress.py index 71b5510f2..c06575233 100644 --- a/projects/policyengine-simulation-executor/tests/test_job_progress.py +++ b/projects/policyengine-simulation-executor/tests/test_job_progress.py @@ -1123,6 +1123,56 @@ def dispatch(params, *, app_name, runtime, progress): assert dispatched_params == [malformed_params] assert _queue_time_attributes(events) == [] + def test__a_failing_start_time_read_leaves_the_result_unchanged( + self, modal_app, monkeypatch + ): + def dispatch(_params, *, app_name, runtime, progress): + return {"ok": True} + + events, _ = self._wire_reporter_started_at( + modal_app, monkeypatch, dispatch, started_at=T0 + ) + reporter = modal_app._job_progress_reporter() + + def failing_started_at(): + msg = "record unavailable" + raise RuntimeError(msg) + + monkeypatch.setattr(reporter, "started_at", failing_started_at) + + assert modal_app.SimulationWorker().run_simulation( + {"country": "us", JOB_SUBMITTED_AT_PARAM: T0.isoformat()} + ) == {"ok": True} + assert _queue_time_attributes(events) == [] + + def test__a_failing_attribute_write_leaves_the_result_unchanged( + self, modal_app, monkeypatch + ): + def dispatch(_params, *, app_name, runtime, progress): + return {"ok": True} + + events, _ = self._wire_reporter_started_at( + modal_app, monkeypatch, dispatch, started_at=T0 + ) + + class _QueueTimeRefusingRuntime(_RecordingRuntime): + def set_context(self, **attributes): + if "job_queue_seconds" in attributes: + msg = "attribute refused" + raise RuntimeError(msg) + super().set_context(**attributes) + + monkeypatch.setattr( + modal_app, + "_configure_modal_observability", + lambda *, service_role: _QueueTimeRefusingRuntime(events), + ) + + assert modal_app.SimulationWorker().run_simulation( + {"country": "us", JOB_SUBMITTED_AT_PARAM: T0.isoformat()} + ) == {"ok": True} + assert "operation_end" in events + def test__a_job_without_a_submission_time_records_no_queue_time( self, modal_app, monkeypatch ): From f56aa9dcf7064efbb92acdaccdb706020702d1ee Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:48:25 +0400 Subject: [PATCH 6/6] Say when every attempt carries the same queue time, and how to count jobs The observability guide said the queue time never counts the wait before a later attempt, without the exception its own "No earlier record" bullet describes, and the worker's docstring had the same gap. Both now say the value is the same on every attempt only while each later attempt finds the earlier attempt's record. The guide also says to take one record per function_call_id when computing statistics over jobs, since a preempted job writes one record per attempt, and names the two telemetry values the Modal payload carries besides calculation inputs and functional metadata. Co-Authored-By: Claude Opus 5.5 --- docs/engineering/skills/observability.md | 20 +++++++++++++------ .../src/modal/app.py | 7 ++++--- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/docs/engineering/skills/observability.md b/docs/engineering/skills/observability.md index 54147618e..cc08a8e6d 100644 --- a/docs/engineering/skills/observability.md +++ b/docs/engineering/skills/observability.md @@ -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 @@ -170,11 +174,15 @@ from the gateway's submission of the job to the job's start in the worker. 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. Every attempt's record, - a preempted one's included, carries the same value, so the successful - attempt's record carries it too, unless a later attempt finds no earlier - record (below). It never counts the time between a preemption and the next - attempt. + 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 diff --git a/projects/policyengine-simulation-executor/src/modal/app.py b/projects/policyengine-simulation-executor/src/modal/app.py index cf0ed98ed..367df19e6 100644 --- a/projects/policyengine-simulation-executor/src/modal/app.py +++ b/projects/policyengine-simulation-executor/src/modal/app.py @@ -459,9 +459,10 @@ def _record_queue_seconds( """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, so every attempt's record carries the same - value. Jobs spawned without a submission time record none: a - budget-window batch's years, and jobs an older gateway spawned. + 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):