Repository navigation
feat(batch): 2-hour timeliness alarm for unpublished batch audio - #24364
Conversation
David (2026-11-02): process most batch audio within 30 minutes of finalization and alarm at 2 hours,
including failed_held, quarantined and repair waits.
The batch queue sample now exports, at most every 5 minutes per process:
- omi_batch_timeliness_new_oldest_age_seconds{leg}: oldest unpublished unit admitted at or after the
epoch (uncommitted with policy holds skipped, quarantined, projection, sibling_held)
- omi_batch_timeliness_new_over_sla_units{leg} and omi_batch_timeliness_backlog_units{leg}: new breaches
versus units from before the epoch, which stay visible as counts and never alarm
- omi_batch_timeliness_samples_total{outcome} and a truncation gauge
Kill switch BATCH_TIMELINESS_ALARM_ENABLED (default on). Epoch BATCH_TIMELINESS_EPOCH defaults to
2026-11-02T06:09:00Z, when the target was set. Every query rides an existing index; validated read-only
against prod. Alert-only: no scheduler, ramp, gate or hard-3 trigger reads it.
Two agent-tier Grafana rules wait in charts/monitoring/pending/ until the series exist in prod; the apply
step is in charts/monitoring/batch-projection/README.md.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…index guard Co-Authored-By: Claude Opus 5.5 <[email protected]>
…switch Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
There was a problem hiding this comment.
6 issues found across 10 files
Confidence score: 3/5
- In
backend/utils/batch_pipeline/metrics.py, a truncated uncommitted walk exports an age of0, so the 2h alert can treat an incomplete scan as healthy even when an older unit exists. Make truncation visible to the alert instead of reporting a healthy age. - In
backend/database/batch_pipeline_store.py, the timeliness sample skipsprovider_pendingandrecord_pending, so those units never contribute to age alarms or backlog metrics. Include both states in the active indexed scan. - In
backend/charts/monitoring/pending/batch-timeliness.json,$B < 900breaks for valid cadences up to 3600 seconds: it can suppress breach alerts and repeatedly fire the stale alert. Clamp the threshold to the configured cadence. - In
backend/config/batch_timeliness.py, a naivetimeliness_epochis interpreted in the host's local timezone, shifting the backlog and alarm boundary. Treat parsed values without an offset as UTC.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="backend/config/batch_timeliness.py">
<violation number="1" location="backend/config/batch_timeliness.py:28">
P2: `timeliness_epoch` treats an epoch without a UTC offset as local time, not UTC. An override like `2026-11-02T06:09:00` moves the backlog/alarm boundary by the host's UTC offset. Assume UTC when the parsed value is naive.</violation>
<violation number="2" location="backend/config/batch_timeliness.py:30">
P3: A malformed `BATCH_TIMELINESS_EPOCH` falls back to the default epoch without any warning. Log the rejected value once before returning the default so a bad override is visible on the worker.</violation>
</file>
<file name="backend/charts/monitoring/batch-projection/README.md">
<violation number="1" location="backend/charts/monitoring/batch-projection/README.md:33">
P2: The read budget is wrong: the hold-skipping walks can read up to 140 documents per sample (7 walks x `TIMELINESS_HOLD_SCAN_LIMIT` of 20), not 40. Correct the figure so cost and quota planning uses the real bound.</violation>
</file>
<file name="backend/utils/batch_pipeline/metrics.py">
<violation number="1" location="backend/utils/batch_pipeline/metrics.py:238">
P2: When the bounded uncommitted walk is truncated, this exports `0` for the `uncommitted` age even though an older unit may exist. The 2h alert reads that 0 as healthy, and no rule consumes `omi_batch_timeliness_scan_truncated`. Export an unmeasured value for that leg, and make the alert fire on `scan_truncated == 1`.</violation>
</file>
<file name="backend/charts/monitoring/pending/batch-timeliness.json">
<violation number="1" location="backend/charts/monitoring/pending/batch-timeliness.json:63">
P2: `$B < 900` assumes a cadence below 15 minutes, but the documented and implemented cadence allows 3600 seconds. Longer valid cadences suppress this breach alert and repeatedly trigger the stale alert; clamp the cadence below 900 seconds or make the freshness threshold follow the configured cadence.</violation>
</file>
<file name="backend/database/batch_pipeline_store.py">
<violation number="1" location="backend/database/batch_pipeline_store.py:650">
P2: The timeliness sample omits `provider_pending` and `record_pending`, so unpublished provider and repair-wait units never contribute to either the age alarm or backlog metrics. Add both states to the active indexed scan.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| def timeliness_epoch() -> float: | ||
| raw = os.getenv('BATCH_TIMELINESS_EPOCH', '').strip() or DEFAULT_EPOCH | ||
| try: | ||
| return dt.datetime.fromisoformat(raw.replace('Z', '+00:00')).timestamp() |
There was a problem hiding this comment.
P2: timeliness_epoch treats an epoch without a UTC offset as local time, not UTC. An override like 2026-11-02T06:09:00 moves the backlog/alarm boundary by the host's UTC offset. Assume UTC when the parsed value is naive.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/config/batch_timeliness.py, line 28:
<comment>`timeliness_epoch` treats an epoch without a UTC offset as local time, not UTC. An override like `2026-11-02T06:09:00` moves the backlog/alarm boundary by the host's UTC offset. Assume UTC when the parsed value is naive.</comment>
<file context>
@@ -0,0 +1,38 @@
+def timeliness_epoch() -> float:
+ raw = os.getenv('BATCH_TIMELINESS_EPOCH', '').strip() or DEFAULT_EPOCH
+ try:
+ return dt.datetime.fromisoformat(raw.replace('Z', '+00:00')).timestamp()
+ except ValueError:
+ return dt.datetime.fromisoformat(DEFAULT_EPOCH.replace('Z', '+00:00')).timestamp()
</file context>
| return dt.datetime.fromisoformat(raw.replace('Z', '+00:00')).timestamp() | |
| parsed = dt.datetime.fromisoformat(raw.replace('Z', '+00:00')) | |
| if parsed.tzinfo is None: | |
| parsed = parsed.replace(tzinfo=dt.timezone.utc) | |
| return parsed.timestamp() |
| Config: `BATCH_TIMELINESS_ALARM_ENABLED` (default on; `false` stops the Firestore reads), | ||
| `BATCH_TIMELINESS_EPOCH` (default `2026-11-02T06:09:00Z`, when the target was set) and | ||
| `BATCH_TIMELINESS_INTERVAL_SECONDS` (default 300, clamped to 60–3600). Each sample uses existing indexes only: | ||
| about 10 single-document or count reads, plus at most 40 for the hold-skipping walks. |
There was a problem hiding this comment.
P2: The read budget is wrong: the hold-skipping walks can read up to 140 documents per sample (7 walks x TIMELINESS_HOLD_SCAN_LIMIT of 20), not 40. Correct the figure so cost and quota planning uses the real bound.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/charts/monitoring/batch-projection/README.md, line 33:
<comment>The read budget is wrong: the hold-skipping walks can read up to 140 documents per sample (7 walks x `TIMELINESS_HOLD_SCAN_LIMIT` of 20), not 40. Correct the figure so cost and quota planning uses the real bound.</comment>
<file context>
@@ -0,0 +1,54 @@
+Config: `BATCH_TIMELINESS_ALARM_ENABLED` (default on; `false` stops the Firestore reads),
+`BATCH_TIMELINESS_EPOCH` (default `2026-11-02T06:09:00Z`, when the target was set) and
+`BATCH_TIMELINESS_INTERVAL_SECONDS` (default 300, clamped to 60–3600). Each sample uses existing indexes only:
+about 10 single-document or count reads, plus at most 40 for the hold-skipping walks.
+
+The metric is alert-only. No scheduler, ramp, hard-3 rollback trigger or gate reads it.
</file context>
| about 10 single-document or count reads, plus at most 40 for the hold-skipping walks. | |
| about 10 single-document or count reads, plus at most 140 for the hold-skipping walks (7 walks x 20 documents). |
| ) | ||
| return | ||
| for leg, started in sample['new_oldest'].items(): | ||
| self.timeliness_age.labels(leg).set(max(0.0, now - started) if started is not None else 0) |
There was a problem hiding this comment.
P2: When the bounded uncommitted walk is truncated, this exports 0 for the uncommitted age even though an older unit may exist. The 2h alert reads that 0 as healthy, and no rule consumes omi_batch_timeliness_scan_truncated. Export an unmeasured value for that leg, and make the alert fire on scan_truncated == 1.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/batch_pipeline/metrics.py, line 238:
<comment>When the bounded uncommitted walk is truncated, this exports `0` for the `uncommitted` age even though an older unit may exist. The 2h alert reads that 0 as healthy, and no rule consumes `omi_batch_timeliness_scan_truncated`. Export an unmeasured value for that leg, and make the alert fire on `scan_truncated == 1`.</comment>
<file context>
@@ -173,8 +215,35 @@ def refresh(self, store: Store, now: float) -> None:
+ )
+ return
+ for leg, started in sample['new_oldest'].items():
+ self.timeliness_age.labels(leg).set(max(0.0, now - started) if started is not None else 0)
+ for leg, units in sample['new_over_sla'].items():
+ self.timeliness_over_sla.labels(leg).set(units)
</file context>
| self.timeliness_age.labels(leg).set(max(0.0, now - started) if started is not None else 0) | |
| if started is None and sample['truncated'] and leg == 'uncommitted': | |
| self.timeliness_age.labels(leg).set(float('nan')) | |
| else: | |
| self.timeliness_age.labels(leg).set(max(0.0, now - started) if started is not None else 0) |
| "type": "__expr__", | ||
| "uid": "__expr__" | ||
| }, | ||
| "expression": "$A > 7200 && $B < 900", |
There was a problem hiding this comment.
P2: $B < 900 assumes a cadence below 15 minutes, but the documented and implemented cadence allows 3600 seconds. Longer valid cadences suppress this breach alert and repeatedly trigger the stale alert; clamp the cadence below 900 seconds or make the freshness threshold follow the configured cadence.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/charts/monitoring/pending/batch-timeliness.json, line 63:
<comment>`$B < 900` assumes a cadence below 15 minutes, but the documented and implemented cadence allows 3600 seconds. Longer valid cadences suppress this breach alert and repeatedly trigger the stale alert; clamp the cadence below 900 seconds or make the freshness threshold follow the configured cadence.</comment>
<file context>
@@ -0,0 +1,288 @@
+ "type": "__expr__",
+ "uid": "__expr__"
+ },
+ "expression": "$A > 7200 && $B < 900",
+ "intervalMs": 1000,
+ "maxDataPoints": 43200,
</file context>
|
|
||
| # 2-hour timeliness alarm (David, 2026-11-02). Every query rides an existing index: jobs (state, enqueued_at), | ||
| # the capacity index, jobs (priority, retry_started_at) and results (projection_state, committed_at). | ||
| TIMELINESS_ACTIVE_STATES = ('leased', 'result_ready', 'vendor_held') |
There was a problem hiding this comment.
P2: The timeliness sample omits provider_pending and record_pending, so unpublished provider and repair-wait units never contribute to either the age alarm or backlog metrics. Add both states to the active indexed scan.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/database/batch_pipeline_store.py, line 650:
<comment>The timeliness sample omits `provider_pending` and `record_pending`, so unpublished provider and repair-wait units never contribute to either the age alarm or backlog metrics. Add both states to the active indexed scan.</comment>
<file context>
@@ -642,6 +645,91 @@ def oldest_retry(client: Any, namespace: str, priority: int) -> float | None:
+# 2-hour timeliness alarm (David, 2026-11-02). Every query rides an existing index: jobs (state, enqueued_at),
+# the capacity index, jobs (priority, retry_started_at) and results (projection_state, committed_at).
+TIMELINESS_ACTIVE_STATES = ('leased', 'result_ready', 'vendor_held')
+TIMELINESS_UNCOMMITTED_STATES = (*TIMELINESS_ACTIVE_STATES, 'ready', 'retry')
+TIMELINESS_HOLD_SCAN_LIMIT = 20
</file context>
| TIMELINESS_ACTIVE_STATES = ('leased', 'result_ready', 'vendor_held') | |
| TIMELINESS_ACTIVE_STATES = ('leased', 'result_ready', 'vendor_held', 'provider_pending', 'record_pending') |
| try: | ||
| return dt.datetime.fromisoformat(raw.replace('Z', '+00:00')).timestamp() | ||
| except ValueError: | ||
| return dt.datetime.fromisoformat(DEFAULT_EPOCH.replace('Z', '+00:00')).timestamp() |
There was a problem hiding this comment.
P3: A malformed BATCH_TIMELINESS_EPOCH falls back to the default epoch without any warning. Log the rejected value once before returning the default so a bad override is visible on the worker.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/config/batch_timeliness.py, line 30:
<comment>A malformed `BATCH_TIMELINESS_EPOCH` falls back to the default epoch without any warning. Log the rejected value once before returning the default so a bad override is visible on the worker.</comment>
<file context>
@@ -0,0 +1,38 @@
+ try:
+ return dt.datetime.fromisoformat(raw.replace('Z', '+00:00')).timestamp()
+ except ValueError:
+ return dt.datetime.fromisoformat(DEFAULT_EPOCH.replace('Z', '+00:00')).timestamp()
+
+
</file context>
…projection waits Review round 1 (Luna, FIX-FIRST) and lead ruling 2cef45: - projection leg clocks from the unit's admission (job enqueued_at behind the oldest pending results), not from commit, so 1h59m to commit plus 1h59m unprojected reads as about 4h - live vendor holds are walked apart from active work and cannot hide an overdue unit; truncation is a per-leg gauge with an agent-tier blind rule on the uncommitted leg - new assignment_held leg: committed units whose projection receipt is quarantined (job recovery_state held), the real holes; needs the new jobs (state, recovery_state, enqueued_at) composite index - the sibling leg is renamed quarantine_held_rows and stays visible-only: most rows are ready receipts already in the conversation - README read ceiling corrected (under 300 reads per sample) Co-Authored-By: Claude Opus 5.5 <[email protected]>
… store surface unchanged test_jobstore_protocol_parity requires every store backend to serve the FirestoreStore surface. The metrics sample now calls timeliness_sample(store.client, store.namespace, ...), as refresh_projection does. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…runcation fix Open question (lead asking David): does a terminal empty_asr unit with no recoverable speech count as processed? TERMINAL_EMPTY_IS_PROCESSED in config/batch_timeliness.py answers it in one line. Default False: those units stay in the 2h alarm. True subtracts them exactly from the quarantined leg. A terminal_empty count is exported either way so the units stay visible. "No recoverable speech" reuses the silence contract: failed held, recovery failure empty_asr, measured held VAD speech exactly 0. On prod at 10:36Z no quarantined empty_asr unit met that (13 of 13 new ones carry measured speech), so the switch changes nothing today. Also: a walk ordered by a clock other than admission reports truncation on a full page even when it found admitted rows, since an older admission can sit behind it. The blind rule now reads every leg. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…stry and document the switch Co-Authored-By: Claude Opus 5.5 <[email protected]>
… default David, 2026-11-02 10:45Z: "finished recording counts as processed". The lead ruled the switch defaults that way (alarm only). Units with measured speech stay in the alarm, and terminal_empty stays a visible count. No speech threshold. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Why
David, 2026-11-02 06:09Z: "We should be processing most audio within 30 mins of finalization, and alarm on 2 hours." Failed-held, quarantined and repair waits must count, because that is how 165 segments were lost on 11-01. The existing projection gauge reads 14.9 days of held backlog, so any plain age alarm would fire forever on day one.
What
The batch queue sample (
QueueMetrics.refresh, FirestoreStore only) exports, at most once per 5 minutes per process:omi_batch_timeliness_new_oldest_age_seconds{leg}uncommitted(policy and vendor holds skipped),quarantined(every recovery state),assignment_held(committed, projection receipt quarantined),projection;quarantine_held_rowsvisible onlyomi_batch_timeliness_new_over_sla_units{leg}terminal_empty(visible only)omi_batch_timeliness_backlog_units{leg}omi_batch_timeliness_scan_truncated{leg}/omi_batch_timeliness_samples_total{outcome}BATCH_TIMELINESS_ALARM_ENABLED, default on, registered asops_kill.BATCH_TIMELINESS_EPOCH, default2026-11-02T06:09:00Z, when the target was set.BATCH_TIMELINESS_INTERVAL_SECONDS, default 300.TERMINAL_EMPTY_IS_PROCESSEDinconfig/batch_timeliness.py, defaultTrue(see below).database/batch_pipeline_indexes.pywithfirestore.indexes.jsonregenerated:(state, recovery_state, enqueued_at)forassignment_held, and(state, recovery_state, recovery.failure.reason, measured_held_vad_speech_seconds, enqueued_at)forterminal_empty. Until both are READY the sample countserrorand the stale rule fires.charts/monitoring/pending/batch-timeliness.json, because the monitoring contracts reject rules on series that don't exist in prod yet:omi-batch-unit-unpublished-2h: max new age over the uncommitted, quarantined, assignment_held and projection legs > 7200 s, with a fresh sample.omi-batch-timeliness-sample-staleomi-batch-timeliness-scan-blind: any leg's walk full for 30 minutes.charts/monitoring/batch-projection/README.md.Terminal empty_asr counts as processed (David, 2026-11-02 10:45Z)
David: "finished recording counts as processed". The lead ruled the one-line switch
TERMINAL_EMPTY_IS_PROCESSEDdefaults that way, alarm only, with no speech threshold.True: units that arefailed_heldwith recovery failureempty_asrand measured held VAD speech exactly 0 leave thequarantinedleg. Its count subtracts them exactly, so a page of them can hide a younger unit but never a breach.False: puts them back in the 2h alarm.terminal_emptystays a visible count either way.held_silence_allowed: census exactly 0).Measured (ro-prod, 10:36Z, counts only): no quarantined
empty_asrfailed-held unit had zero measured speech. All 13 admitted since the epoch carry some: 10 under 2 s, 2 at 2–10 s, 1 over 10 s. Of 530 backlog units, 137 have no VAD evidence at all. So the default changes nothing in today's alarm.Measured (ro-prod, read-only, 2026-11-02)
fire_test.py): epoch 03:00Z FIRES ($A = 18,155 s); epoch 06:09Z is clear.empty_asr), so once deployed the alarm keeps firing until those are resolved within 2 h. That is the intended signal.Round 1 fixes (Luna FIX-FIRST, lead ruling 2cef45)
enqueued_at(oldest 50 pending results, then job reads), not from commit.assignment_heldleg, the real holes per siblingrelease.store.clientinstead of a new store method, which fixestest_jobstore_protocol_parity.Round 2 delta (lead accepted 5e44c47 without a round 3, 11:42Z)
terminal_emptycount, above.available_at, retry byretry_started_at) reports truncation on a full page even when it found admitted rows, since an older admission can sit behind it. The blind rule now reads every leg.Trueper David's ruling.Tests
TERMINAL_EMPTY_IS_PROCESSED).backend/test.sh:test_batch_pipeline_timeliness.py(15),test_batch_pipeline_metrics.py,test_entitlement_versions.py,test_storefront_presentation.py, and the Firestore index/query-shape guard (test_firestore_query_shapes,test_firestore_indexes,test_firestore_index_config,test_firestore_index_selector_contract,test_firestore_query_contract).Deploy
Batch worker image (lead's train), after the index reconcile. Rollback: set
BATCH_TIMELINESS_ALARM_ENABLED=false, or revert. Nothing else reads the series.🤖 Generated with Claude Code