Repository navigation
fix(stt): pace bounded replay and recover past provider queue deaths - #20357
Conversation
|
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.
2 issues found across 10 files
Confidence score: 4/5
- In
backend/utils/stt/resilient_stream.py, teardown during replay is recorded as a failed reconnect and degraded hop. Check the inactive or terminal state before handling the replay rejection. - In
backend/tests/unit/test_live_replay_provider_pairs.py,GateStateandreplay_packetsare imported inside test functions, contrary to the backend import rule. Move both imports to the module header.
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/tests/unit/test_live_replay_provider_pairs.py">
<violation number="1" location="backend/tests/unit/test_live_replay_provider_pairs.py:127">
P3: `GateState` and `replay_packets` are imported inside test functions, contrary to the backend import rule. Move both imports to the module header.</violation>
</file>
<file name="backend/utils/stt/resilient_stream.py">
<violation number="1" location="backend/utils/stt/resilient_stream.py:357">
P3: A teardown during replay makes `replay_chunks` return a rejection, so this raises into the generic handler and records a failed reconnect and degraded hop instead of teardown. Check the inactive/terminal state before treating the returned index as a send failure.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
…ing-replay Cancellation while fallback_socket_is_serving vetted the fresh raw leg left it open: the CancelledError handler only closed the wrapped replacement, which does not exist until after vetting. Track the raw leg and retire + close it when cancellation lands before adoption. A replay rejection reported because the session owner tore us down is not a provider send failure. Check host activity before treating the replay_chunks rejection as send_failed, so the pacer stop is classified as teardown (outcome='teardown', no terminal settlement) instead of a failed reconnect. Verified: BACKEND_UNIT_TEST_FILE_LIST (test_live_evidence_settlement, test_live_stt_resilient_stream, test_live_replay_provider_pairs) via backend/test.sh — 86 passed; new regression tests test_cancelled_liveness_probe_closes_the_unadopted_raw_leg and test_owner_teardown_during_replay_is_classified_as_teardown.
…imports Regression tests for the review fixes: cancellation during the liveness probe must close the unadopted raw leg, and a replay rejection caused by owner teardown must record outcome='teardown' without a provider-failure settlement. Move function-level imports in test_live_replay_provider_pairs.py to the module header per the backend import rule (backend/AGENTS.md), covering all eight sites so a re-review does not re-flag the same pattern. Verified: backend/test.sh with BACKEND_UNIT_TEST_FILE_LIST — 86 passed across the three touched files; 44 passed in test_live_evidence_settlement.
858b126 to
ad29f21
Compare
|
Addressed the three review threads from the monitor pass (head
Regression tests added for both production fixes ( |
) ## Summary **Supersedes #20357. Merges inert; enabled only on the canary Deployment via `STT_FAILOVER_RECOVERY_ENABLED=true`. No PR merge or deployment performed.** The pod-level switch defaults false in code, dev/prod listen charts, runtime base and overlays. One mode is read at session construction and propagated to the receiver, successor legs, callbacks and spawned writers; a session never switches mid-flight. Unset/false/invalid values retain current main's recovery, replay, capture, paid writer, rejection/circuit and settlement behavior, including #20393's managed `owner_closing` fence. The semantics-preserving PCM ring optimization below remains active in both modes. Failure-Class: FC-live-stt-audio-lost-on-provider-death No provider-order, allocation, routing-default, health namespace or workflow changes. Keep `STT_ROUTING_MODE=shadow`, `STT_ROUTING_ON_PERCENT=0`. Main through `bf48ed0e68674a0d5d3c3e17f57dff042156b15d` was merged normally in `abcadb4bc5b6418d9fe969baa5262e7eda054540`, retaining upstream STT log sanitization, #20418 canary tooling, #20433 abandoned Parakeet queue cleanup and subsequent serving changes. The legacy controller/replay/paid-writer baseline remains `147f77d86a`: later main merges change none of those extracted recovery functions. The new main Parakeet POST-budget/queue-timeout contract applies identically in both flag modes, and unrelated deployment settings retain latest main exactly. The merge hook's unrelated Flutter formatting was restored byte-for-byte to main; locked dependency resolution made all 117 restored files format-stable, and the repair commit passed the normal hook. No stash, rebase, force-push, hook bypass, customer transcript/audio read, cloud mutation, PR merge or deploy. ## PCM ring hot path — independent of recovery enablement `AudioRingBuffer._append_bytes` now keeps the newest capacity-sized suffix with at most two memoryview bulk copies, replacing a Python loop for every byte. Capacity, physical overwrite order, absolute counters, span ledger and read APIs are unchanged. No await, lock, thread or bytearray resize was added; the existing caller ownership/scheduling contract is unchanged. Local Python 3.11.15 microbenchmark, `time.process_time_ns`, median of five runs over 135 s of 16 kHz mono PCM16 (4,320,000 bytes). Allocation/payload creation are outside timing; the public positioned-write path and span recording are included. These are local measurements under load, not production CPU measurements: | Input | Before CPU / 135 s | After CPU / 135 s | CPU per second of audio, before → after | | --- | ---: | ---: | ---: | | 4,500 live 30 ms packets | 127.055 ms | 3.410 ms | 0.941148 → 0.025259 ms (37.3× faster) | | One full-ring write | 125.977 ms | 0.099 ms | 0.933163 → 0.000733 ms (1,272.5× faster) | Both public write APIs have full-ring and live-packet tests asserting <0.10 s CPU, below the unchanged 0.30 s fast-test guard. All four performance cases failed before the optimization and pass after it. Small reference-model tests cover capacities 1/2/7/10, empty/exact-wrap/oversized multi-wrap/subsequent writes, counters, extraction and timestamps. The retained boundaries are asserted exactly: profiling pinned pytest 8.4.1 proved its first scalar `pytest.approx` equality imports NumPy (`is_bool`), dominating the tiny ten-byte test. Removing that unnecessary approximate comparison strengthens the assertions and removes a real cold-import cost; payloads, timed regions and both performance/guard thresholds are unchanged. The profiled NumPy import accounted for 0.485 of 0.487 cumulative profile seconds in that test (diagnostic profile time, not a production CPU measurement). Evidence: `.pytest-tmp/pcm-cold-approx.pstats`; the strengthened ring file passes 24 tests with zero guard warnings (`inert-exact-ring-assertions.log`). Seven selected files through `backend/test.sh`: 336 passed, one slow deselected. Evidence: `.pytest-tmp/pcm_ring_benchmark.py`, `pcm-ring-before.json`, `pcm-ring-after.json`, and `.pytest-tmp/logs/test-sh-selected.log`. The previously unpushed all-cooling/test-isolation round and ring fix were published normally at `e67b5ebfb9cb8d995d57c202bcbff8abd7b494ec`. All local hooks passed, including the 0.30 s CPU guard; `make preflight` passed 31 checks. That intermediate head had a main merge conflict and only CodeQL ran remotely, so it is not a backend-CI receipt. Logs: `.pytest-tmp/logs/pcm-ring-push.log`, `pcm-ring-make-preflight.log`. ## Flag-off equivalence and validation Baseline: main `147f77d86a2de9d68cec63b6adeb69bd282aeeae`. - **Ten extracted function bodies match baseline AST**, normalizing only helper-module qualification, the finishing-helper name and function docstrings: receiver failover/rebuild/monitor/flush; replay reconnect/rejected-successor retry/synchronous send; configured-chain attempt; replacement selection; reconnect admission. Evidence: lead-authored `.pytest-tmp/flag_equivalence_audit.py` and `flag-equivalence-audit.json`. - **285 original main tests passed with false, and the same 285 passed unset**, through `test.sh` and the unchanged guard. The ten test files were byte-identical to pinned main: death monitor, resilient stream, session failover, managed fence, Parakeet exhaustion, Soniox rate-limit/typed rejection, Modulate socket/capacity, configured chain. No assertion edits. Preserved original sources and hashes: `.pytest-tmp/baseline-stt-recovery-sources/`, `baseline-stt-hashes.txt`, `flag-equivalence-audit.json`; logs `test-sh-baseline-{false,unset}.log`. After the ring pin correction, the unmodified original resilient suite passed again both false and unset (22 each). - **42 flag-contract tests passed**: fail-closed parsing; runtime/receiver/ring/VAD/real paid successor pins in both env-flip directions; task/context propagation and cancellation reset; plain 2,000-item queues and unchanged EOS off; legacy vs enabled 429 circuits; 135/150 s caps and legacy reconnect budgets; managed fence retained; departure settlement; no new counter or histogram observations off while baseline replay metrics still emit. File-local fixtures isolate circuits, backoff and health, with no network/Redis access. Initial log: `test-sh-flag-isolated-final.log`; final pin-entry regressions: `inert-ci-pin-fix.log`. - **Flag-on matrix: 97 fast passed; provider-pair suite: 27 passed.** File-local ON fixtures preserve the matrix and branch qualification assertions; there is no global fixture silently forcing production default on. Flag-contract plus matrix/provider-pair narrow run: 162 passed, one slow deselected (`test-sh-narrow-final.log`). Cost-router, speaker/capture-birth and evidence-settlement follow-up files also passed after explicitly enabling their qualification fixtures. After integrating #20433, the window suite (161), matrix (97) and provider pairs (27) passed together with the unchanged guard (`inert-main-queue-composition.log`). Eleven byte-identical newest-main queue-contract cases also passed OFF, including the actual marked-503 receiver failover (`inert-main-queue-off.log`). - **196 deployment/default checks passed** (Helm/env/render/validator/key bindings); runtime compose `--check` and feature-flag registry checks passed. Typecheck: **0 errors** (`typecheck-rework.log`). No timing-guard/duration-allowlist, CI threshold or security-policy relaxations. The proper flag-on slow lane also passed: **1 passed, 97 deselected** (`.pytest-tmp/logs/inert-slow.log`). Final local preflight passed **41 checks**, and PR-body CI-lane preflight passed **40 checks**, after registering the new flag's non-secret/config and listen-only ownership. Evidence: `inert-make-preflight.log`, `inert-pr-preflight.log`; those metadata additions are committed before publication. After the final main merge, compose/registry checks and **24 upstream canary-tooling tests** passed with the default timing guard (`inert-post-merge.log`); the worktree is clean with no app/workflow diff against main. The first inert push was correctly blocked by fixtures that bypassed receiver construction and by two qualification files missing explicit ON mode. A test-only follow-up pins those doubles coherently and enables only the affected test modules; all assertions remain unchanged. The three failing files now pass **192 tests**, and the two affected original-main baseline files pass again false and unset (**42 each**) without silently enabling their imported shared fixture. Logs: `inert-fixture-followup.log`, `inert-baseline-helper-{false,unset}.log`. No production follow-up or timing-budget relaxation was needed. A subsequent full normal-hook retry passed every assertion but blocked on one existing Parakeet case at 0.35 s CPU; the required single-file `test.sh` rerun passed all 151 tests, with that case at 0.24 s under the unchanged 0.30 s guard (`inert-timing-single-file.log`). Normal push and complete remote CI remain pending; the receipt below will be updated on the exact published head. ## Serving behaviour changes — complete gate map Paths below are the final serving surface. OFF preserves pinned-main behavior; ON enables the described recovery changes. Declarative limits/metric registration may exist in OFF images but have no OFF serving consumers/emissions. | File:line | Gate / serving change | | --- | --- | | `backend/utils/audio.py:41` | Ungated, semantics-preserving two-copy PCM hot-path optimization described above. | | `backend/config/live_stt_recovery.py:18,21,28` | Pure fail-closed env/context lookup and explicit owner pin; no per-user cohort or Redis switch. | | `backend/routers/listen/runtime.py:134,410,920` | Session-start snapshot, whole-run context lifetime and ON-only terminal-after-text emission; existing any-text SLI unchanged. | | `backend/routers/listen/receiver.py:243,867,1253,1294,1420,1578,1666,2075` | ON-only controller, unified dial/replay/adoption/ingestion/birth path; OFF dispatches original locked/synchronous recovery, capture and monitor behavior. | | `backend/routers/listen/legacy_recovery.py:27,46,147,183` | OFF-only main failover/rebuild/monitor/flush implementations, including old failure latch, attempt limits and synchronous prefix replay. | | `backend/utils/stt/recovery_state.py:59,115,279` | ON-only controller instantiated by receiver: lifecycle, episode/time/unique-target accounting and candidate-bound recovery proof. | | `backend/utils/stt/resilient_stream.py:73,162,188,323,357,478` | Pinned 135 s OFF / 150 s ON headroom; restored 3-total/2-per-minute/30 s cumulative OFF reconnect budget. Managed owner fence stays in both; unmanaged raw finishing remains authoritative OFF. New bounded capture/paced replay is ON-only. | | `backend/utils/stt/legacy_replay.py:24,120,149` | OFF-only main Soniox reconnect, rejected-successor retry and synchronous replay, with baseline metrics. | | `backend/utils/stt/live_recovery.py:25,32,69` | OFF retains 3 managed / 2 legacy rebuild limits and main rescue condition; ON uses shared controller and the sole qualified Soniox repeat. | | `backend/utils/stt/live_chain.py:139,305,332,520,861` | OFF exact main attempt body, cleanup and 429 breaker semantics; ON target reservations, bounded dials, refusal backoff and one earliest-expiry all-cooling escape. | | `backend/utils/stt/connect_backoff.py:22,108,178` | ON-only serving use via chain gate; per-target 3-in-10 s refusal history, 2/4/8/10 s backoff, exclusive probe, bounded escape and healthy reset. OFF never acquires a lease or mutates this state. | | `backend/utils/stt/streaming.py:419,466,484,521,1403,1531,1593` | OFF legacy-primary 429 failure handling and plain Modulate writer/EOS; ON admission release and recovery-only paced/deadline-aware writer. Parakeet replay declarations at `1856,2095` are consumed only ON. | | `backend/utils/stt/soniox.py:196,263,268,357` | Pinned plain queue/no pacing/original send-finalize-EOS OFF; ON bounded queued/in-flight accounting, writer cadence and capture-age expiry. | | `backend/utils/stt/send_queue.py:16` | `AudioSendQueue` allocated only ON by paid adapters; OFF uses exact `asyncio.Queue(maxsize=2000)`. | | `backend/utils/stt/replay_delivery.py:145,211,354,492` | ON-only serving activation of writer pacing, newest-unanswered prefix, bounded birth ledger and ordered live tail; OFF never enters pump/skip/expiry paths. | | `backend/utils/stt/live_session.py:57,384,463,847,858,947` | Managed leg inherits session pin; ON-only cancellation disposal, waits, typed endpoint limits, controller departure and departing settlement; OFF main lifecycle retained. | | `backend/utils/stt/vad_gate.py:736,762` | VAD wrapper pins underlying mode and forwards new capacity waits only ON. | | `backend/utils/stt/live_failure.py:160,239,577` | Pending settlement inherits source/session mode; departure degradation and extra post-await lifecycle checks only ON; OFF existing exhaustion/termination semantics. | | `backend/utils/stt/live_outcome.py:53` | Mode metadata only; existing single serving-owned emission seam remains authoritative. | | `backend/utils/stt/live_metrics.py:5,24,29,113` | New bounded families can register/preinitialize at zero in either mode; all recovery observation sites and terminal-after-text emission are ON-only. Baseline metrics unchanged OFF. | | `backend/config/live_stt_replay.py:11`; `backend/config/live_stt_registry.py:26`; `backend/utils/stt/safe_socket.py:60` | Typed endpoint/adapter replay declarations are data only OFF and consumed by ON pumps; order/ramp defaults unchanged. | | `backend/deploy/runtime_env/_base.yaml:100`; `backend/deploy/runtime_env/dev.overlay.yaml:50`; `backend/deploy/runtime_env/prod.overlay.yaml:43`; `backend/deploy/runtime_env.yaml:139,2151` | Default-off runtime declaration and composed dev/prod manifests. | | `backend/charts/backend-listen/dev_omi_backend_listen_values.yaml:378`; `backend/charts/backend-listen/prod_omi_backend_listen_values.yaml:405`; `config/feature-flags.yaml:132` | Explicit false chart defaults and reviewed flag registry. | | `config/deployment-setting-classification.json:229`; `backend/scripts/verify_pusher_cohost_env_diff.py:99,203` | Declare the new boolean as non-secret configuration and as listen-only STT ownership in both environments; no secret mappings, shared-finalizer requirements or enforcement thresholds changed. | Line-Count-Exception: backend/routers/listen/receiver.py | 1842 -> 2237 | Default-off main recovery dispatch plus explicit ON session-owner replay/adoption/ingestion integration. Line-Count-Exception: backend/utils/stt/streaming.py | 2205 -> 2322 | Separate pinned OFF writer and ON recovery cadence/deadline branches plus shared target-aware bounded dials. ## Enabled recovery design and known trade-offs Only flag-on sessions use `serving → provider_died → recovering → replaying → recovered`, or terminal `exhausted` / `client_leaving`. Departure is owner/application lifecycle, never managed raw cleanup. One 60 s episode covers actual dials, replay and proof; real dials are capped at min(5 s, episode remaining). Up to 20 unique identities/episodes and one qualified Soniox repeat bound work. Skips consume no dial. Prefix adoption plus current-candidate text or an observed 5 s healthy-connected dwell releases the episode; silence is normal. Connected proof does not synthesize transcript success or settle a hop recovered. Replay defaults: 1× audio time, ≤16 KiB frames, two queued+in-flight slots, ≤2 s capacity wait. [Soniox real-time cadence](https://soniox.com/docs/stt/rt/error-handling#real-time-cadence) supports near-real-time delivery; [Modulate streaming reference](https://docs.modulate.ai/api-reference/stt/streaming.md) supplies no qualified accelerated ceiling, so 1× is conservative. Window/RNNT/Deepgram use conservative pump limits and their existing admission contracts, not a claim of qualified acceleration. Optional endpoint declarations may only tighten limits. **Loss trade-off:** at default 1× and a 20 s prefix wall, a 135 s unanswered backlog keeps the newest 20 s and skips 115 s from successor transcription, explicitly metered and retired once. Capture gaps do not count as audio. Slower endpoint limits, repeated failures and residence expiry can cut additional audio. Transport writes are not transcript acknowledgments. Live ingestion stays ordered in a ≤26 s tail; first capture acceptance is retained in a bounded 8,192-entry birth ledger. Tail writes have a 28 s capture-age bound, or are explicitly cut/rejected. The qualified one-handoff 20 ms consumer case measured ≤25.532 s capture-to-wire at 16 kHz including setup (≤26.044 s at 8 kHz), excluding transcript latency. Continuous 1× speech cannot catch up until admitted audio pauses. Conservative recovery-owned PCM allowance: 8,241,152 B/session; 125.75 MiB for 16 sessions at 16 kHz, 375.75 MiB at 48 kHz, excluding Python/VAD/POST/ordinary queues/RSS. 429s remain session-local refusal evidence ON, not account quarantine or a shared long serving bench. Three refusals in 10 s open 2/4/8/10 s process-local backoff. All-cooling cannot alone deny a fresh session: one earliest-expiry otherwise-admissible dial is allowed; an early lease does not extend/escalate cooldown. Account, withdrawal, failed-target, capability, window admission and recovery budgets remain enforced. Historical paid concurrency was supplied by the coordinator; fake surge tests do not establish current paid headroom. No global paid limiter was added. Historical aggregate exhausted events cannot be individually attributed. Reproductions cover stalled send/finalize queues outside replay and already-claimed failures settling after later departure. OFF keeps main semantics; ON departure settles degraded, with exhausted reserved for active bounded recovery exhaustion. PTT stays unpaced and retains its existing large-frame follow-up: independently supervised disconnect, bounded residual cursor, paced pump and EOS barrier are still needed. ## Canary observation and rollout — coordinator-owned, not performed New metrics are not fleet-wide SLIs while defaults are off. Set `${canary_pods:regex}` / `${control_pods:regex}` to escaped exact enabled-canary / flag-off control pod names and refresh after replacement. Current scrape does not carry `track`; do not filter on it. Missing telemetry/exposure is HOLD, not zero-loss proof. Examples, not executed production measurements: ```promql sum by (source,successor) (increase(omi_stt_recovery_attempts_total{job="backend-listen-metrics",namespace="prod-omi-backend",pod=~"${canary_pods:regex}"}[15m])) histogram_quantile(0.95,sum by (le,source,successor) (rate(omi_stt_replay_wall_seconds_bucket{job="backend-listen-metrics",namespace="prod-omi-backend",pod=~"${canary_pods:regex}"}[5m]))) sum by (source,successor) (increase(omi_stt_replay_skipped_seconds_total{job="backend-listen-metrics",namespace="prod-omi-backend",pod=~"${canary_pods:regex}"}[15m])) sum by (provider) (increase(omi_live_session_terminal_after_text_total{job="backend-listen-metrics",namespace="prod-omi-backend",pod=~"${canary_pods:regex}"}[15m])) sum(increase(omi_stt_recovery_attempts_total{job="backend-listen-metrics",namespace="prod-omi-backend",pod=~"${control_pods:regex}"}[15m])) > 0 ``` Proposed canary alerts (`for: 1m`), scoped rather than mixing inert controls: ```promql sum(increase(omi_fallback_total{job="backend-listen-metrics",namespace="prod-omi-backend",pod=~"${canary_pods:regex}",component="stt_live_session",from_mode=~"soniox|modulate",reason="capacity_full"}[5m])) > 0 sum(increase(omi_live_stt_terminal_failures_total{job="backend-listen-metrics",namespace="prod-omi-backend",phase=~"connection|send"}[25m])) > 3 ``` The latter is the supplied historical fleet 0–3/25 min baseline, not a measured per-canary threshold. Compare same-load controls and retain independent any-text/continuity checks. Two fixed canary pods plus isolated dev soak are the agreed mechanism (#20418), not an action performed here. First 15 min: ≥10 positive replays including both paid families, all canary pods scraped, zero replay-induced terminal/capacity deaths, replay p95 ≤20 s with ≥10 observations, no unexplained fresh skips, no sustained lifecycle residual, ≥50 sockets with ≥95% any-text and ≤2-point decline vs controls. First 60 min: ≥30 positive replays/≥5 per paid family/≥100 sockets, same no-loss/lifecycle gates, first-text p95 <30 s, window POST p95 <2 s, combined pressure/overflow ≤1% with ≥20 admissions. Missing exposure is HOLD; replay-induced terminal loss is ABORT. Approval, paid/public-speech soak, vendor capacity/quality/billing/RSS/backfill and attended rollback remain coordinator gates. Controller/ring/tail state is process/WebSocket memory only. Existing sockets retain their pinned mode through drain; reverting flag false affects new sessions, not in-flight recovery. An older-image rollback is safe for persisted data but restores its known synchronous-overflow defect. Abrupt process death can lose in-memory tails; client offline capture/sync owns cross-process recovery. ## Product invariants affected - **INV-MEM-4 preserved** (`product/invariants/memory-promotion-authority.md`): runtime manifest gains only a false listen STT flag; memory admission, schedules, authority and fences are unchanged. Runtime compose/render/validator checks cover this additive deployment declaration. ## Final publication / CI receipt The inert implementation was published normally at `9ec29a62cba2bffdfe4f2fe5ed81d429f11e54f5`: all hooks passed (41 preflight checks, typecheck 0 errors, selected backend files under the unchanged CPU guard). Receipt: `.pytest-tmp/logs/inert-push-final.log`. Newer main introduced a documentation conflict, preventing full PR CI; main is now integrated locally at `abcadb4bc5b6418d9fe969baa5262e7eda054540`, preserving its queue cleanup and the bounded-replay wording. A merged-head push passed preflight/typecheck/source closure but was blocked when the canonical `.venv` disappeared before unit tests. The documented `scripts/sync-python-deps.sh` route restored Python 3.11.15 from `pylock.macos.toml`, with no tracked dependency or policy edits; environment preflight and 38 flag tests passed (`env-repair-sync.log`, `inert-env-repair.log`). The remover is unknown; no other lane/process was altered. Final local head is `389885f9e7194db42ceae060b52947e0cde5ad77`, adding only the exact ring-assertion/cold-import follow-up to that merge. **Published normally at `389885f9e7194db42ceae060b52947e0cde5ad77`** with all hooks enabled: 41 preflight checks, typecheck 0 errors, selected backend suites passing the unchanged 0.30 s guard, runtime/env/source closure and API contracts. Receipt: `.pytest-tmp/logs/inert-cold-import-fixed-push.log`. GitHub reports this head MERGEABLE and full source CI is running, including all four backend shards. CI on that head passed CodeQL, slow guardrails, hermetic E2E/listen-pusher gauntlet, metadata/hygiene, env and source closure, but its broad unit shards caught five unchanged provider/readiness files calling constructor-bypassing owners without the new pin field, plus a static lifecycle test inspecting the wrapper rather than the serving body. Follow-up `fab2f0754f8ea52d6f828ea022ba80c9019085b8` pins only missing/non-boolean entry fields once (inheriting an already-pinned receiver), leaves fully constructed sessions unchanged, and strengthens the lifecycle guard across `run → _run → finally teardown`. All original provider assertions remain unmodified; six failing suites plus 42 flag cases passed locally (**159 passed, 14 slow deselected**), typecheck 0 errors (`inert-ci-pin-fix.log`, `typecheck-pin-fix.log`). **That follow-up is now published normally at final head `fab2f0754f8ea52d6f828ea022ba80c9019085b8`**. All hooks passed again (41 preflight checks, typecheck 0 errors, selected tests under unchanged 0.30 s CPU guard); receipt `inert-ci-pin-fix-push.log`. GitHub reports it MERGEABLE and exact-head source CI is running; no green unit-CI claim is made yet. PR remains open/draft; do not merge or deploy. #### Test plan - [x] PCM semantic regressions and before/after benchmark; publish prior unpushed fixes normally. - [x] Flag-off original-main false/unset suites; source/body equivalence audit; mode-pinning/metrics/circuit contracts. - [x] Flag-on fast recovery matrix, provider pairs and affected qualification suites; unchanged CPU guard. - [x] Default-off chart/base/overlays/compose and flag registry; typecheck 0 errors. - [ ] Final slow matrix, committed-head preflight, normal inert-head push and complete source CI. - [ ] Independent coordinator approval, paid/public-speech soak, deployment and attended rollout (not performed). Generated with [Devin](https://devin.ai)
A live failover replay could synchronously overflow either paid adapter's 2,000-item queue; coalescing alone still sent 135 seconds of audio in a burst. This revision uses adapter-declared 1x audio-time pacing, a 20-second newest-unanswered prefix within a 25-second setup/replay allowance, a bounded ordered live tail, and serving-owner cleanup. A 135-second backlog explicitly skips 115 seconds rather than silently bursting it. No routing configuration, static order, production shadow/on-percent defaults, or PTT provider policy changes.
Root cause and evidence
A 135s capture ring at 30ms per chunk has 4,500 items. Synchronous admissions fail at item 2,001 for BOTH real Soniox and Modulate wrappers. Coalescing to 16KiB produces only 264 items, so queue capacity alone admits the entire ring in milliseconds. Adapter drain scheduling differs, but neither item capacity nor Modulate-first order is a pacing guarantee. Managed Soniox transport disposal also sets raw
_finishing; owner teardown, rather than that raw disposal flag, must fence recovery.The supplied aggregates show 6–8 exhausted hops/20min alongside a recovered 0–3 client-terminal baseline. They cannot establish the replay duration, stalled-transport timing, or client state for individual events. Real-adapter tests demonstrate queue-full on ordinary send and Soniox finalize outside replay. #20350 excludes death first observed after departure; an eligible earlier death still gets one health settlement, while unproven recovery settled during owner departure is degraded. Active recovery exhaustion retains exhausted and stt_failed/1011. Do not interpret every to=unavailable event as client termination.
Pacing contract and sources
Setup is bounded at 5s including its final liveness check; prefix admission is bounded at 20s. The newest 20s of unanswered PCM fits at 1x; older PCM is counted in omi_stt_replay_skipped_seconds_total. Delivered prefixes are excluded, offsets remain capture-positioned, and retired callbacks cannot duplicate text. Retained replay/live audio is ordered and not dropped. This does not claim transcript preservation for the explicitly skipped span.
Live capture continues without awaiting the failover lock. A supervisor-owned tail accepts at most 26s PCM (832,000 bytes at 16kHz; shared bytes also enter the capture ring), and stays at 1x until its lag drains during silence. At 16kHz with the qualified 20ms/packet consumer, worst live audio delivery delay is 25.532s including the full setup allowance (20.532s after setup); at 8kHz it is 26.044s due to 16KiB packet granularity. These are audio delivery bounds, not vendor transcript latency guarantees. A stalled transport is rejected after 2s waiting for the two-packet paced queue watermark, or the prefix deadline; the existing finite attempt budget then controls recovery. Repeated failure can cause additional explicit budget cuts, each recorded.
Serving behaviour changes
PTT follow-up (Luna P2; intentionally untouched)
backend/routers/chat.py:send_stt_audio_or_close and its 30ms accepted-frame flush loop still admit a valid 5MiB frame as about 5,460 synchronous sends. This can overflow Modulate's 2,000-item queue at ~60s before its sender runs. Fix in a dedicated PTT change: retain ownership of the complete accepted frame until paced transport admissions succeed; use ReplayPacer plus awaited adapter capacity with the current 30ms packet policy; continue websocket reads through a separately supervised bounded frame-delivery task so a 164s accepted frame does not hide client disconnect; retain the unsent frame suffix through existing failover; preserve accepted-byte accounting, one reservation/refund/settlement, EOS ordering and cancellation/socket cleanup. Keep the existing PTT provider policy unchanged. Regression: 5MiB synthetic frame, real SafeModulateSocket/fake websocket, 20ms consumer, max two paced queue items, exact retained-frame order/coverage, mid-frame provider death and client disconnect. Do not fix PTT by simply awaiting 164s inside websocket.receive's loop.
Validation
Fake-clock real-provider-pair suite covers full 135s capture, actual 2,000-item send loops, 20ms consumers with real-time live audio, rate/depth/delay/order/coverage, explicit skipped amount, successor death → next provider, emitted-prefix fencing, setup/replay cancellation and exactly-once settlement. Historical full-prefix stress tests override only the cut size to qualify the pump; production-budget tests pin the shipped newest-20s cut. Additional receiver/recovery/#20348/#20350 tests are run with the requested TMPDIR/no-cacheprovider command and unchanged 0.30s CPU guard. Final focused run after the fresh main merge and environment restoration: 285 passed across eight recovery/provider/accounting/gauge files in 65.68s wall time; all pass the unchanged 0.30s CPU guard. All 25 provider-pair cases use <=0.179s CPU; the slow-consumer cases use 0.081770s/0.081541s, closure/retry cases 0.109121s/0.120025s, disconnect/cancel cases <=0.014s. The gauge-drain fixture initializes replay lifecycle fields like the receiver constructor while retaining the original gauge-balance assertion. The full per-test CPU receipt is retained locally. Full backend pyright: 0 errors (existing warnings).
make preflight: 31 checks passed; PR metadata is revalidated against the final committed head before push.Final published head
858b1269fe856c6c5a849de09d6dd17f302317f1(merged maina0a5a45245194a43f1bbc0ce999c1892c7948045) reached terminal CI: 28 success, 22 skipped, 3 failed checks, zero pending. source closure, public API contract, CodeQL, hermetic E2E, listen gauntlet, guardrails and shards 3/4 passed. Shards 1/2 and the aggregate failed only on two inherited tests: the suppliedTestRouterWiring::test_sensitive_read_page_capsbaseline, andtest_selfheal_recovery.py::test_recovery_minimum_structure_raises_before_persist_or_fanout. The latter's exact event comparison omitsstructure_reason: no_enriched_structure, added on main in #20359 (0052abbe3f, process_conversation.py:3110); the relevant test and production files are byte-identical to main and the failure reproduces locally. Upstream follow-up: update that expected event shape to include the bounded structure_reason field while retaining the pre-persist/fanout assertions. It is excluded from this replay PR's diff. The corrected Soniox gauge-drain test passes in CI. Clean repository CI remains blocked by those upstream failures. The first shard-3 attempt passed all tests but exceeded the 600s whole-step wall budget (744s); one targeted rerun passed the unchanged authoritative step in 577s, without guard/workflow changes or skipped tests. Final unit run. Final publication incorporates main's people-stats fix without changing any of the 17 replay PR files. Worktree is clean; remote branch and PR head match the published SHA.No production credentials, kubectl/gcloud, user audio/transcripts, PR merge, or deployment were used. Main was merged without rebase or force-push; config/order files are absent from the PR diff.
Staged rollout suggestion
Keep router shadow/on-percent 0. After terminal CI and review, deploy the image to a small attended listen canary (static chain remains Parakeet→Modulate→Soniox); synthetic changed-path canaries must exercise both paid successors before expansion. During the first 15min compare control/canary replay wall p95/max, queue high-water (expected <=2 paced PCM items, with small finalize/EOS control overhead), replay audio/skipped seconds by family pair, successor-closed counter, capacity_full/exhausted vs client-terminal/send/1011 counters, transcript continuity, memory and opened–settled–open lifecycle gap. Abort for any replay-induced death/1011, duplicate/out-of-order retained transcript, growing tail/delivery lag, a persistent lifecycle gap, or unexplained skip volume. Budget cuts are expected for >20s backlog; quantify their cost before widening. Expand image exposure 5→25→50→100 only with actual replay-path traffic and an attended peak interval; image rollback restores prior implementation. Router-on activation is a separate decision.
Product invariants affected
INV-MEM-4: retain capture mapping and exclude emitted prefixes through provider recovery; explicit budget cuts are metered separately from safe emitted-text trims.
Failure-Class: FC-recoverable-provider-failure-terminal
Line-Count-Exception: backend/routers/listen/receiver.py | 1842 -> 1988 | Bound paced recovery at the serving-owner seam and let live reads continue through supervised delivery; unrelated receiver extraction would widen this incident fix.
Line-Count-Exception: backend/utils/stt/streaming.py | 2188 -> 2198 | Replace the queue with bounded capacity signalling and declare the existing adapter's conservative replay ceiling.