Skip to content

fix(stt): bound live recovery and replay under one session owner - #20391

Merged
Git-on-my-level merged 49 commits into
mainfrom
fix/stt-failover-recovery
Oct 3, 2026
Merged

Git-on-my-level merged 49 commits into
mainfrom
fix/stt-failover-recovery

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 2, 2026 •

Copy link
Copy Markdown
Member

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 fix(parakeet): release abandoned live queue capacity #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 supports near-real-time delivery; Modulate streaming reference 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:

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:

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

  • PCM semantic regressions and before/after benchmark; publish prior unpushed fixes normally.
  • Flag-off original-main false/unset suites; source/body equivalence audit; mode-pinning/metrics/circuit contracts.
  • Flag-on fast recovery matrix, provider pairs and affected qualification suites; unchanged CPU guard.
  • 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

Git-on-my-level and others added 22 commits October 2, 2026 23:29
Keep provider disposal separate from client departure and carry unresolved
capture through one target/time budget with paced paid-adapter writes.
Retain the expanded recovery matrix as a draft qualification surface.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Integrate the replay branch without rewriting its reviewed history.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Keep upstream client and voiceprint work intact and initialize the new
recovery owner in the inherited drain fixture.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Retain upstream work without changing the reviewed STT implementation.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…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.
Git-on-my-level added a commit that referenced this pull request Oct 2, 2026
…20393)

## What

`socket_is_finishing()` (`backend/utils/stt/resilient_stream.py`) no
longer descends into a managed leg's raw transport. For a managed
`LiveLegSocket` (it has `leg_outcome`), "is the session tearing down" is
decided only by `leg_outcome.owner_closing`. Unmanaged/legacy sockets
keep their `_finishing` latch. One regression test file.

## Why (prod)

Since #20343, `LiveLegSocket.send` calls `raw.finish()` as transport
cleanup after a rejected send. When a failover replays the capture ring
into Soniox and Soniox's 2,000-item send queue overflows
(`capacity_full`), that cleanup sets the raw Soniox `_finishing` latch.
`ListenReceiver._failover_stt_socket` and the Soniox reconnect path call
`socket_is_finishing()`, read the raw latch as client teardown, and
return without trying a successor — the session ends (`stt_live_session
… outcome=exhausted`, client closed). Independent review finding 2
reproduced it (owner_closing=False, raw finishing=True, backup
attempts=0). Listen logs at the evening peak show 6–11 sessions per 25
minutes lost this way, mostly `modulate→soniox` chains; on image
`0ba6edb` (before #20343) the same chains recovered.

This is the minimal hotfix for that regression. The queue overflow
itself (replay is a burst) and the long-term recovery design are in
#20391; this does not conflict with it in intent and #20391 will
supersede this code.

## Serving behaviour changes

| File:line | Old | New |
| --- | --- | --- |
| `backend/utils/stt/resilient_stream.py` `socket_is_finishing` | Any
`_finishing` on the managed wrapper or its raw transport blocked
recovery | Managed legs: only `leg_outcome.owner_closing` blocks
recovery; unmanaged sockets unchanged |

Effect: after a provider death caused by our own transport cleanup,
recovery tries the next capable provider again, as on `0ba6edb`.
Client-initiated teardown still sets `owner_closing` before flushing
(#20343/#20350), so it still blocks recovery.

## Tests

`tests/unit/test_recovery_fence_managed_leg.py` (4 cases) plus the
neighbouring suites `test_live_stt_resilient_stream.py`,
`test_stt_session_failover.py`, `test_live_evidence_settlement.py`,
`test_parakeet_failover_exhausted.py`: 110 passed locally.

## Product invariants affected

None.

Failure-Class: none

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/20393?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
Git-on-my-level and others added 6 commits October 3, 2026 08:03
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…eive loop

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Git-on-my-level and others added 2 commits October 3, 2026 14:22
Give an all-cooling chain one bounded earliest-expiry dial while preserving
probe ownership and recovery exclusions. Scope process state and health
aliases per test so Soniox surge assertions observe only its own refusal.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Git-on-my-level added a commit that referenced this pull request Oct 3, 2026
## Summary

Fix independent-review finding 12 at Omi-owned logging sites. Soniox and
Modulate error frames, Deepgram callbacks, and Parakeet/auxiliary
exceptions previously emitted provider-supplied text that can echo
request context. Use a shared strict diagnostic primitive rather than
token masking: arbitrary text (including purely alphabetic user text),
domains, signed URLs, paths, and unknown provider code strings never
enter these log messages. Emit only validated numeric status and
constant canonical diagnostics, capped at 160 characters.

Failure-Class: none

Line-Count-Exception: backend/utils/stt/streaming.py | 2188 -> 2205 |
Minimal logging-only replacements need multiline bounded code/reason
diagnostics; sanitisation is extracted into the shared log_sanitizer
primitive, while moving adapter/transport code would conflict with
#20391's ownership.

The registry's nearest logging definition,
`FC-secret-printed-to-plugin-logs`, is specifically the plugin/OAuth
stdout contract and guard. No existing definition exactly owns backend
STT provider diagnostics; no `.github/` registry changes are made under
this task's scope. The reusable primitive and behavioral adapter
regressions are the prevention surface, not a new source-string guard.

## Serving behaviour changes

| File:line | Change |
| --- | --- |
| `backend/utils/log_sanitizer.py:189` | New `sanitize_provider_error`:
HTTP 100–599 or WS 1000–1015 status, otherwise `unknown`; bounded
canonical phrase or `[redacted]`, and an optional closed-set
`exception_type` for exception objects; max 160 output characters and
2,000 input characters scanned. Validated scalar fields work on mappings
and SDK objects, skip unusable codes/blank diagnostics, and never
stringify arbitrary objects. Matching normalizes
case/underscores/whitespace but emits only constants. Existing
sanitizers unchanged. |
| `backend/utils/stt/soniox.py:144`, `:373`, `:383` | Persistent 429
escalation and both receive-loop severity branches use the safe
primitive; retain bounded typed reason and numeric status. No raw
error_type/message in emitted logs. |
| `backend/utils/stt/streaming.py:1057–1224` | Omi Deepgram
error/close/retry callbacks and unhandled-frame logging suppress raw
payloads. The metadata callback remains registered but no longer logs
its payload or a constant redacted INFO line. Existing classification
and raw close latches remain untouched. |
| `backend/utils/stt/streaming.py:1557–1574` | Modulate receive-loop
error/warning logs keep typed reason and safe diagnostics, not raw
provider frames. |
| `backend/utils/stt/streaming.py:1823–2155` | Parakeet pump/drain,
embedding, HTTP transcription, startup-death and WS send/connect/receive
error messages use safe diagnostics. Pump/drain retain ERROR severity
but omit raw exception tracebacks. |
| `backend/utils/stt/safe_socket.py:103`, `:140`, `:169` | Deepgram
keepalive/send/finalize exception logs no longer echo exception strings.
No transport behavior changes. |
| `backend/utils/stt/pre_recorded.py:984` | Batch diarization warning
uses the safe diagnostic; existing main prerecorded provider logs
already emit exception type/attempt only. |
| `backend/utils/stt/speaker_embedding.py:187`, `:215` | Embedding
exception logs drop raw path/error text while retaining ERROR severity.
|
| `backend/utils/stt/vad.py:227`, `:256`, `:386` | Hosted-VAD fallback
and decode error logs drop raw paths/error text; fallback behavior
unchanged. |

No provider order, allocation, charts, runtime env, metric schema, or
`.github/` changes. Production remains `STT_ROUTING_MODE=shadow`,
`STT_ROUTING_ON_PERCENT=0`. No send, recovery, replay, retry-policy, or
classification changes; `soniox.py` / `streaming.py` changes are imports
and logging expressions only (one exception binding solely to provide a
safe diagnostic).

## Test plan

- [x] Initial regression proof against clean `origin/main`: **13 failing
adapter-log tests**, plus sanitizer import errors before the primitive
existed.
- [x] Before test consolidation: `cd backend && mkdir -p ../.pytest-tmp
&& TMPDIR=$PWD/../.pytest-tmp .venv/bin/python -m pytest -q -p
no:cacheprovider tests/unit/test_stt_provider_error_logs.py
tests/unit/test_log_sanitizer.py
tests/unit/test_soniox_typed_rejections.py
tests/unit/test_modulate_serve_error_deaths.py
tests/unit/test_soniox_rate_limit.py
tests/unit/test_streaming_deepgram_backoff.py --durations=8`: **256
passed**.
- [x] Same six files through the selected `test.sh` runner: **245
passed**. Its `not integration and not slow` filter excludes 11 existing
marked cases; direct pytest above included them.
- [x] Final test-only consolidation moves all 16 adapter regressions
unchanged into existing `tests/unit/test_log_sanitizer.py`, removing the
task-created new file. At consolidation that suite had **95 tests**, all
passing through prescribed pytest and isolated `test.sh`, with no
CPU-guard findings. All assertions are preserved; no skips or threshold
changes. The review follow-up adds diagnostic-field/category
regressions: a helper + Deepgram checkpoint passed **203 tests** (192
through the normal marker-filtered runner), and final
`tests/unit/test_log_sanitizer.py` passes **115 tests** through both
prescribed pytest and isolated `test.sh`.
- [x] Real Soniox/Modulate receive loops with synthetic provider frames;
actual Omi Deepgram callbacks; unchanged severity/death types;
persistent 429 escalation; alphabetic private text, emails, paths,
signed URLs, malformed codes, control characters, oversized messages,
the original 16 canonical diagnostics and the internal
bounded-connect-window diagnostic. Object-field, blank-field, status
fall-through, safe exception category and both reconnect-flag branches
are covered; arbitrary class names map to `other`.
- [x] Parakeet HTTP/startup, batch diarization, embedding and VAD error
paths; existing window 500/invalid-JSON paths verified body-safe without
changing their source.
- [x] Final startup tests use local coroutines, not DNS/WebSocket calls;
no wall sleeps in new receive-loop tests and no live services. An early
synthetic startup test incorrectly scheduled a `.invalid` dial and was
replaced before final verification.
- [x] `test-preflight.sh`: 18 passed, 0 failed; async blocker scans: 0
findings; `scripts/typecheck.sh`: 0 errors; `make preflight`: 30 checks
passed. Final committed metadata/source gate runs before push.
- [x] New fast tests below 0.30s local CPU; no slow manifest additions.
Ignored local evidence: `.local/f12/`.

## CI record

Initial head `05b4e97086` passed all test assertions and the other
checks, but backend shard 4 exceeded the 600-second wall budget twice:
636s, then 601s on a failed-jobs rerun (`37106032979`). Main runs at
both `7a58c973` and `61f889624b` passed, so the overruns were not
excused as pre-existing. The runner slices a sorted file list by index
(`backend/scripts/run-unit-ci.sh:48–51,89–94`); the task's new test file
shifted later suites between shards. The follow-up test-only
consolidation keeps all 16 adapter regressions alongside the shared
primitive's existing tests, removes that file-list insertion, and leaves
production code and CI configuration/budgets unchanged. This structural
correction does not prove that the earlier timing variance had only one
cause. **Final head `5e059e68e547be457a15807aae26f12f63fac3c4` is
CI-green**: backend unit run `37110162396` succeeded (all four shards,
guardrails and aggregate); Hermetic Backend E2E/Merge Gate, CodeQL,
Hygiene, Formatting and source closure passed. GitHub reports
`mergeStateStatus=CLEAN` and no failing checks. Scope-skipped
image/stack/client jobs are not claimed as executed. Nothing was merged
or deployed.

## Conflict / ownership note

**Possible conflicts with PR #20391**: it edits `soniox.py` /
`streaming.py` send paths and also `safe_socket.py` and pipeline
documentation. This PR changes logging expressions/imports only;
preserve both patches if nearby lines conflict. No files in the
receiver/recovery/replay/send-queue ownership area are edited.

## Remaining gaps (explicitly deferred)

**Router-boundary rethrows can still log raw provider context.**
Confirmed during PR review: `backend/utils/stt/streaming.py:352–357`
embeds raw `death_reason` in a fallback-rejection `RuntimeError`;
`backend/routers/listen/receiver.py:1234` and
`backend/routers/chat.py:1636,1872` can emit it via traceback/direct
error logging. The brief excludes the receiver/recovery owner and
restricts streaming changes to logging expressions. Changing the
raise/classification/terminal router boundary requires coordination with
#20391; it is not silently changed here. The guide and this PR
deliberately guarantee only the adapter log statements actually
hardened, not every Omi-owned log. This confirmed gap remains
unresolved.

**This is not a claim that all Deepgram SDK output is safe.** The
installed Deepgram 4.8.1 SDK constructs private `VerboseLogger` objects
with their own `StreamHandler` and a direct root parent
(`clients/listen/v1/websocket/client.py:75–77`,
`clients/common/v1/abstract_sync_websocket.py:79–81`,
`utils/verboselogs/__init__.py:147–148`). Those bypass Omi's existing
named `deepgram` capture handler. Fixing SDK-internal stderr needs
logger-filter setup at SDK construction, beyond this task's
logging-expression-only boundary. That expansion was offered but not
approved; it is deferred, and the existing capture handler remains
unchanged. Do not treat synthetic named-logger tests as proof of SDK
stderr suppression.

## Deployment / scope

Ships in the existing backend images that import these shared adapters
(not the separate Parakeet GPU image). Deploy/merge is not performed
here. Verify with synthetic provider error fixtures on the deployed
backend image: bounded `reason`/`code`/`diagnostic`, same severity and
failure counters, no sentinel context in Omi-owned adapter logs. The
independent cancelled-GPU-work fix is local on
`fix/parakeet-cancelled-work` at
`43d72c78c03bb24e2084075fe10579080bdf5a58`: two permitted pushes failed
an unchanged window test CPU guard; clean main reproduces it at 0.34s
against 0.30s. No hook bypass or owned recovery-test change was made.

Generated with [Devin](https://devin.ai)
Git-on-my-level and others added 6 commits October 3, 2026 16:38
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Git-on-my-level added a commit that referenced this pull request Oct 3, 2026
## Summary

Fix independent-review finding 11 and Luna's queue-expiry classification
follow-up. Cancelled submission futures remained in the Parakeet batch
queue, inflated pressure, and were still dispatched to the GPU. Prune
abandoned work before admission/dispatch/pressure reads, expire queued
live work under a caller-supplied remaining budget, and release only
files owned by abandoned requests. Preserve live priority and the single
aged-backfill turn after four live batches.

Queue expiry now returns HTTP 503 with JSON `error: "queue_timeout"` and
`X-Omi-STT-Error: queue_timeout`. Listen recognizes only that exact
503/header pair as `capacity_full`, with the bounded log subtype
`queue_timeout`: the window dies and releases admission promptly, and
existing failover proceeds without a Parakeet serve-failure count or
circuit strike. Missing/unknown markers and other 5xx statuses retain
`provider_5xx`. No response-body parsing or free-text reason inference
is added.

Failure-Class: FC-shared-batch-pressure-blocks-live

## Serving behaviour changes

| File:line | Change |
| --- | --- |
| `backend/parakeet/batch_engine.py:177` | Live-only finite queue
deadline; already-expired submissions fail before enqueue. Cancelled
queued callers release capacity and owned files. |
| `backend/parakeet/batch_engine.py:256` | Expiry timer and queue
pruning remove done/expired entries before capacity checks, pressure
reads, and dispatch after the inflight semaphore. Empty pruned queues do
not advance fairness. Dispatched requests retain owned files until GPU
completion. |
| `backend/parakeet/main.py:205` | Live `/v1/transcribe` accepts
`X-Omi-STT-Timeout-Seconds`, capped at 8 seconds and defaulting to 8 for
older clients. Invalid/nonfinite/nonpositive budgets return bounded 400.
Backfill ignores the header. |
| `backend/parakeet/main.py:276` | Queue expiry alone returns 503 with
bounded JSON `error=queue_timeout` plus `X-Omi-STT-Error:
queue_timeout`; existing detail and lane-refusal metrics remain. Other
503 responses are unchanged. |
| `backend/parakeet/main.py:253` | Cancelled/failed upload writes clean
their generated temp file after the writer finishes; cancelled handlers
count `status=cancelled`, not success/RTFX. Pending gauge refreshed on
completion. |
| `backend/utils/stt/parakeet_window.py:1106` | Send the remaining
overall POST budget after local semaphore admission, floored to
milliseconds; exhausted budgets fail locally without a POST. |
| `backend/utils/stt/parakeet_window.py:1146` | Exact signalled
queue-expiry 503 is `capacity_full` / `queue_timeout`, records
`WINDOW_POSTS{outcome="queue_timeout"}`, and fails the window over
without `record_serve_failure`. Unsignalled 503/other 5xx still strike
the circuit as before. |
| `backend/utils/observability/fallback.py:163` | Allow `queue_timeout`
as a bounded capacity log subtype; fallback metric reason stays
`capacity_full`, with no new metric dimension. |

The server-local deadline starts at handler entry and includes file
read/write and queue time. The transmitted relative budget does not
compensate for network/multipart time before handler entry.
Already-dispatched inference is not preempted. No provider order,
allocation, chart, runtime environment, router default, or `.github/`
changes: production remains `STT_ROUTING_MODE=shadow`,
`STT_ROUTING_ON_PERCENT=0`. Recovery implementation files owned by
#20391 are untouched.

## Test plan

- [x] Follow-up regressions were run before implementation: **5 failed /
5 passed**, demonstrating the missing wire reason, wrong window
classification, and unbounded subtype handling.
- [x] `cd backend && TMPDIR=$PWD/../.pytest-tmp .venv/bin/python -m
pytest -q -p no:cacheprovider tests/unit/test_parakeet_batch_engine.py
tests/unit/test_parakeet_endpoints.py
tests/unit/test_parakeet_window_live.py --durations=8`: **251 passed**.
- [x] `PYTHON=.venv/bin/python bash test-preflight.sh`: 18 passed, 0
failed. Standard `test.sh` with `BACKEND_UNIT_TEST_FILE_LIST` selecting
those three files: **251 passed**. Final isolated window-file rerun
after review: **161 passed**, with the unchanged 0.30-second local CPU
guard.
- [x] ASGI endpoint expiry pins exact JSON/header, existing
503/refusal/file cleanup; socket/pump tests pin signalled capacity vs
unmarked/unknown/other-5xx provider failures, malformed body, prompt
release, one POST/no retry, zero vs one serve-failure call, and closed
vs open circuit.
- [x] Both rollout orders: frozen pre-signal listener
status-classification seam on the real window socket receives the new
JSON/header 503 and still strikes/opens the circuit; new listener
against an unmarked old-server 503 preserves `provider_5xx`.
- [x] Real receiver/window-to-Soniox failover test propagates
`capacity_full` / `queue_timeout`, settles a recovered hop, and leaves
serve-failure calls/events unchanged and the circuit closed. Bounded
subtype tests keep `queue_timeout` out of metric reason labels and
suppress unbounded content.
- [x] Backend async blocker scan: 0 findings;
`backend/scripts/typecheck.sh`: 0 errors (existing warnings).
- [x] `make preflight`: 30 selected checks passed. `origin/main` at
`147f77d86a2de9d68cec63b6adeb69bd282aeeae` was merged normally, without
conflicts.
- [x] New fast tests remain below 0.30 seconds local CPU; no threshold,
allowlist, or slow-manifest changes and no hook bypass.

Local evidence: ignored `.local/f11/` logs, including
`pytest-f11-red.log`, `test-sh-f11.log`, `test-sh-f11-final-window.log`,
`typecheck-f11.log`, and `make-preflight-f11.log`. Synthetic data/fake
GPU/providers only; no production or dev data/services accessed. The
original task reported an accidental temporary stash immediately
restored; no stash was used in this review round.

## Deployment and rollout order

**Requires BOTH deployments:** a **backend-listen image deploy** for the
remaining-budget header and queue-expiry classification, and a
**separate Parakeet image deploy via existing `gcp_parakeet.yml` /
`backend/charts/parakeet`** for cancellation/queue hygiene and the
machine-readable response. A listen-only deploy does not ship the GPU
queue fix; a Parakeet-only deploy does not fix listen classification. No
deployment is performed by this PR/task.

**Recommended order: deploy listen first, wait until all listen pods use
the new image, then deploy the Parakeet image.** This avoids enabling
queue expiry while pre-signal listeners can mistake it for provider
unavailability. Verify both image SHAs and the response header survives
the actual service path.

| Mixed-version state | Exact behavior |
| --- | --- |
| New Parakeet + old listen | Additive JSON/header remain compatible,
but old listen ignores them. The 503 is `provider_5xx`: it calls
`record_serve_failure()` once, immediately opens the process-local
Parakeet serve-error circuit, releases the window, and enters existing
failover. Repeated queue expiries can extend/escalate the provider bench
and influence provider-failure health evidence. This false-outage risk
remains until listen is upgraded; Parakeet-first is not
classification-safe. |
| Old Parakeet + new listen | No reason header is present, so the
exact-match branch does not run. An old-server 503 remains
`provider_5xx`, one serve-failure call/open circuit, and existing
failover. No heuristic interprets old free-text bodies. Old servers may
ignore the request-budget header. |
| New Parakeet + new listen | Queue-expiry 503/header is `capacity_full`
/ `queue_timeout`; prompt release/failover, no serve-failure call or
circuit strike. Capacity is censored rather than provider-failure
evidence in the existing health taxonomy. Genuine unmarked 503/other 5xx
still behave as provider failures. |

On the new Parakeet image, use synthetic live-window requests queued
behind controlled GPU work, then cancel them or give a short queue
budget. Check `/batch/metrics`: `pending_requests`,
`live_pending_requests`, and `live_oldest_pending_seconds` return to the
surviving queue only. Existing Prometheus
`parakeet_batch_pending_requests` /
`parakeet_batch_lane_pending_requests{lane="live"}` must fall rather
than retain obsolete work; expiry increments
`parakeet_batch_lane_refusals_total{lane="live",reason="queue_timeout"}`
and `parakeet_requests_total{endpoint="v1_transcribe",status="error"}`.
Cancelled requests increment the existing request counter with
`status="cancelled"`. Discarded files must not appear in GPU batch
assembly, and must not add observations to
`parakeet_batch_lane_queue_wait_seconds`,
`parakeet_queue_duration_seconds`, or `parakeet_batch_size`. Verify the
queue-expiry response is 503 with the exact header and JSON error. On
new listen, check `omi_stt_window_posts_total{outcome="queue_timeout"}`
and existing
`omi_fallback_total{component="stt_live_session",reason="capacity_full"}`
with bounded `subtype=queue_timeout` logs, without new Parakeet serve
strikes/provider-failure health evidence from that expiry. Observe lower
obsolete live queue pressure and fewer unnecessary
`omi_stt_window_admissions_total{outcome="batch_pressure"}` refusals
under comparable load, without promising a specific production
improvement. Verify owned temp files disappear, unowned files survive,
and existing backfill fairness still holds.

## Coordination / deferred work

PR #20391 owns recovery/replay and Soniox/Modulate send paths. None are
changed here. It also edits `test_parakeet_window_live.py` and
`listen_pusher_pipeline.mdx`, so preserve both changes when resolving
nearby test/documentation conflicts. Longer-term GPU preemption/backfill
execution quanta or separate capacity remain deferred; this fix removes
obsolete queued work, not running kernels. Neither PR merge nor
deployment is authorized by this task.

Generated with [Devin](https://devin.ai)
Git-on-my-level and others added 2 commits October 3, 2026 19:03
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Git-on-my-level added a commit that referenced this pull request Oct 3, 2026
Finding 3 remaining blocker (review PRRT_kwDOLkKqys6olkiO): in
STT_ROUTING_MODE=off the permission filter consults FleetHealth, but
quarantine() refused to record new benches, _drain_pending_benches()
never flushed them, refresh_once() loaded no shared state, and
cached_snapshot() ignored pod-local benches. A quota/auth rejection on
one pod therefore did not withdraw the credential anywhere while the
kill switch was off, although account exclusion is documented as a hard
exclusion in every mode.

Account-bench lifecycle is now mode-independent: quarantine() accepts
account kind in off mode, the drain flushes account deadlines, and
refresh_once() reads only fleet account state keys (scores, selection
benches, probe leases and interests stay routing-only state).
cached_snapshot() enforces known pod-local benches even with routing
off. Both account-quarantine callsites (live_chain.py and the
#20391-owned live_session.py/streaming.py legs) get the fix through the
shared FleetHealth API without touching those files.

The end-to-end off-mode NoPermittedTarget reproduction from the review
thread now passes: an account bench written by one pod denies the dial
on a fresh pod before any connect attempt.

Failure-Class: FC-cache-merge-write-race

Tests: an autouse fixture resets the module-level FleetHealth singleton
in place (sibling modules keep import-time references), four new
regressions in test_live_router_hardening.py (red pre-fix on three),
109 + 262 + 721 + 1118 passed across the affected suites; the two
combined-run failures in test_listen_ready_provider.py and
test_streaming_deepgram_backoff.py reproduce identically on the
pristine branch and are pre-existing order-dependence.
Git-on-my-level and others added 2 commits October 3, 2026 20:26
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Flag-off scrapes now match main: the replay, recovery-attempt, terminal-
after-text and connect-backoff label sets are pre-created only on pods
running STT_FAILOVER_RECOVERY_ENABLED=true (the canary).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Git-on-my-level
Git-on-my-level marked this pull request as ready for review October 3, 2026 15:26
@Git-on-my-level
Git-on-my-level merged commit 8fb7dc1 into main Oct 3, 2026
56 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/stt-failover-recovery branch October 3, 2026 15:26
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 3, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-03T15:28:54.702714Z e9da873 Draft marked ready
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Git-on-my-level added a commit that referenced this pull request Oct 4, 2026
## Summary

Harden live STT routing before a separately approved router-on rollout.
Addresses independent-review findings 3, 4, 5, 6 and 9, plus their
composition with main's default-off recovery controller (#20391).
**Non-draft for review; no merge, deployment or router-on rollout
approval.**

### Round 5 — Luna's requested changes on `0dbe1574ff`

Continued with `git merge --ff-only origin/fix/stt-router-hardening`,
preserving the separately pushed identity-rotation commit. The first
`git merge origin/main` found main already included. After main advanced
during verification, normally merged its new head `cd3326b3a5` in
`c033629891`; the PR diff remains the same 27 router-hardening paths,
with no authored workflow, client, chart, runtime-env or
recovery/send-path edits.

- **Credential rotation:** Process-local selection identity is provider
+ endpoint + stage, with credential/account identity tracked separately.
Rotating a key clears only account/quota protection and invalidates
stale callbacks, not an unchanged endpoint's connect/serve outage,
deadline, escalation or recovery requirements. Selection evidence
temporarily superseded by an account bench is restored on rotation.
Endpoint changes start fresh selection state while an unchanged
credential's account protection remains; stage changes start fresh
scoped state. Redis fleet/cost namespaces remain unchanged.
- **Custom endpoint death:** The typed plain-socket fallback opens the
endpoint-keyed local target circuit, not the family default, matching
the Redis quarantine scope. Credential account failures retain
family-wide protection.
- **Tests:** The existing credential-rotation assertion that expected a
fresh custom breaker encoded the reviewed defect; it now requires the
same open breaker. The custom-endpoint test now checks the actual local
custom breaker, family/default breaker and sibling endpoint, in addition
to Redis state. New cases cover account-only rotation, mixed
outage/account evidence, repeated rotation, stale callbacks and explicit
endpoint/stage transitions.

#### Round-5 test evidence

- Pre-fix regression reproduction: eight failures, including
key-rotation outage preservation and the custom-endpoint local-family
assertion (`.local/r5-prefix-red.log`).
- Ran all requested live-STT families plus connect-refusal/circuit
coverage through file-isolated `backend/test.sh`: **72 files**,
including slow cases. The full run found one failed-account-probe
regression; corrected it and verified the original assertion on
canonical retry (`.local/r5-retry-testsh.log`). The new hardening file
passed all 156 cases.
- Local full-run exit remains nonzero for the unchanged 0.30-second CPU
guard in `test_live_recovery_matrix`, `test_live_shadow_replay` and
`test_live_gate_replay`, including single-file retries. The gate-replay
timing failure also reproduces on unmodified `0dbe1574ff`
(`/tmp/r5-baseline-gate.log`). This is not claimed as a green local full
run; no threshold, marker or allowlist was changed.
- Canonical backend typecheck: **0 errors**; Python Black check clean;
async scan **0 findings**; backend environment preflight **18 passed, 0
failed**.
- Post-main-merge canonical `backend/test.sh` check: **465 passed across
8 files, exit 0**, including hardening, cost router, live chain,
provider resilience, Deepgram account probe and transcript/Soniox paths
(`.local/r5-postmerge-testsh.log`).
`OMI_PR_BODY_FILE=.local/pr-20422-body.md make preflight` and explicit
body validation each passed **31 checks**; the line-count ratchet passed
with `streaming.py` **2324 -> 2367**. Pinned Black check passed. Logs:
`r5-make-preflight.log`, `r5-pr-preflight-body.log`,
`r5-black-check.log`.
- Full evidence: `.local/r5-full-files.txt`, `r5-full-testsh.log`,
`r5-focused-testsh2.log`, `r5-retry-testsh.log`, `r5-pyright.log`,
`r5-async-scan.log`. Normal push and pre-push gates passed for
`c033629891087f866d5dd22dc6fdb960d5035af3`. **Exact-head GitHub CI
green, first attempt:** [Backend Unit Tests run
37162666478](https://github.com/BasedHardware/omi/actions/runs/37162666478)
passed all four shards, slow guardrails and aggregate suite; [Repo
Checks run
37162666406](https://github.com/BasedHardware/omi/actions/runs/37162666406)
passed Hygiene (including line-count metadata) and Formatting. Hermetic
backend E2E/merge gate, CodeQL, source closure and OpenAPI also passed;
unrelated client/deployment checks correctly skipped. PR remains
non-draft; no merge or deployment.

Canonical full-set command from `backend/`:

```sh
PYTHON=.venv/bin/python BACKEND_PYTEST_WORKERS=2 \
  BACKEND_PYTEST_MARK_EXPR='not integration' \
  BACKEND_UNIT_TEST_FILE_LIST=../.local/r5-full-files.txt bash test.sh
```

Round 3 reproduces and fixes the eight backend CI failures on
`a5d66e8067` (run `37140378015`). The seven recovery/replay failures
were not caused by merging recovery target IDs:
`live_cost_health.py:238` correctly refused unread language health, but
`live_chain.py:263-287` then replaced registry targets with target-less
family callbacks. This lost distinct candidates, endpoints, replay
declarations and the known Modulate demotion. The eighth failure was a
stale private breaker-map key assertion.

Round 4 addresses Luna's two REQUEST CHANGES findings on `bdf23e8899`.
Normally merged `origin/main` (`6eb534630fdb`) in `bbc941f837`,
committed the reviewed fixes in `cb7fb6efb9`, then normally merged the
subsequently fetched main `d4062b9ee8` in `62750e215e`. The second merge
changes no STT source/test bytes, and the app/workflow diff against main
remains empty. No upstream workflow or client edits were authored in
this round.

- **Redis round trips:** `_write_result` reads endpoint-selection and
family-account state together in one bounded MGET, then retains the
identity fences and atomic compare-delete cleanup. A normal text outcome
takes two Redis round trips (one batch read, one pipeline execution),
matching main; no-text takes one. Each expired state still requires its
existing cleanup EVAL, intentionally preserving renewal-race protection.
- **Breaker eviction:** At the 64-identity cap, only the oldest closed
breaker is evicted. Open and half-open breakers remain cached even after
cooldown, until a normal probe closes them. If all entries are
protected, a constant-size denial circuit refuses uncached identities,
including forced probes; cached identities and family defaults remain
usable. This is deliberately conservative and can temporarily reduce
custom-target availability under extreme identity churn, rather than
resetting an unhealthy endpoint to closed.
- **Optional assertion:** The Soniox non-refusal test now explicitly
asserts the returned fallback provider is Modulate, including auth/quota
cases.

Failure-Class: FC-cache-merge-write-race

Continued from remote head `21d6b94cde`, normally merged main's
`8fb7dc1ccf` (#20391), then continued round 3 from pushed head
`a5d66e8067`. Preserve David's failure-class guard citation in that
head. No force-push, stash, hook bypass, merge of this PR, or
deployment.

### Findings and prevention

| Finding | Change | Regression proof |
| --- | --- | --- |
| **3 — hard-exclusion closure / endpoint attribution** | One permission
closure enforces actual engine, capabilities, explicit ramp and account
protection in every mode. Transcript and connect/serving failure
evidence follows the actual endpoint, not the configured primary.
Account failures remain credential-family scoped. | Zero dials for
withdrawn/quarantined/incapable targets; custom endpoint text/no-text
and failure evidence leave default and sibling endpoint selection state
untouched. Both recovery flag states covered. |
| **4 — atomic shared quarantine** | Atomic Lua update preserves account
priority and maximum expiry across stale writers; compare/delete cannot
erase a renewed bench. A custom selection writer learning existing
account quarantine protects all siblings immediately, including with
routing off. | Two-pod priority/expiry/renewal races and stale-writer
learning. Earlier isolated production-Lua checks passed 17/17. |
| **5 — independent recovery evidence** | Per-user success/failure caps
constrain promotion evidence. Stage 5 requires 30 admitted outcomes / 10
witnesses / 300 seconds; stage 25 requires 60 / 20 / 600. Existing
healthy-stage gate and backoff unchanged. | Repeated single-user
outcomes cannot promote; exact breadth/dwell boundaries, held windows
and generation fences. |
| **6 — environment/endpoint/account identity** | Stage-scoped
cost-v8/fleet-v2 keys separate dev from prod. Non-account fleet state
follows actual endpoint; account state spans endpoints sharing
credentials. Off-mode snapshots merge account-only exclusion with
neutral scores, retaining strongest known live account deadlines despite
stale cache/Redis failure. | Environment/endpoint/credential isolation;
two-pod off-mode propagation; account-only reads; on/shadow-to-off
transitions; stale selection cannot shed the configured chain. |
| **9 — per-language freshness** | Missing language entries cannot
borrow global freshness. Bounded full-language preload and per-key
freshness expose unknown/stale views. | First Korean request sees its
remote bench; unread/stale language state and bounded comparison
metrics. Round 3 retains the unread-health exception rather than
inventing freshness. |
| **Breaker identity (round 5)** | Local selection circuits key on
provider + actual endpoint + stage, locked and capped at 64. Credential
identity is synchronized separately: rotation clears only account state
and retains endpoint outage evidence. Endpoint changes start fresh
selection; stage changes start fresh scoped state. Aliases on the same
endpoint share a breaker. | Credential rotations retain open
connect/serve benches while clearing credential-only account benches;
mixed outage/account evidence survives rotation. Endpoint/stage
isolation, alias reuse, cache bound and supplied default-object identity
remain. Distinct target IDs remain distinct recovery candidates even on
a shared breaker. |
| **Round 3 — registry-preserving fail-open** | Router-on canary
cache/router faults keep permitted registry targets in configured
provider/registry order, not anonymous family callbacks. Cache
exceptions carry conservative per-target views; known restricted states
stay demoted without becoming fresh. A withdrawn/incapable default
cannot suppress a permitted custom sibling. Non-canary static planning
stays unchanged. | Existing recovery matrix and 135-second replay
assertions pass unchanged. New cases cover both recovery flags,
cache/router faults, shared-breaker distinct IDs, known demotion, unread
freshness and withdrawn-default/custom-sibling composition. |

## Serving behaviour changes

| File:line | Serving change |
| --- | --- |
| `backend/utils/stt/live_router.py:66-120,151-190` | Shared
hard-permission filter; endpoint/stage-scoped custom selection circuit
identity with separate credential-account synchronization. Closed-only
eviction and conservative saturated-cache admission remain. |
| `backend/utils/stt/streaming.py:190-221,245-263`;
`backend/utils/stt/provider_resilience.py:458-503` | Round 5 clears
credential account state without erasing unchanged-endpoint outages;
explicit endpoint changes reset selection while preserving
unchanged-account protection. Known custom-endpoint serve deaths open
their existing target circuit rather than the family default. |
| `backend/config/live_stt_state.py:98-107` | Local selection identity
excludes credentials; Redis fleet/cost identities and all routing
defaults remain unchanged. |
| `backend/utils/stt/live_health.py:333-355` | Round 4 batches
endpoint/account state reads into one MGET; identity checks and
renewal-safe Lua cleanup remain. |
| `backend/utils/stt/live_chain.py:163-325` | Filter
static/proposed/fail-open paths; typed `NoPermittedTarget`. Round 3's
`fallback_routes` preserves canary registry target identity while
maintaining hard exclusions and existing capacity admission. |
| `backend/utils/stt/live_chain.py`;
`backend/utils/stt/live_session.py:583-603,660-669` | Attribute custom
connect rejection, serving death and transcript outcomes to actual
endpoint; keep account quarantine family-wide. Both recovery modes
preserve routing profile in static-only engine-mismatch fallback. |
| `backend/config/live_stt_registry.py:38-41` | Window ramp remains the
minimum of registry percentage and existing window allocation. |
| `backend/config/live_stt_state.py:38-119`;
`backend/utils/stt/live_health.py:94-122,177-229,569` |
Environment/endpoint/account namespaces, atomic quarantine, scoped
memory/async writes and account-only off-mode snapshots. No raw
endpoint, credential or UID labels/logs. |
| `backend/utils/stt/live_gate.py:132,277,301`;
`backend/utils/stt/live_cost_health.py` | Admitted-only recovery
evidence, breadth/dwell and truthful excluded-vote accounting. |
| `backend/utils/stt/live_cost_health.py:39-45,181-243`;
`backend/utils/stt/live_metrics.py:214` | Per-key/full-language health
freshness; cache refusal carries only conservative state for fail-open
demotion, not qualification; bounded
no-permitted-target/language-comparison metrics. |

### Test changes and why

- **Round 4:** Network-round-trip assertions count MGET, GET, pipeline
execution and cleanup EVAL separately across missing/live/expired
account and selection state. Existing renewal-race and identity-change
tests move their injection seam from GET to MGET without weakening the
assertions. Breaker tests cover oldest-open and occupied half-open
preservation, all-open denial even with force, one cached recovery
probe, subsequent closed-entry recycling, unaffected family defaults,
and real-chain Deepgram fallback under both recovery flag states.
- **Round 4 optional:**
`test_live_stt_chain.py::test_non_refusal_outcomes_do_not_count_toward_the_gate`
asserts Modulate serves every fallback; the intended one Soniox
auth/quota dial remains unchanged.
- **Round 3:** `test_soniox_rate_limit.py` used
`_target_circuits['soniox-b']`, a genuinely wrong identity after the
endpoint/credential key change. It now obtains the circuit through
`target_circuit(selected_target)`, asserts the same object remains, and
retains closed/zero-failure/no-quarantine checks while adding zero
target probes in flight. No recovery-matrix or replay-provider-pair
assertions changed.
- New hardening tests exercise production candidate planning, with
synthetic callbacks/fake Redis; no new timing exceptions, guard
bypasses, scoring changes or workflow edits.
- Earlier rounds intentionally retired one-user promotion expectations
and unread-language-as-fresh expectations. One merged off-mode
account-protection test now expects one dial, not three, after
auth/quota rejection; connect-refusal-backoff assertions remain
unchanged.

### Compatibility, rollout and scope

- Production defaults stay `STT_ROUTING_MODE=shadow`,
`STT_ROUTING_ON_PERCENT=0`; recovery stays default off. No
provider-order, allocation, chart, runtime-env or workflow changes.
`.github/failure-classes/FC-cache-merge-write-race.json` only cites the
reusable hardening regression guard.
- #20391's receiver, recovery-controller, replay and send-queue
implementation is untouched. Round 3 only changes router-on canary
fail-open candidate planning, independent of the recovery flag.
- `cost-v8`/`fleet-v2` start fresh on rollout; older namespaces are not
read, migrated, backfilled or deleted. Endpoint rotation resets
endpoint-specific state, not shared credential-account quarantine.
- Synthetic/offline verification only; no user transcript/audio or
shared dev/prod state accessed. Independent-review findings outside
3/4/5/6/9 remain outside this PR. Green CI is not rollout qualification.
- Earlier merge-hook Dart formatting was corrected with a normal commit
restoring exact upstream bytes; final app diff against main is empty.

## Product invariants affected

none

## Round 4 test plan / evidence

- [x] Pre-fix canonical-runner reproduction: 17 failed, 120 passed in
the new/migrated hardening cases (`.local/pr-20422-r4-baseline.log`).
- [x] Initial focused `backend/test.sh` run: hardening 137, live chain
104 and cost router 73 passed; local CPU thresholds unchanged
(`.local/pr-20422-r4-focused.log`).
- [x] Full requested `test_live_*`, `test_soniox_*`, `test_modulate_*`,
`test_parakeet_*`, `test_deepgram_*`, `test_stt_*` families plus
connect-refusal backoff through `backend/test.sh`: **71 files, 3757
passed, no functional assertion failures**, including slow cases. Runner
exit is nonzero on the unchanged local 0.30s CPU guard in six files, not
claimed as a green local full run. Hardening has 141 passing cases
including malformed MGET batch responses; no CPU-budget changes.
- [x] Load-sensitive recovery-pacing and batch-pressure guard failures
clear on canonical single-file retry. Remaining slow-marked
replay/matrix guards are outside the normal fast lane. Unchanged
speaker-carry test takes 0.56s here versus a borderline 0.30s warning on
detached main `d4062b9ee8` (36 assertions pass on both); the round-4
main probe did not reproduce a failure. No threshold, marker, allowlist,
or out-of-scope code changes.
- [x] Touched-source Pyright: zero errors; black check clean; async scan
zero findings. `make preflight` and explicit body validation each pass
31 checks. Logs: `.local/pr-20422-r4-full.log`, `pr-20422-r4-retry.log`,
`pr-20422-r4-main-speaker.log`, `pr-20422-r4-pyright.log`,
`pr-20422-r4-async.log`, `pr-20422-r4-repo-preflight.log`, and
`pr-20422-r4-body.log`.
- [x] Normal push of head `62750e215e2974151fffb78c784dbc2fb744c0fa`;
pre-commit and bounded pre-push gates passed, including latest-main body
validation. PR remains draft. No merge or deployment.
- [x] Exact-head GitHub CI green on
`62750e215e2974151fffb78c784dbc2fb744c0fa`, first attempt: [Backend Unit
Tests run
37154015517](https://github.com/BasedHardware/omi/actions/runs/37154015517)
passed all four shards, slow guardrails and aggregate suite. Hermetic
Backend E2E/merge gate, CodeQL, source closure, formatting/hygiene,
OpenAPI and PR metadata checks passed. Applicable client checks
correctly skipped. PR remains draft; no merge or deployment.

Round-4 full-set command from `backend/`:

```sh
PYTHON=.venv/bin/python BACKEND_PYTEST_WORKERS=2 \
  BACKEND_PYTEST_MARK_EXPR='not integration' \
  BACKEND_UNIT_TEST_FILE_LIST=../.local/pr-20422-r4-full-files.txt bash test.sh
```

## Historical round 3 evidence

- [x] Round 3 pre-fix reproduction through `backend/test.sh`: all eight
reported failures reproduced across the three named files.
- [x] Initial corrected four-file run: recovery matrix 97, replay pairs
27, Soniox rate-limit 12 and hardening 109 cases passed. Follow-up
hardening review cases: 113 passed.
- [x] Touched-source Pyright zero errors; Python formatting clean. No
fast CPU threshold change.
- [x] Full requested hermetic file-family set through `backend/test.sh`:
69 matching unit files plus `test_connect_refusal_backoff.py`,
file-isolated, including slow-marked cases
(`BACKEND_PYTEST_MARK_EXPR='not integration'`), **zero assertion
failures**. The combined run exits 1 on CPU guards; this is not claimed
as a completely green local run.
- [x] Canonical slow lane (`backend/scripts/run-slow-guardrails-ci.sh`):
1438 passed. Slow-heavy gate/shadow/recovery files also pass their
normal fast lane. The early-provider-deaths load-only CPU failure passes
its documented single-file retry.
- [x] Remaining local timing failure independently reproduced on
pristine main `7b40315647` in a separate owned worktree: unchanged
`test_live_speaker_carry.py::test_matcher_does_not_emit_an_automatic_alternative_for_a_carried_person`
takes 0.47s CPU against the 0.30s guard on both main and this branch; 36
assertions pass in each. No threshold, marker, allowlist or assertion
changed. GitHub's existing 1.0s-ceiling unit lane passed.
- [x] `make preflight` and `scripts/pr-preflight --pr-body-file
.local/pr-20422-body.md`: 31 checks passed in each.
- [x] Round-3 head `bdf23e8899b4dc2ca4138d0950ed9ce60bc1ff8c` pushed
normally; pre-commit and bounded pre-push gates passed; PR remains
draft.
- [x] CI run `37146871133` passed the original eight regression cases,
shards 2/3/4 and slow guardrails. Its initial shard-1 failure is the
unchanged
`test_log_sanitizer.py::test_soniox_persistent_rate_limit_log_redacts_payload`:
the test resets its last-log timestamp to zero but does not control
monotonic time, and `soniox.py:145` suppresses logging below 300
seconds. Executing that original assertion with monotonic=100 reproduces
the failure on both main `7b40315647` and this branch; monotonic=400
passes on both, and the unchanged full sanitizer file passes 115 cases
on the main baseline. The normal failed-job retry passed; no code,
production/test assertions or checks were changed for this unrelated
condition.
- [x] All applicable GitHub CI green after retry: [Backend Unit Tests
run
37146871133](https://github.com/BasedHardware/omi/actions/runs/37146871133),
attempt 2, exact head `bdf23e8899`. All four shards, slow guardrails and
aggregate suite passed; hermetic backend E2E/merge gate, CodeQL, source
closure, OpenAPI and selected repo checks passed. PR remains draft; no
merge or deployment.

Full-set command from `backend/`:

```sh
PYTHON=.venv/bin/python BACKEND_PYTEST_WORKERS=2 \
  BACKEND_PYTEST_MARK_EXPR='not integration' \
  BACKEND_UNIT_TEST_FILE_LIST=../.local/pr-20422-r3-full-files.txt bash test.sh
```

Local evidence is ignored under `.local/`: `pr-20422-r3-before.log`,
`pr-20422-r3-after.log`, `pr-20422-r3-hardening.log`,
`pr-20422-r3-full.log`, `pr-20422-r3-retry.log`, `pr-20422-r3-slow.log`,
`pr-20422-r3-fast-retry.log`, `pr-20422-r3-main-speaker.log`,
`pr-20422-r3-preflight.log` and `pr-20422-r3-body.log`. File-isolated
execution preserves test import isolation and the local 0.30-second
fast-test CPU blocking limit.

Line-Count-Exception: backend/utils/stt/streaming.py | 2324 -> 2367 |
Reviewed router hardening: separate endpoint selection and credential
account rotation, and route custom endpoint serving deaths to their
local target circuit. No socket send/recovery path changes.

Generated with [Devin](https://devin.ai)
Git-on-my-level added a commit that referenced this pull request Oct 5, 2026
## What changed and why

Set `STT_FAILOVER_RECOVERY_ENABLED=true` for prod listen in the Helm
values and runtime overlay, regenerate the runtime manifest and
feature-flag registry, and align the listen pipeline/rollout docs. This
enables the recovery stack from #20391/#20491/#20534/#20560/#20671 for
new stable listen sessions after deployment.

Dev listen remains `false` in its chart and runtime overlay. The shared
base and code default stay `false`, so a missing environment variable
means off. `SONIOX_IDLE_CLOSE_SECONDS`, router mode, provider order, and
allocations are unchanged.

## Canary evidence — coordinator to complete

**PLACEHOLDER:** attach the 25% prod listen canary versus control
evidence after it holds through the next peak: exact image/config,
observation window including peak, cohort and scrape coverage, session
counts, recovery/continuity and terminal-after-text rates, latency and
error comparison, and the coordinator's acceptance decision. Canary
success is supplied context; this PR preparation does not independently
qualify production health. Keep this PR draft until the coordinator
fills this evidence and authorizes the stable flip.

## Deploy and rollback

Deploy prod listen Helm through the normal `gcp_backend_listen_helm.yml`
workflow (`environment=prod`, `mode=deploy`) after the coordinator
merges the approved config flip. This draft does not merge or deploy
anything.

Rollback: revert this PR and deploy listen through the same normal
workflow. For emergency rollback, use `gcp_backend_listen_helm.yml` with
`environment=prod`, `mode=rollback` (select the pre-flip Helm revision
if needed).

## Follow-up

This flag also flips the canary-only terminal-after-text (TAT) metric,
`omi_live_session_terminal_after_text_total`, fleet-wide. After stable
rollout, relax the canary-scoped selectors from #20660 for the alert's
volume floor, numerator, and denominator together. Alert rules are
unchanged here; the coordinator owns this follow-up to #20660.

## Product invariants affected

- INV-MEM-4: the generated runtime manifest is in scope; canonical
memory intake, promotion authority, and processing-host bindings are
unchanged.

## How it was verified

- `PATH="$PWD/backend/.venv/bin:$PATH" bash
backend/scripts/pre-deploy-check.sh`: passed runtime/workflow/state
validation for dev and prod, plus 284 deploy contract tests.
- `BACKEND_UNIT_TEST_FILE_LIST="$PWD/.local/stable-flip-test-files.txt"
bash backend/test.sh`: 73 cases passed across
`test_stt_failover_recovery_flag.py` (45) and
`test_listen_stt_rollout.py` (28), including Helm canary rendering and
flag-off behavior.
- Offline `helm template` for prod and dev: exactly one recovery
declaration per rendered listen container, prod `true` / dev `false`.
Compared chart env and composed runtime state against `origin/main`:
only prod listen's recovery value changed; other runtime settings and
code defaults were preserved.
- `OMI_PR_BODY_FILE=.local/pr-stable-flip-round2-body.md make
preflight`: all 38 selected checks passed, including the committed-diff
rerun.
- `scripts/pr-preflight --lane local --metadata-only --pr-body-file
.local/pr-stable-flip-body.md`: all 3 metadata checks passed.
- Re-ran the committed-diff preflight with the required INV-MEM-4
citation for `backend/deploy/runtime_env.yaml`.

Production acceptance remains the coordinator's canary evidence above.

## Tests

Added `test_stable_recovery_flag_is_scoped_to_prod_listen` in
`backend/tests/unit/test_listen_stt_rollout.py`: prod listen must
declare `true` in Helm values and both committed/freshly composed
runtime manifests; dev listen must declare `false`. Exhaustive runtime
declaration paths require pusher, sync, desktop-backend, jobs, shared
config, and every other service to leave the flag unset.
`test_stable_recovery_code_default_remains_off` checks unset and
explicit false against the production reader. Existing default-off and
canary tests are unchanged. This pins the rollout boundary identified in
Luna's review of #20696; the shared composition primitive already
validates general config consistency, while this test preserves the
intended service scope.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/20696?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
Git-on-my-level added a commit that referenced this pull request Oct 5, 2026
…20660)

Keep the router off until saturation escape, paid spillover admission,
bounded no-text rescue and continuity alerts are reviewable. Router-on
selection now retains permitted configured endpoints when custom breaker
state is saturated. Endpoint aliases use the family breaker, and
router-on managed rebuild accounting admits the registry's 16 targets
plus legacy endpoints.

Paid spillover admission is gated by
`STT_PAID_SPILLOVER_BUDGET_ENABLED=false` (default). Redis atomically
admits at most 30 router-promoted paid dials per provider per Redis UTC
minute, shared across pods, accounts and endpoint aliases; rotations do
not reset the cap; provider limits are configurable (integer 0–10000).
Malformed or out-of-range caps deny promotion before Redis access, log
once per provider without the raw value, and restore configured order.
Denial/Redis failure restores configured order. This is a router
promotion budget: the static chain can still require paid traffic.

No-text rescue is gated by `STT_NO_TEXT_RESCUE_ENABLED=false` (default)
and requires `STT_FAILOVER_RECOVERY_ENABLED=true`. One session gets at
most 60 seconds each of paid wall-time admission and admitted audio
(including replay), configurable between 5 and 120 seconds. Lease expiry
tries Parakeet once using normal capture replay and owner fences. If
cheap admission fails, the session terminates rather than silently
extending paid processing. Empty audio remains ambiguous. Returned cheap
decoding retains audio and suppresses further no-text rescues for that
session; real transport faults retain normal recovery. The gated window
progress deadline also rearms after text. Rescue evidence requires
capture-mapped text overlapping the original stalled interval;
later/unmapped text is unproven. Physical transport cleanup remains
bounded by the existing abort path.

#20391 already ships recovery-gated terminal-after-text telemetry.
Recovery is enabled across production listen, so the dedicated rule now
includes all backend-listen series, including stable and former-canary
traffic, while retaining the 20-session accepted-session volume floor;
the independent mid-session terminal rule covers every path. Chart
sources and the canonical combined Grafana export alert on
terminal-after-text and mid-session terminal failure, replay continuity,
paid capacity, combined pressure, POST latency, lifecycle/persistence
gaps, snapshot readiness, unknown selected targets and stage
disagreement. The existing live-STT importer and coverage gate include
the new rules (26 active UIDs); monitoring import must precede live
coverage verification. No workflow changes.

Production is read-only. Aggregate 24h queries on 2026-10-04 returned
approximately 811 first-text-deadline window outcomes, 5,152 text
outcomes, and 634 deadline fallback events. They have different
populations and cannot attribute paid billing. The new aggregate rescue
audio/proof metrics support that join going forward. A synthetic
one-hour all-paid Soniox remainder costs $0.0754 versus at most
$0.001257 of leased Soniox audio plus subsequent cheap processing;
provider billing increments remain outside that audio-price model;
admitted replay is included in the lease budget.

Validation: 973 focused hermetic unit cases across thirteen files
through `backend/test.sh` with the unchanged 0.30s CPU guard; saturation
tests cover all breaker entries protected, capacity signals on/off,
alias/default tails, both recovery modes and hard withdrawals. Receiver
tests exercise lease expiry, successor text/emptiness, replay audio
budget and cheap re-entry. Local disposable Redis qualification passed:
200 concurrent attempts across four clients admitted exactly 30. `make
preflight` passed 33 checks; backend pyright reports zero errors. The
unchanged 0.30s CPU guard was rerun in file isolation after machine-load
failures. Round 2: 108 focused cases passed through `backend/test.sh`
(44 router-readiness, 16 exported-query counter fixtures, 48 monitoring
contracts). A negative-control replay of the prior exported queries
reproduces the diluted non-firing alert while both fixed exports fire at
2%. Fixtures cover job/cohort isolation, the 20-session volume floor,
the strict 1% threshold and no data. Cap cases cover all three
providers, defaults, bounds, malformed values, denial before Redis, one
warning without the raw value, corrected configuration and real
configured-order fallback. CI status will be attached at handoff.

Failure-Class: FC-live-stt-audio-lost-on-provider-death

Before any on-percent > 0: coordinator Luna review, terminal CI on this
exact head, merge and deployment by the coordinator, uniform
image/config and isolated namespaces, enabled limiter/rescue canary
qualification, production-shaped paid headroom tests, rendered
adapter/replay soak and tested live alert delivery/rollback. This PR
does not authorize enablement, merge or deployment.


Line-Count-Exception: app/lib/services/capture/capture_controller.dart |
4074 -> 4077 | Flutter 3.44.5 formatter normalized inherited origin/main
changes during merge; formatting only
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant