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..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 @@ -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 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..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,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. @@ -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``. diff --git a/libs/policyengine-simulation-contract/tests/test_job_progress.py b/libs/policyengine-simulation-contract/tests/test_job_progress.py index 600b6bf13..2964c3170 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,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): diff --git a/projects/policyengine-simulation-executor/src/modal/app.py b/projects/policyengine-simulation-executor/src/modal/app.py index 106a0e2f5..367df19e6 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,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, *, @@ -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 @@ -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, ) 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 d473bf689..c06575233 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,245 @@ 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_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_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 + ): + # Jobs that budget-window batches 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/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, 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(