Repository navigation
fix(monitoring): add STT and finalization health signals - #22134
Conversation
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ad2811f0e7
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| "record": null | ||
| }, | ||
| { | ||
| "uid": "omi-stt-gate-unavailable", |
There was a problem hiding this comment.
Add the gate-unavailable rule to the automatic import set
On normal main-branch deployments this new alert is not provisioned: the checked gcp_cloud_run_metrics_egress.yml workflow invokes verify_pusher_live_alert_route.py --mode import, whose import set consists of LIVE_STT_IMPORT_UIDS plus live-alert-gate.json, but this UID appears in neither. The general Grafana workflow only applies all alert definitions during an explicit production dispatch, while push runs default to development and skip that step. Add this UID to the gated/import set so the new signal actually becomes live and is verified.
Useful? React with 👍 / 👎.
| "record": null | ||
| }, | ||
| { | ||
| "uid": "omi-stt-evidence-loss-critical", |
There was a problem hiding this comment.
Add the critical evidence rule to the live-STT allowlist
Adding this rule to alerts/live-stt.json without also adding its UID to LIVE_STT_IMPORT_UIDS makes every automatic alert import fail before contacting Grafana. I checked load_live_stt_import_rules() directly: it requires the file's UID set to equal LIVE_STT_IMPORT_UIDS ∪ LIVE_STT_PENDING_UIDS, and the current commit raises AlertRouteError: committed live-STT rules do not match the import allowlist and pending set. Update the allowlist so the monitoring workflow can provision any of the gated rules.
Useful? React with 👍 / 👎.
| "type": "prometheus", | ||
| "uid": "prometheus" | ||
| }, | ||
| "expr": "(sum(increase(omi_stt_fleet_health_write_dropped_total{job=\"backend-listen-metrics\"}[15m])) + sum(increase(omi_stt_cost_routing_evidence_errors_total{job=\"backend-listen-metrics\"}[15m])) + sum(increase(omi_stt_cost_routing_emission_ack_errors_total{job=\"backend-listen-metrics\"}[15m]))) / clamp_min(sum(increase(omi_stt_cost_routing_settlements_total{job=\"backend-listen-metrics\"}[15m])), 1)", |
There was a problem hiding this comment.
Zero-fill the sparse dropped-write term
On a freshly started fleet with no dropped writes, omi_stt_fleet_health_write_dropped_total has no time series because this labeled counter is never initialized. In PromQL, sum(increase(...)) over that absent family is an empty vector, so adding it to the two evidence-error sums makes the entire ratio empty; with noDataState: OK, this new critical rule will miss evidence/ack failures until some unrelated dropped write has first created a label child. Zero-fill the sparse term with or vector(0) or initialize the bounded label children at startup.
Useful? React with 👍 / 👎.
| "type": "prometheus", | ||
| "uid": "prometheus" | ||
| }, | ||
| "expr": "absent(listen_finalization_summary_last_success_timestamp_seconds) or max(listen_finalization_summary_last_success_timestamp_seconds) < bool time() - 600", |
There was a problem hiding this comment.
Deploy the freshness metric before activating its alert
Once the import allowlist failure is fixed, a normal main push will activate this critical absent-is-bad rule before its emitting workload is updated. I checked the workflow ordering: gcp_cloud_run_metrics_egress.yml automatically imports gated alerts when these monitoring files change, while gcp_backend_listen_helm.yml auto-runs only for backend-listen chart/secret changes, not these Python changes; the Cloud Run metrics bridge also keeps only omi_.*, so it cannot supply this listen_... gauge. The expression is therefore guaranteed to become true against the still-running backend-listen image and page after two minutes, potentially indefinitely until a separate rollout. Stage the alert paused or gate its import until the emitter has been deployed and observed.
Useful? React with 👍 / 👎.
| "__dashboardUid__": "omi-core-features", | ||
| "__panelId__": "30", |
There was a problem hiding this comment.
Link the freshness alert to the new summary-age panel
This alert links responders to omi-core-features panel 30, which is the existing “Oldest system-owned job” panel and queries listen_finalization_oldest_nonterminal_age_seconds; during the summary-read outage detected here that series is intentionally absent, so the linked panel only shows no data and does not expose the timestamp being alerted on. This commit adds the actual summary-age visualization as panel 19 on omi-resilience-fallbacks, so point the annotation there to make the alert's prescribed verification actionable.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 89b5f946fe
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| "updated": "2026-10-18T00:00:00Z", | ||
| "noDataState": "OK", | ||
| "execErrState": "KeepLast", | ||
| "for": "30m", |
There was a problem hiding this comment.
Remove the freshness-alert coverage gap
When a previously healthy summary publisher stops, the critical rule fires after roughly 20 minutes but becomes OK once its 30-minute lookback loses the last sample; this absent-series rule does not fire until its separate 30-minute pending period completes, around 60 minutes after the outage. That leaves an approximately 30-minute interval where the ongoing outage is reported as recovered. Shorten this pending period or keep the stale alert firing until the absent-series rule takes over.
Useful? React with 👍 / 👎.
| async for chunk in generate_stream_body(journey_attempt): | ||
| yield chunk |
There was a problem hiding this comment.
Close the delegated stream before leaving the wrapper
If a client disconnects after at least one SSE frame has been yielded, closing generate_stream() injects GeneratorExit while this wrapper is suspended at its own yield, but the async for does not synchronously close generate_stream_body(). Python later finalizes that inner async generator in a different task/context, where reset_usage_context(usage_token) raises because the ContextVar token was created in the original context; the usage and surface cleanup is therefore skipped and an unhandled async-generator exception is logged. Keep this as one generator or explicitly retain and await aclose() the inner iterator in the wrapper's finally.
Useful? React with 👍 / 👎.
| except Exception: | ||
| if not write_committed: | ||
| record_drop('redis_error') | ||
| logger.debug('STT cost-routing write bookkeeping failed', exc_info=True) |
There was a problem hiding this comment.
Preserve local benches after exhausted CAS contention
When all five cost-state CAS attempts lose to concurrent writers, _cost_update() raises _CostStateContention, which lands in this generic bookkeeping branch rather than the Redis-failure branch above. If the failed observation locally moved a target to stage 0, this path neither adds the state to _cost_unreconciled nor starts the retry backoff, so a fresh cached remote state can immediately override the local bench and continue routing sessions to the failing target. Handle exhausted contention separately while preserving the same local stage-0 reconciliation behavior used for pre-commit Redis failures.
Useful? React with 👍 / 👎.
Resolve rule-file conflicts with BasedHardware#22134 by appending the three NEG exporter rules to main's rule lists; regenerate the GMP inventory. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Prod listen stays `STT_ROUTING_MODE=on`, `STT_ROUTING_ON_PERCENT=100`.
This PR ships only the first-text instrumentation and runbook,
preserving production allocation. A separate draft stage-1 PR will carry
on/95 after the instrumented image has served on/100 for at least 60
minutes, with `image_tag` pinned to that same image.
Adds `omi_stt_routing_cohort_window_first_text_seconds{routing_arm}` at
the existing Parakeet-window first-emitted-text seam. The window socket
pins the managed session's arm before background work; only `off`,
`shadow`, and `on` labels exist. Existing histograms retain their schema
and semantics. This is window-leg latency, not all-provider end-to-end
timing; unmanaged sockets are excluded.
The runbook specifies 95→90→75→50→0, stage sample/dwell floors,
concurrent-control gates, operator review, and rollback to on/100 on the
same image. Chart, prod overlay, generated runtime manifest and flag
documentation retain on/100. The pipeline contract describes the
separate stage-1 change. No merge or deployment is included.
Image investigation: the canary/rollback image `5bb18b1` was not
identical to `ecd1f40`. #22134's metrics are exception-isolated, and
global off skips the scheduled score/cost writes; its backoff correction
preserves the deadline when no Redis write is attempted. #22075 adds one
cohort document read per account/pod/cache lifetime (60s), awaited up to
1.25s before the listen session, with a separate 4-worker/64-queue
executor. That is an admission confound, but the late first-text metric
begins after VAD speech, and rollback did not uniformly restore metrics.
Neither hunk is causally established as the regression, so this PR
contains no speculative health/cohort revert.
Validation: 255 focused tests passed (187 window, 27 cohort, 12
health-write fault/backoff, 29 resolver), plus 320 hermetic pre-deploy
tests. Tests used nice -n 19 through omi-heavy. Full repository
preflight passed all 38 checks after a serial rerun resolved a
concurrent temporary OpenAPI-directory cleanup race. Normal
pre-commit/pre-push hooks passed, including selected unit tests, Pyright
(zero errors), 17-image source closure, and runtime/deployment
contracts. The tests exercise real window/VAD/POST/receiver seams with
synthetic providers; production acceptance awaits a separately
authorized rollout.
Failure-Class: none
Product-Invariants: INV-MEM-4
INV-MEM-4: preserved. The generated runtime manifest retains listen
routing allocation at on/100; canonical intake, promotion receipts,
memory authority and projections retain their existing configuration and
behavior.
This is bounded observability and the runbook for a separately gated
allocation experiment; it does not change account migration authority,
credentials, data-plane routing, or user data. No GitHub workflow
change.
What changed and why
Implements the review follow-ups for PR #22134. Fleet-health attempted, dropped, and written metric increments are best-effort and logged on failure; post-commit cleanup, metrics, and identity checks cannot turn an acknowledged write into a Redis error or dropped write. Only the explicitly labelled
identity_changed_after_commitcase can count both written and dropped.The separate Redis backoff fix is a small live-path behavior change that reduces dropped cost writes after Redis recovers: an already-active backoff is counted and returned without sliding the deadline or marking local cost state unreconciled. The retry deadline moves only after an actual Redis failure or timeout.
chat_responseacceptance now starts with consumption of the response body inside a terminalizingtry/finally, including failures during app-awareness preparation and timezone lookup.mobile_chatacceptance remains at the HTTP response boundary because it measures the accepted client request; its stream observer continues to own client completion.The critical capture-summary alert now requires a previously published series and only fires when its timestamp is older than 900 seconds; absent data is OK for that rule. A separate warning requires no sample for 30 minutes plus another 30-minute hold. Its annotations say that an unshipped image, restart, or lease handoff can explain the absence.
Evidence:
/Users/dazheng/workspace/omi/data/run-2026-10-17-monitoring-prescriptions/HBCJ-thresholds-nllb.md(C, D, H, B, E) and/Users/dazheng/workspace/omi/data/run-2026-10-17-monitoring-prescriptions/A-capture-finalization.md; decisions:/Users/dazheng/workspace/omi/data/run-2026-10-17-monitoring-prescriptions/DECISIONS.md.Product invariants affected
none (confirmed by
scripts/pr-preflight --suggest)How it was verified
python3 backend/scripts/provision_monitoring_alerts.py --lintvalidated all 136 combined/split production alert definitions.make preflightpassed 35 selected checks, including the Firestore index guard. No due-query ordering change was made.ro-prodtier onprod-omi-gkeinbased-hardware. The live env key isFIRESTORE_READ_LEVERS. The activeprod-omi-backend-listendeployment (24/24 ready) and listen canary (4/4 ready) explicitly setsingleton_loopsto0. Four other listen deployments are scaled to zero; they omit this key, andprod-omi-backend-configalso omits it. The code defaults a missing lever to0, so singleton loops are off and every active listen pod is eligible to publish the summary. No secrets were read or printed.ro-prodCloud Monitoring queries had no samples for the new summary series or recent STT settlement/gate-unavailable signals, so replay against known-good and known-bad production intervals remains unavailable. The critical freshness rule usesnoDataState: OKuntil a series exists.git diff --checkpassed. The commit hooks formatted changed Python files.Tests
Targeted pytest ran at
nice -n 10; no full backend suite was run. The new tests cover raising metric counters, post-commit cleanup and identity-check failures, cost Redis backoff, and timezone setup failure before the chat stream body.UI evidence
UI-Evidence: none -- no UI changes.
Failure class (fixes)
Failure-Class: FC-alert-never-provably-fired
Line-Count-Exception: backend/utils/metrics.py | 1567 -> 1595 | adds STT write-attempt, write-result, dropped-write, and finalization freshness metrics required by these alerts
Rollback
Revert this PR. No production changes were made.
Deliberately unchanged
The conversation finalization due-query ordering remains unchanged because changing it would require review and provisioning of a Firestore composite index. No production deploy or mutation is included.