Repository navigation
feat(listen): event-loop lag and per-frame timing metrics - #22397
Conversation
D0a of the realtime-gateway plan: the signals the listen HPA retune
(CPU 70%, 35 sockets/pod) is gated on.
- omi_listen_event_loop_lag_seconds: asyncio sleep-drift probe, one
0.25 s task per process, started lazily by the first listen session.
- omi_listen_frame_processing_seconds{codec}: wall time from receiving a
client audio frame to the next receive; closed codec vocabulary.
- omi_vad_windows_total / omi_vad_inference_seconds_total: Silero windows
inferred by the streaming VAD gate and time spent in them.
No uid/session labels. Kill switch LISTEN_LOOP_METRICS_ENABLED, default
on (ops_kill). Overhead is under 1 us per frame.
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dd47e140fb
ℹ️ 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".
| """Listen event-loop health: loop lag, per-frame processing time and VAD inference rate. | ||
|
|
||
| These are the signals the listen HPA retune (CPU 70%, more sockets per pod) is gated on. | ||
| Labels are closed vocabularies only; never uid, session or conversation identifiers. |
There was a problem hiding this comment.
Document the telemetry in the listen pipeline contract
Add the new probe, frame/VAD metrics, kill switch, and HPA qualification semantics to backend/docs/listen_pusher_pipeline.mdx; this changes both the listen WebSocket receive path and streaming VAD observability, but the canonical pipeline map remains stale, leaving operators without the new signal and rollback contract in the document that owns this flow.
AGENTS.md reference: backend/AGENTS.md:L159-L159
Useful? React with 👍 / 👎.
| def record_vad_windows(windows: int, seconds: float) -> None: | ||
| if windows <= 0: | ||
| return |
There was a problem hiding this comment.
Record elapsed VAD work even without a full window
When a call only converts and buffers samples without completing a 512-sample window, windows is zero and this early return discards all elapsed time. This occurs in the ordinary 16 kHz path because the receiver flushes 30 ms (480 samples) at a time, so some _run_vad calls necessarily only buffer data; consequently omi_vad_inference_seconds_total, whose contract includes conversion and buffering and is intended to estimate VAD CPU share, systematically underreports that work. Increment the seconds counter independently while leaving the window counter conditional.
Useful? React with 👍 / 👎.
| current = _probe | ||
| if current is not None and current[0] is loop and not current[1].done(): | ||
| return current[1] | ||
| task = start_background_task(_probe_loop_lag(interval), name='listen_loop_lag_probe') | ||
| _probe = (loop, task) |
There was a problem hiding this comment.
Start the process-wide probe with a clean context
When the first accepted listen session supplies BYOK headers, this perpetual task is created from that session's context: asyncio.create_task inside start_background_task copies the current ContextVar values, including the validated provider keys and UID installed by the WebSocket auth dependency. Because the probe runs until pod shutdown, those credentials remain strongly referenced after the user's socket and normal request context finish; launch the process-wide probe from startup or with an explicitly clean context so it does not retain the first listener's secrets.
Useful? React with 👍 / 👎.
…metrics # Conflicts: # config/feature-flags.yaml
The probe was started lazily inside the first listen session, so asyncio copied that session's contextvars (validated BYOK keys and uid) into a task that lives for the pod lifetime. Start it inside a fresh contextvars.Context so it inherits nothing; start_background_task still tracks it for shutdown drain. Test proves no BYOK/uid reaches the probe. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…metrics # Conflicts: # config/feature-flags.yaml
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…oop metrics Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4559001564
ℹ️ 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".
| - `LADDER_V1_PRO_GATES_ENABLED` — Default-off ladder proactive and screen Pro gates; legacy prices unchanged (fail: closed) | ||
| - `LADDER_V1_RETIRE_PRO_ALIAS_ENABLED` — Default-off pro-as-Architect alias retirement; requires old-client and stored-record audit (fail: closed) | ||
| - `LADDER_V1_WIRE_IDENTITY_ENABLED` — Default-off approved mobile/Windows decoder floors; old installed clients preserve remap (fail: closed) | ||
| - `LISTEN_LOOP_METRICS_ENABLED` — Default on unless false; listen event-loop lag probe, per-frame processing histogram and VAD window counters (fail: open) |
There was a problem hiding this comment.
Wire the kill switch into deployed listen environments
The generated registry categorizes LISTEN_LOOP_METRICS_ENABLED as undeclared, and repo-wide inspection finds no binding in either backend/charts/backend-listen/*values.yaml or backend/deploy/runtime_env/. Consequently the deployed listen pods always use the enabled code default, so operators cannot apply the documented false rollback through the normal Helm/runtime-env deployment paths if this always-on instrumentation causes production load; add the flag to the backend-listen and corresponding runtime environment contracts.
AGENTS.md reference: backend/AGENTS.md:L153-L153
Useful? React with 👍 / 👎.
, #22362, #22461, #22471 sync) - config/feature-flags.yaml: kept both new rows (LISTEN_LOOP_METRICS_ENABLED from main, ENRICHMENT_ROUTE from integration); rendered doc regenerated. - #21932 moved the legacy sync runner's 500/503 into _run_sync_job_attempt: known gaps and the task-target KNOWN set gain the four _run_sync_job_attempt keys (legacy, leave with C11), drop the _run_sync_job_body/503 keys and recover_quarantine/503 (fixed by #22476).
Prod listen pods showed no omi_listen_event_loop_lag_seconds series. The code path is correct: every listen deployment runs an image older than #22397 (backend:8d7778a is its parent), while Cloud Run backend runs 4f43b2d, which contains it. Pin the two links the D0b gate depends on: run_listen_session starts the probe before building the runtime, and the listen /metrics handler renders the histogram from import. Document the image-tag check for a missing series. Failure-Class: none Co-Authored-By: Claude Opus 5.5 <[email protected]>
* test(backend): catch main up to the TTS rate-limit rename and retired task wake #15171 renamed the offloaded rate-limit call to redis_db.check_tts_rate_limit_for_user but left the desktop TTS unit stub and its identity assertion on the old function name, and #20665 retired routers.action_items._wake_task_changes while the shared-task 503 regression still patched it. Both files failed on origin/main and blocked every backend unit shard. Align the stub and assertion with the renamed call and drop the stale wake patch. * test(listen): guard lag-probe wiring and /metrics exposition Prod listen pods showed no omi_listen_event_loop_lag_seconds series. The code path is correct: every listen deployment runs an image older than #22397 (backend:8d7778a is its parent), while Cloud Run backend runs 4f43b2d, which contains it. Pin the two links the D0b gate depends on: run_listen_session starts the probe before building the runtime, and the listen /metrics handler renders the histogram from import. Document the image-tag check for a missing series. Failure-Class: none Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(listen): tie exposition test to the route wiring; fix frame-histogram doc Grok review on #22608: the exposition test did not use the listen route import, and the doc said every loop histogram renders from import, which is false for the codec-labelled frame histogram. Assert the route -> runtime -> probe module chain and the import-time registry collector, and document that the frame series appears only after the first timed frame. Failure-Class: none Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(listen): frame histogram child appears at receive-loop entry, not first frame Failure-Class: none Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(listen): exercise the deployed app's /metrics exposition in a fresh process Codex review: the exposition test imported routers.listen.runtime itself and called the metrics handler directly, so it kept passing if main.py stopped registering metrics.router, and its zero-count check only asserted the series name after earlier tests in the same file had already incremented the process-global histogram. Run the assertion path in a fresh interpreter instead: install the hermetic network blocker, import main (the deployed listen entrypoint per backend/Dockerfile CMD), make an unauthenticated request (401) and an authenticated one (200) through the real app routing, and assert the exact import-time 'omi_listen_event_loop_lag_seconds_count 0.0' with no probe started before or after serving. Subprocess CPU is not charged to the fast-unit duration guard, and the network blocker proves the path stays hermetic for the no-Redis CI lane. Failure-Class: none * test(sync): legacy import ratchet and enrichment outbox contracts Plan C (legacy sync consolidation) PR C1. Tests only; no runtime change. - tests/unit/test_sync_legacy_import_ratchet.py + fixtures/sync_legacy_import_baseline.json: freezes the 10 current importers (outside utils/sync and routers/sync.py) of the 19 legacy sync modules scheduled for retirement; new edges fail, stale edges must be removed, every edge carries a reviewed "why". - tests/integration/test_enrichment_outbox_contract_emulator.py: Firestore-emulator contracts for the sync enrichment outbox that the utils/enrichment move must keep: first-summary wake within 120s, coalescing, stale-token refusal, lease expiry repaired by the sweep, redirect custody transfer and the privacy fence. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(sync): address review — selector coverage, keyword imports, fixture teardown - Ratchet now runs for every in-scope importer on changed-file CI, not only the post-merge --all run: new shared scope predicate (tests/support/sync_legacy_ratchet_scope.py) wires the selector the same way the background-task ratchet is wired, so an importer under e.g. backend/utils/apps selects test_sync_legacy_import_ratchet.py. Contract tests pin the predicate against the ratchet's own scope. - import_module detection also accepts the keyword form (name='utils.sync.pipeline'); non-literal names still detect nothing. - Enrichment outbox emulator fixture deletes dormant receipts and synthetic conversation documents by key on teardown (uid is cleared on dormant rows, so the uid-query teardown misses them; parent deletes keep subcollections). - All function-local imports in the integration test hoisted to module scope (backend AGENTS.md import rules). - Baseline gains the reviewed upstream edge scripts/cap_hold_durability_emulator_test.py -> utils.sync.pipeline (rebased onto main that introduced cap-hold durability). * test(sync): address review — aliased import_module, survivor scope, selector tuple - import_module detection now resolves aliases bound by 'from importlib import import_module as load'; calls through the alias with a literal module name are dynamic-import edges. Non-importlib aliases with the same call shape still detect nothing (parametrized). - The ratchet no longer excludes the whole utils/sync/ package: only the retiring modules themselves and routers/sync.py are out of scope, so surviving in-tree callers (cap-hold core, recording_session_target) are scanned and their legacy edges are frozen in the baseline with reviewed whys. These are exactly the edges C11 (#22635, keep the cap-hold core) must cut; the shared selector predicate keeps its cheap superset and still defers narrow area selection to AREA_TESTS. - SYNC_LEGACY_RATCHET_TESTS now selects only the ratchet itself. test_workflow_contracts.py has no legacy-ratchet assertions; it keeps its own selection via workflow contract sources and backend/testing/ full-run prefixes, instead of riding every backend-Python selection. * test(listen): keep the child's network guard referenced for its whole body Codex review: 'block_outbound_network().__enter__()' drops the only reference to the _GeneratorContextManager, so CPython finalizes it (and its finally block restores the socket functions) before 'import main' runs — the hermetic claim was inert, and an environment supplying Stripe credentials could turn the import into real network calls. Enter the guard through an ExitStack held for the entire child body. Failure-Class: none * test(sync): address review — proven import_module bindings, relative targets, fence/IO contracts - Dynamic-import detection now requires proven importlib bindings: attribute receivers bound by 'import importlib [as imp]' and bare names bound by 'from importlib import import_module [as load]'. An unrelated obj.import_module(...) or a local function named import_module no longer fabricates a legacy edge and fails changed-file CI (V8). - Relative import_module targets ('.pipeline', package='utils.sync') resolve against the literal package argument — positional or keyword — with each leading dot beyond the first trimming the package, mirroring the interpreter. A relative name without a literal package detects nothing (-s). - Privacy-fence contract now exercises the race it names: phase 1 keeps the pre-blocked discard (entry fence), phase 2 lands the block between the entry fence and the claimed callback and proves the adapter's inner discard_blocked discards without ever invoking work; blocks are cleared between phases so each parametrized block path is really driven (-z). - Malformed-binding rejection now proves 'before any IO': the Firestore client accessor is replaced with a fail-fast mock for both the adapter and the outbox, so any pre-validation read/write fails the test (WB). * test(jobstore): port recovery discovery and progress parity invariants Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(backend): carry recovery custody invariants across job stores Failure-Class: FC-empty-asr-without-context-recovery Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(backend): pin recap fixture to a reproducible admission time The unmodified main test fails five assertions before noon because its fixture and recap selection use different dates. Pass one explicit afternoon instant through the existing production input seam; keep every assertion and production behavior unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(backend): port recovery and admission parity invariants Carry PL-057, PL-072 and PL-086 through the shared Store matrix. Keep the new-store cancellation gap strict and linked to issue #23761. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(mobile-perf): upload-success window, sparse scoring, semantics knob; tag lag stalls with work in flight - --upload accept --upload-wals N appends wal_sync_upload_success: synthetic uploads and jobs drive real sync phases, persistence and reconcile. - cold_start, home_idle_sync_refresh and the upload window are sparse: cold readiness keeps the 15% spread gate and each run has a stall budget (<=2 stalls over 100 ms, <=500 ms). Dense windows keep 15% p90; no run dropped. - Semantics is off for heavy perf by default; --semantics on is a separate dataset and compare refuses mixed settings. - LagWorkRegistry: bounded, allocation-free begin/end; mobile_lag_stall records overlapping sync/upload/reconcile/WAL-load work. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(mobile-perf): dry-run tests pass an explicit artifact root Without one, device_run.main() exits 2 on hosts with no scratch mount, so the manifest check failed on ordinary Linux checkouts. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(jobstore): qualify fenced shard pulls across stores Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(jobstore): require available backends in the selected proof lane Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(outbox): preserve durable enqueue across wake failures (PL-042) Failure-Class: none Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(outbox): verify committed enqueue result identity Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(backend): qualify partial-pull leases across store backends Port PL-194 into the shared scheduler/Store matrix and existing emulator proof lane. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(backend): qualify pending deletion across old and new stores Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(backend): PL-049 positive-speech custody follows the one Soniox second chance Main a866d27 (10-30) gives Modulate-empty held units with positive speech one independent Soniox second chance. The PL-049 case written 10-26 asserted no second provider at all, so it failed on every store after the merge. It now pins the new contract: the second chance is spent at most once across repeated sweeps, and an uncertain call keeps audio, intent and custody held. Measured silence still settles without any paid call. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test: qualify pull-batch parity across Firestore and Postgres Preserve PL-321/322/323 at frame boundaries, buffered query overlays and bounded walk stops. Register the shared matrix in the existing emulator-proof runner. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test: clean coordination fixtures within their owned namespace Include merge holds beside pull claims and prove cleanup preserves foreign namespaces and synthetic customer rows. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(backend): enforce held-custody and no-spend recovery parity Qualify PL-061, PL-105 and PL-363 on old Firestore, new Postgres and the simulator through the existing Store harness. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(backend): keep partial-custody identity distinct from producer outcomes Use PL-396 for phone custody and leave PL-061 producer client_status as a separate missing invariant in the parity ledger. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(backend): declare isolated stage and fence paid refusal markers Make the conformance fixture independent of CI stage defaults and reject paid-attempt metadata on a local no-spend refusal. Clarify minimum CI stores versus all-store cutover qualification. Co-Authored-By: Claude Opus 5.5 <[email protected]> * style(firmware): match CI clang-format on the safe-mode snapshot initializer CI's clang-format 18 attaches the compound-literal brace and drops the space before it; break nothing else and keep the initializer alignment one column left. * test(backend): keep the enrichment proof clock a real clock The consumer's heartbeat hold cap reads time.monotonic, so the injected consumer clock must carry the full time module with only the wall-clock pinned, or every PL-397 delivery dies on AttributeError before the callback runs. * style(firmware): drop the compound-literal brace space CI's clang-format rejects CI formats firmware with clang-format 18, which attaches the brace after the compound-literal cast; the local 23 kept a space and realigned one column right, so the Formatting job failed on the merge preview. Commit with clang-format 18 first on PATH so the pre-commit hook agrees. * test(backend): inventory lifecycle writers and latch invariant gaps * test(backend): re-baseline the legacy-sync import ratchet to the folded tree The ratchet fixture arrived from #22390 with a baseline ~4.5k commits stale: main gained nine importers of the retiring legacy sync modules (staging syncsplit proof, backfill worker control/job, empty-success guard, watch recovery e2e, capture coverage lanes) and lost two baseline edges (enrichment callback, cap_recovery_audio coverage replay). Regenerated with the ratchet's own --write pass, then reviewed each edge's why against the retire milestones (C10/C11). * test(backend): align partial-pull conformance with the current lease API The PL-194 file predates two scheduler changes main landed since its base: - The pull transaction now returns (receipts-or-None, eligible, observations) where each receipt is (lease, enqueued_at, relet); Scheduler.pull is what unwraps receipts into LeasedWork. The conformance helper treated result[0][0] as a lease, so its committed list held receipt tuples against pull's LeasedWork list, and aborted['lease'].item raised AttributeError. Unwrap receipts to the lease on both sides so the whole test speaks the one shape main's lease API returns. - A multi-lease abort rolls back every receipt in its transaction, so the exact 'failing_lease - 1 committed' count only holds one lease per transaction; pin the documented BATCH_PULL_MULTI_LEASE_ENABLED kill switch (as the file already pins shard spread and cap dispatch). - Shard-spread selection reads control_candidates (plural fanout), not the singular control_candidate the overlap test paused; hook both, each wrapping its own original, since the singular delegates to the plural. All 24 partial-pull parametrizations plus both overlap cases pass on sim and Postgres locally; emulator legs stay with CI's proofs job. --------- Co-authored-by: David Zhang <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
Summary
D0a of the realtime-gateway plan (workstream D). Adds the listen signals that the HPA retune (D0b: CPU 70%, 35 sockets/pod instead of 22) is gated on. David approved the sequence on 2026-10-19.
omi_listen_event_loop_lag_secondsasyncio.sleepdrift beyond a 0.25 s probe interval; one probe per process, started by the first listen sessionomi_listen_frame_processing_secondscodec(closed: opus, aac, lc3, pcm8, pcm16, multi_channel, other)receive()omi_vad_windows_totalrate()= VAD inferences/somi_vad_inference_seconds_totalLISTEN_LOOP_METRICS_ENABLED, registered asops_killand on by default (ship on by default).false/0/off/nodisables the probe, frame timing and VAD counting. It is read once per session or gate, so rolling back takes an env change plus a restart.start_background_task, so shutdown'sdrain_background_taskscancels it.Files: new
backend/utils/observability/listen_loop.py. The hooks inrouters/listen/receiver.py(+5),routers/listen/runtime.py(+5) andutils/stt/vad_gate.py(+7) are small. This PR does not touch the files edited by #22365 (soniox_idle, live_metrics) or #22372 (live_reason, parakeet_window).Line-Count-Exception: backend/routers/listen/receiver.py | 2755 -> 2760 | five lines of frame-timer hooks at the receive loop; the timing logic lives in utils/observability/listen_loop.py
Product invariants affected
none
Failure class (fixes)
Failure-Class: new
New definition added in this PR:
.github/failure-classes/FC-lifetime-task-inherits-request-context.json. This covers review finding 1. The lag probe was started lazily inside the first listen session, soasyncio.create_taskcopied that session's validated BYOK keys and uid into a task that lives as long as the pod. The probe now starts from an emptycontextvars.Context().test_lag_probe_does_not_inherit_session_byok_or_uid_contextfails without the fix and passes with it. No existing class covers a lifetime task inheriting request context;FC-per-request-credential-mutates-shared-client-configcovers shared client config, not task context.Review round 2 (Grok, c79b762)
record_vad_windowsnow addsomi_vad_inference_seconds_totalwhenever seconds > 0 andomi_vad_windows_totalonly when windows > 0, so buffering-only calls keep their time.backend/docs/listen_pusher_pipeline.mdxgains a "Listen loop health metrics" subsection.Rollout and gate for D0b
histogram_quantile(0.99, sum by (le) (rate(omi_listen_event_loop_lag_seconds_bucket[5m])))below 50 ms. It also checks first-text per arm and terminal-after-text before and after.Test plan
pytest tests/unit/test_listen_loop_metrics.py: 23 passed. Covers the kill-switch parsing, the closed codec vocabulary and absence of identity labels, a lag probe that detects an 80 ms loop block and is idempotent per loop, the probe disabled under the kill switch, VAD window counting on vs off, and receiver frame timing that counts audio frames only (not text or heartbeats) on vs off.test_vad_gate.py(130),test_listen_receiver_frame_recovery.py,test_listen_receiver_decode_failure_report.py,test_listen_runtime_regressions.py,test_listen_receiver_opus_frame_capacity.py.scan_async_blockers.py: 0.scan_import_time_side_effects.py: 0.check_feature_flag_registry.py: OK. pyright on the changed files: 0 errors.Known main-branch harness failures from #22321 (goldens, sim threshold, gauntlet batch-empty-asr-recovery) are fixed by #22385 and are unrelated to this PR.
🤖 Generated with Claude Code