Skip to content

fix(listen): fail over at the audio send path, not just the death-monitor poll - #12469

Merged
mdmohsin7 merged 3 commits into
mainfrom
fix/stt-send-path-failover
Aug 31, 2026
Merged

mdmohsin7 merged 3 commits into
mainfrom
fix/stt-send-path-failover

Conversation

@mdmohsin7

@mdmohsin7 mdmohsin7 commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Problem

#12459 added mid-session STT failover, but wired it only into _monitor_stt_death, which polls the death latch every 1.0s. The audio send path (send_live_stt_audio) checks the same latch on every chunk and terminated the session directly (stt_failed + WebSocket 1011). With audio flowing, the send path observes a provider death within ~100–300ms of the error frame — always before the 1s poll — so the failover was structurally unreachable exactly when it was needed.

Measured in production during the 2026-08-31 Velma outage (chain velma → soniox → dg, image f125bb8 with #12459 deployed):

omi_live_stt_terminal_failures_total{provider="modulate", phase="connection"}: +3,110 in 30 min
'STT failover mid-session' log events: 0

Pod logs show the loop users sat in: Velma accepts the upgrade → Modulate streaming error: Internal server error ~300ms later → session closed ~200ms after that → the client reconnects → repeat, every ~2 seconds per device.

Fix

  • send_live_stt_audio — the single termination authority for the live send path — now accepts an attempt_failover callback and only declares a recoverable death terminal once the chain is exhausted. After a successful failover the chunk is reported unsent with the caller's buffer intact. socket_unavailable (no socket ever initialized) stays terminal: there is nothing to fail over from.
  • _flush_stt_buffer passes _failover_stt_socket and retries in a bounded loop so the buffered audio reaches the replacement socket in the same call — the next client chunk can be a VAD-gated silence away.
  • _failover_stt_socket is serialized behind a lock: the death monitor and the send path can observe the same death within milliseconds of each other, and the loser adopts the winner's replacement instead of burning a second chain slot on a redundant rebuild. MAX_STT_FAILOVERS still bounds the walk.
  • Multi-channel and custom-STT sessions are unchanged; fix(listen): fail a live STT session over to the next provider #12459's single-channel-only scope still applies.

The guard surface for this class is now behavioral, not positional: the termination authority itself refuses to declare a recoverable death terminal without offering the failover, and tests/unit/test_live_stt_failure.py pins that contract for every current and future caller of the send path.

E2E wire-contract update

Two hermetic e2e tests asserted the pre-#12459 contract — any provider send failure is immediately terminal — and correctly failed on this branch. Per the rewritten-test rule, the external source for the new expected value is the merged #12459 failover design plus the production measurement above: a death is terminal only once reselection finds no provider. Both tests now pin the receiver's reselection to an exhausted chain and keep their exact terminal payload assertions (stt_failed, bounded reason, close 1011). The reselection pin is also a harness necessity: failover reselects via the receiver's namespace, which the fakes previously left unpatched, so it read the real provider chain and reached for un-faked network clients (the CI timeouts).

Added test_web_listen_streaming_stt_send_failure_fails_over_and_the_session_survives: the wire-level guard for this fix — first socket dies on first send, the session moves to the replacement, the same buffered chunk reaches it in the same flush, a transcript flows, and the client never sees stt_failed.

Verification

Run with the pinned backend venv (pylock.macos.toml):

  • pytest testing/e2e/test_listen_stt.py — 12 passed (new survival test included; terminal test unchanged assertions).

  • pytest testing/e2e/test_listen_pusher_wire_contract.py — 7 passed.

  • pytest tests/unit/test_stt_session_failover.py — 11 passed (4 new: a death observed by the send path fails over and delivers the buffered audio to the replacement in the same call; an exhausted chain still terminates; the lock loser adopts the already-installed replacement instead of rebuilding).

  • pytest tests/unit/test_live_stt_failure.py — 16 passed (3 new: a successful failover is not terminal and preserves the unsent buffer; an exhausted failover stays terminal with the bounded close; a death latched during send also offers failover).

  • pytest tests/unit/test_listen_stt_death_monitor.py — 4 passed (monitor path unchanged).

Not exercised against live Modulate: reproducing the outage needs Velma to emit mid-session error frames on demand. The regression tests drive the production code through the controllable seam the outage used (live_stt_socket_is_dead latch on the socket the flush path holds), and the production numbers above pin the failure mode this would have caught.

Product invariants affected

none — scripts/pr-preflight --suggest: changed paths match no locked invariant globs.

Failure-Class: FC-recoverable-provider-failure-terminal

send_live_stt_audio observes a provider death on the very next audio chunk —
hundreds of milliseconds before the 1s death-monitor poll — and terminated the
session there, so the monitor's mid-session failover (#12459) was structurally
unreachable for any session with audio flowing. During the 2026-08-31 Velma
outage that meant 3,110 modulate sessions terminated in 30 minutes with zero
failovers fired.

The termination authority now accepts the session's attempt_failover callback
and only declares a recoverable death terminal once the chain is exhausted. A
successful failover reports the chunk unsent with the buffer intact so the
caller retries it against the replacement socket.

Failure-Class: FC-recoverable-provider-failure-terminal
…ered audio

The receiver hands _failover_stt_socket to the send helper and retries the
flush in a bounded loop, so the buffered chunk reaches the replacement socket
in the same call instead of waiting for the next client chunk — which a
VAD-gated silence can postpone indefinitely.

_failover_stt_socket is now serialized behind a lock: the death monitor and
the send path can observe the same death within milliseconds of each other,
and the loser must adopt the winner's replacement instead of burning a second
chain slot on a redundant rebuild.

Failure-Class: FC-recoverable-provider-failure-terminal
…d failover survival test

The two send-failure e2e tests asserted the pre-#12459 contract (any provider
death is immediately terminal). The new expected behavior is the merged #12459
failover design: a death is terminal only once reselection finds no provider.
Both tests now pin reselection to an exhausted chain — the receiver's own
namespace drives it, and left unpatched it reads the real provider chain and
reaches for un-faked network clients, which is why they timed out in CI.

New wire test: a death with a provider left in the chain moves the session —
the buffered audio reaches the replacement socket in the same flush, a
transcript flows from it, and the client never sees stt_failed.

Failure-Class: FC-recoverable-provider-failure-terminal
@mdmohsin7
mdmohsin7 merged commit e1eca38 into main Aug 31, 2026
36 checks passed
@mdmohsin7
mdmohsin7 deleted the fix/stt-send-path-failover branch August 31, 2026 09:40
Git-on-my-level added a commit that referenced this pull request Aug 31, 2026
Live 24h realtime_voice on the PTT surface: 4 success, 13 provider_error
terminals, all paired with "Modulate streaming error" frames. #12469 gave
listen a send-path failover; PTT still terminated the session on the first
rejected send, so a Velma/Modulate socket that accepts the upgrade and dies
~300ms later on the first audio chunk ended the session with 1011 even while
the chain held a healthy replacement (14 ptt provider_terminal_failure in 24h,
zero mid-session failovers on the PTT path).

Port the listen pattern instead of forking it: send_stt_audio_or_close now
routes through utils/stt/live_failure.send_live_stt_audio with an
attempt_failover callback that rebuilds the socket on the next provider in the
chain (selector exclude set, MAX_STT_FAILOVERS bound, liveness-proven before
adoption). A successful failover reports the chunk unsent and the bounded retry
sends it against the replacement socket, so no audio is dropped. The terminal
path now shares terminate_live_stt_session with listen: journey
fail('provider_error') via the shared session adapter, a terminal
service_status event, then close 1011 — previously the PTT close carried no
status event and a different reason string, and both desktop PTT clients
ignore non-array frames (Array.isArray guard in omiListen.ts). The
event=ptt_transcription_stream outcome=provider_terminal_failure log line is
kept on every terminal. Codec/paywall/budget/idle-timeout paths are unchanged;
MAX_STT_FAILOVERS moved to utils/stt/live_failure.py so both surfaces share
one bound.

Verification:
- backend/tests/unit/test_desktop_transcribe.py: 71 passed (RED confirmed by
  reverting routers/chat.py: the new failover test fails with a 1011 close and
  no transcript; GREEN with the fix).
- test_live_stt_failure.py + test_stt_session_failover.py: 27 passed
  standalone (test_excluding_every_provider_selects_nothing fails in a
  combined run identically on pristine origin/main — pre-existing, untouched).
- Live self-test: real uvicorn serving the endpoint, local fake Parakeet
  /v3/stream, dummy Modulate key — healthy segment received; killing the
  provider mid-session produced the connect-time fallback telemetry, the
  failover attempt, the terminal service_status event, close 1011, and the
  provider_terminal_failure log line.

Failure-Class: FC-recoverable-provider-failure-terminal
Git-on-my-level added a commit that referenced this pull request Aug 31, 2026
…#12492)

## Problem

Live 24h `realtime_voice` on the PTT surface
(`/v2/voice-message/transcribe-stream`): **4 success, 13 failure — all
`provider_error`**, 5 cancelled. Cloud Logging pairs **14**
`event=ptt_transcription_stream outcome=provider_terminal_failure` with
**14** `Modulate streaming error`, clustered 13:00–14:56 UTC. Not a
metrics lie, not a Beta-vs-prod app gap: the same Cloud Run backend
serves both, and the serving SHA (`e1eca38`) already carries #12469.

#12469 fixed **listen** mid-session STT failover at the **send path**.
PTT still did this on the first rejected send:

```python
async def send_stt_audio_or_close(audio: bytes) -> bool:
    ...
    if accepted:
        return True
    await close_stt_failure()  # 1011 + journey fail('provider_error')
    return False
```

Velma/Modulate accepts the WebSocket upgrade and only then dies ~300ms
later on the first audio send — the exact shape #12469 closed for
listen. PTT's connect-time `connect_stt_socket_with_fallback` cannot
help there, so a recoverable death terminated the session with 1011
while the chain still held a healthy replacement. The 13 failures never
received a nonempty transcript; `ClientJourneyAttempt.finish` being
one-shot is why the 4 working sessions stayed successes.

Not Beta vs prod. Not dashboard math. Out of scope by design:
Grafana/`client_kind` (SCA-388), success-rate PromQL, provider chain
order, desktop client changes.

## Fix

Port the listen send-path failover onto PTT — reuse, not a fork:

- `send_stt_audio_or_close` now routes through
`utils/stt/live_failure.py::send_live_stt_audio(...,
attempt_failover=...)`.
- The callback mirrors listen's `_failover_stt_socket`: dead-provider
exclusion set fed to `get_stt_service_for_language(..., surface=PTT,
exclude=...)`, bounded by `MAX_STT_FAILOVERS` (moved to
`utils/stt/live_failure.py` so both surfaces share one bound),
replacement proven serving (`fallback_socket_is_serving`) before
adoption, rejected rebuilds released.
- A successful failover reports the chunk unsent and the bounded retry
sends it against the replacement socket — no audio dropped (listen's
flush contract).
- Terminal handling now shares `terminate_live_stt_session` with listen
via a small `_PTTStreamSession` adapter: journey
`fail('provider_error')` only when the chain is exhausted (or no socket
was ever initialized), one terminal `service_status` event, then close
1011 — the same wire contract as `/v4/listen`. Both desktop PTT lane
parsers ignore non-array frames (`Array.isArray` guard in
`desktop/windows/src/main/ipc/omiListen.ts`), and the e2e suites collect
segment arrays only.
- Kept: `succeed()` on first nonempty transcript; the
`event=ptt_transcription_stream outcome=provider_terminal_failure` log
line on every terminal; codec/paywall/budget/idle-timeout cancel
behavior.

## Verification

- `backend/tests/unit/test_desktop_transcribe.py` — **71 passed**. New
behavioral tests:
- `test_ws_send_path_death_fails_over_and_retries_chunk` (GREEN: swaps
parakeet→modulate, retries the same chunk verbatim, no `provider_error`,
later transcript `succeed()`s; **RED** against the pre-fix endpoint:
same test 1011s with no failover — verified by reverting
`routers/chat.py`).
- `test_ws_send_path_death_with_exhausted_chain_closes_1011`
(replacement that never serves is released; `provider_error` + 1011; no
usage charge).
- Updated terminal-wire tests assert the status event before close 1011.
- `test_live_stt_failure.py` + `test_stt_session_failover.py` (listen
failover) — **27 passed**.
`test_excluding_every_provider_selects_nothing` fails when these files
run combined with `test_desktop_transcribe.py`, **identically on
pristine `origin/main`** — pre-existing selection-order interaction,
untouched by this PR.
- Live self-test (commands + observed behavior): real `uvicorn` serving
the real endpoint (auth bypassed via `app.dependency_overrides` only),
local fake Parakeet `/v3/stream` WebSocket, dummy Modulate key. Healthy
phase: connect-time fallback `from=modulate to=parakeet
outcome=recovered`, transcript segment received over the live socket.
Killed the provider mid-session: send-path death latched, failover
attempted, chain exhausted, terminal `service_status stt_failed` event
received, close 1011, `event=ptt_transcription_stream
outcome=provider_terminal_failure` logged.
- `scripts/backend-python-format --check`,
`backend/scripts/scan_async_blockers.py`,
`backend/scripts/check_module_stub_pollution.py`: clean.

Failure-Class: FC-recoverable-provider-failure-terminal


Line-Count-Exception: backend/routers/chat.py | 1935 -> 2097 | PTT
send-path failover is session closure state over ~15 endpoint locals
(socket, provider selection, journey, buffers), mirroring listen whose
equivalent lives inside its receiver class; splitting the endpoint out
of chat.py is a separate mechanical PR. +3 lines are a lazy live_failure
import to break the chat-test circular import.

<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/12492?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. -->
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