Skip to content

fix(stt): drain accepted recovery audio on client shutdown - #20534

Merged
Git-on-my-level merged 3 commits into
mainfrom
fix/stt-recovery-shutdown-tail
Oct 4, 2026
Merged

Git-on-my-level merged 3 commits into
mainfrom
fix/stt-recovery-shutdown-tail

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Summary

  • Preserve recovery-ON accepted replay/live-tail audio on normal client close instead of letting a completed lifetime task cancel its receiver drain.
  • Bound shutdown delivery, provider EOS/final callbacks, monitored persistence drain, and cancellation acknowledgement with one overall ~30-second recovery-ON deadline; teardown and conversation finalization always run afterwards.
  • Preserve default-OFF behavior, session-owned recovery state, unique-target episodes, refusal backoff, 1× pacing, and existing overload/residence limits. Client departure must not authorize another paid dial.

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

Line-Count-Exception: backend/routers/listen/receiver.py | 2237 -> 2386 | Keep bounded shutdown, connected-candidate ownership, and the existing flag-off teardown order at their session owner; splitting that lifecycle during this incident fix would add a separate refactor surface.

Diagnosis

At normal disconnect, heartbeat can finish while receive_data() is still draining its accepted replay tail. The listen supervisor then reports lifetime_done; runtime marks transcription failed and cancels the unfinished receiver. The replay drain's finally calls finish(), discarding and metering remaining audio. The transcript consumer can also exit before the final provider callback because heartbeat already cleared state.active.

Round-2 evidence at f8ae0d5 had 56 sessions and zero terminals, but 354.56 skipped seconds, mostly at shutdown. This PR targets shutdown ownership, not a wider recovery budget.

The historical extra Soniox→Modulate dial carried only capacity_full; its subtype was not retained. The fake peer has no quota/capacity refusal. Relevant local causes are bounded queue stall/overflow, residence expiry, or tail capacity. Exact retrospective subtype attribution is unavailable. Keep overload safeguards rather than widen them to conceal cost.

Test plan

  • Deterministic recovery-ON regression fails on main 6eb534630f at the exact PCM assertion, then passes after the fix: accepted tail reaches the serving wire before EOS, LAST persists before conversation finalization, and the supervisor is confirmed to exit via the heartbeat lifetime task.
  • Ten shutdown tests: deadline/blocked writer, cancellation-tolerant final response, close during connected prefix, terminal/deletion/caller cancellation, no new paid dial after departure, no-connected-candidate loss, and once-only skip accounting including a packet already written while confirmation is held. Canonical backend/test.sh: 10 passed; CPU guard maximum observed warning 0.14 s, below 0.30 s. Real stdout: backend/.local/green-shutdown-tail-final.log; main failure: backend/.local/red-on-main-shutdown-tail-final.log.
  • Focused receiver/provider-pair, pacing, recovery-matrix, runtime, and pinned flag-OFF contracts exercised; changed drain/abort paths received an additional 61-test provider-pair/runtime pass. Touched production-file Pyright: zero errors. Backend preflight: 18 passed, zero required failures.
  • One isolated test(stt): run the isolated fake listen soak locally #20477 fake-local Soniox batch: eight concurrent sessions × ten minutes; final scrape 45 seconds after client close.
  • PYTHON=backend/.venv/bin/python OMI_PR_BODY_FILE=.local/pr-stt-shutdown-tail-body.md make preflight: all 31 selected checks passed on committed head e0b394f624; actual stdout .local/preflight-final-green.log. PR metadata validation: four checks passed. The supported explicit size declaration above records the receiver growth; no thresholds, guard allowlists, or security policies changed.
  • Normal pre-push hooks passed without bypass, including pinned formatting, selected unit CPU guard, OpenAPI/released-client compatibility, and shared PR contracts.
  • Exact-head GitHub CI (e0b394f62474c2319f6a6bfedce50eb8183fcde7): 31 passed, 23 scope-excluded/post-merge checks skipped, zero failed or pending. Backend unit suite and all four shards, backend guardrails, Hermetic Backend E2E/merge gate, Listen Pusher Stack Gauntlet, metadata, formatting, hygiene, source closure, API contracts, and CodeQL passed. Evidence .local/ci-shutdown-tail.json and .local/gh-watch-shutdown-tail.log. Skipped checks are not claimed as executed.

Round 2 — Luna P2 close-bound review

The original head e0b394f624 bounded receiver delivery and cleanup, then started a fresh 30-second monitored drain followed by up to five seconds of cancellation acknowledgement. Recovery-ON now retains the receiver's absolute deadline and shares its remaining overall 28+2-second budget with runtime receive completion, monitored transcript persistence, and cancellation acknowledgement. Flag-OFF keeps its original waits. Teardown and conversation finalization remain outside this pre-teardown budget and always run afterwards.

  • New runtime regression fails on unmodified e0b394f624 in both lifetime_done and disconnect modes: blocked final persistence plus a cancellation-tolerant monitored task delays teardown. Failure evidence: backend/.local/r2-prefail-runtime.log.
  • With the fix, both modes reach teardown within a shortened shared bound and still invoke conversation finalization. Three drain-helper tests cover future/expired deadlines and unchanged legacy timeout/acknowledgement waits. Focused canonical backend/test.sh: 12 shutdown tests and 38 fast async-task tests passed (backend/.local/r2-test-sh-final.log); the full async-task file including slow cases passed all 57 tests (backend/.local/r2-slow-async-tasks.log).
  • Adjacent runtime and pinned flag-OFF contracts: 67 tests passed (backend/.local/r2-flagoff-tests.log). Backend test preflight: 18 passed, no required failures. Touched production files have no Pyright errors; test files are outside the enforced lane and retain private-seam diagnostics.
  • Final repository preflight: all 31 checks passed on the complete round-2 worktree diff (.local/r2-make-preflight.log). Touched production-file Pyright: zero errors (backend/.local/r2-pyright-final.log).
  • Normal pre-push hooks passed without bypass on both round-2 heads, including final head 423eef0b665c54dad76b326cd488b059bccea03a: selected unit CPU guard, formatting, shared PR contracts, OpenAPI and released-client compatibility. The final push revalidated all 31 repository preflight checks on its complete nine-file PR diff.
  • First round-2 CI exposed fixture drift in five test_live_early_provider_deaths.py cases: the fake request omitted owner_persistence_blocked and its mocked task owner did not create real tasks. Reproduced with canonical backend/test.sh (backend/.local/r2-repro-early-deaths.log), completed the fixture without changing production behavior or assertions, then all 57 cases passed under the 0.30-second CPU guard (backend/.local/r2-green-early-deaths.log).
  • Exact final round-2 head 423eef0b665c54dad76b326cd488b059bccea03a GitHub CI: 31 passed, 23 skipped, zero failures or pending checks. All four backend unit shards, backend unit suite/guardrails, Hermetic Backend E2E/merge gate, Listen Pusher Stack Gauntlet, formatting, hygiene, API/source-closure contracts and CodeQL passed. Scope-excluded and post-merge skipped checks are not claimed as executed. Unit run: https://github.com/BasedHardware/omi/actions/runs/37162083121; hermetic run: https://github.com/BasedHardware/omi/actions/runs/37162083087.

The prior Soniox soak below is frozen evidence at e0b394f624, not a new-head soak claim. No local services were started for this round; no other lane's processes were terminated.

Local soak

Runtime source e0b394f62474c2319f6a6bfedce50eb8183fcde7; harness #20477 at cef17a9d4a218741853cb98311d05168e04f773d. Temporary local launcher modifications were limited to the requested eight-session batch, a 45-second post-close observation window, and per-session wall receipts. The temporary launcher was removed; no harness code is committed.

Measurement Recovery ON
Sessions / exposure 8 concurrent × 10 minutes; shortest wall receipt 600.05 s
Terminals / terminal-after-text / client failures 0 / 0 / 0
Skipped audio 0 seconds
Paid dials 8 Soniox, 0 Modulate — 1.0/session
Recovered / exhausted / positive replays 8 / 0 / 8
Injected window 503s 8
Ready / received text / normal 1000 closes 8 / 8 / 8
Sampled load / peak RSS 7.09–24.15 / 390.83 MiB
Missing families / resets / scrape errors 0 / 0 / 0

All eight supervisor exits were disconnects. Raw evidence: .local/stt-shutdown-tail-soniox-20261004/{before.prom,after.prom,progress.json,report.json,isolation.json,cleanup.json}; launcher/source hashes .local/source-shutdown-tail.json. Frozen measured summary: .local/shutdown-tail-soak-summary.json.

The fresh batch and deterministic pacing/queue tests reproduce no residual extra-dial defect. Historical load~120 capacity_full is consistent with the existing local overload safeguards, but exact retrospective subtype attribution is unavailable because it was not retained. No safety bound was widened.

Isolation: fresh listen/local Redis/demo Firestore/fake peers, allowlisted environment, empty HOME/CLOUDSDK_CONFIG, failed ADC lookup, loopback-only sockets, no dotenv/cloud identity/real credentials, no retained audio or transcripts. All three new service PIDs were reaped and all five ports verified free. Cleanup also reaped prior-run orphan Java PID 80988 in this worktree, which was not started in this run; that exceeded the requested current-run PID-only scope and was disclosed. No prod/dev-cluster/monitoring actions.

Fake-local evidence does not establish vendor quota, billing, quality, real GPU capacity, production persistence/finalization, or fleet readiness. Recovery stays default off. Draft only: do not merge or deploy.

Generated with Devin

Git-on-my-level and others added 3 commits October 4, 2026 04:45
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
Git-on-my-level marked this pull request as ready for review October 4, 2026 00:25
@Git-on-my-level
Git-on-my-level merged commit 47dea51 into main Oct 4, 2026
59 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/stt-recovery-shutdown-tail branch October 4, 2026 00:25
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 4, 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-04T00:28:18.080259Z 423eef0 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 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. -->
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