Repository navigation
fix(stt): settle router health at the serving decision - #20343
Conversation
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
There was a problem hiding this comment.
2 issues found and verified against the latest diff
Confidence score: 3/5
- In
live_chain.py, Soniox timeouts, rotations, and invalid hints can count as provider failures and trip the circuit for non-provider problems. Exclude those reasons from provider failure accounting. - In
live_failure.py, the 30-second timer permanently marks the hop as degraded, so a successor that produces text later cannot be recorded as recovered. Keep late transcript recovery observable after the timer fires.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="backend/utils/stt/live_chain.py">
<violation number="1" location="backend/utils/stt/live_chain.py:292">
P2: Soniox timing/configuration deaths still count as provider circuit failures here. Exclude the non-provider reasons (`soniox_request_timeout`, `soniox_idle_timeout`, `soniox_rotation`, and `soniox_invalid_hint`) from `record_failure()` and release the admission instead, so normal session timing does not bench Soniox for subsequent users.</violation>
</file>
<file name="backend/utils/stt/live_failure.py">
<violation number="1" location="backend/utils/stt/live_failure.py:170">
P2: The 30s `call_later` timer permanently settles the hop as `degraded`; a successor that proves text after that point can no longer emit `outcome='recovered'` because `note_transcript` early-returns once `_settled` is set. First text can legitimately arrive after 30s (replay flush under load, VAD-gated speech, `STT_NO_TEXT_SECONDS` default of 30s), so recovery evidence is lost for those hops and the source outcome's settlement classification stays frozen at the degraded state. The timer also fires while the hop is still attached and serving, without checking that the receiver/session is still active.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| # report this hop as degraded, without touching its audio | ||
| # or connection. Source availability cannot depend on a | ||
| # silent successor eventually ending its session. | ||
| self._settlement_timer = loop.call_later(30, self._settle_delayed_hop) |
There was a problem hiding this comment.
P2: The 30s call_later timer permanently settles the hop as degraded; a successor that proves text after that point can no longer emit outcome='recovered' because note_transcript early-returns once _settled is set. First text can legitimately arrive after 30s (replay flush under load, VAD-gated speech, STT_NO_TEXT_SECONDS default of 30s), so recovery evidence is lost for those hops and the source outcome's settlement classification stays frozen at the degraded state. The timer also fires while the hop is still attached and serving, without checking that the receiver/session is still active.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/stt/live_failure.py, line 170:
<comment>The 30s `call_later` timer permanently settles the hop as `degraded`; a successor that proves text after that point can no longer emit `outcome='recovered'` because `note_transcript` early-returns once `_settled` is set. First text can legitimately arrive after 30s (replay flush under load, VAD-gated speech, `STT_NO_TEXT_SECONDS` default of 30s), so recovery evidence is lost for those hops and the source outcome's settlement classification stays frozen at the degraded state. The timer also fires while the hop is still attached and serving, without checking that the receiver/session is still active.</comment>
<file context>
@@ -151,11 +151,50 @@ def __init__(
+ # report this hop as degraded, without touching its audio
+ # or connection. Source availability cannot depend on a
+ # silent successor eventually ending its session.
+ self._settlement_timer = loop.call_later(30, self._settle_delayed_hop)
+
+ def _settle_delayed_hop(self) -> None:
</file context>
## What Prod live STT static order back to `parakeet-window,modulate-velma-2,soniox,dg-nova-3` (config only: listen chart, prod overlay, generated runtime env, the pinned test and the doc line). Everything else from #20343 stays. ## Why #20343 changed the prod order to Parakeet → Soniox → Modulate (live in listen `6e1ce64` since 2026-10-02 15:33Z). Since then, Parakeet sessions that fail over (first-text deadline) land on Soniox, the failover replays the capture ring into Soniox's bounded send queue, and the Soniox leg dies with `capacity_full` and no successor — the session ends. Prod, 10-minute buckets, `omi_fallback_total{component="stt_live_session"}` (aggregates only): | Window | parakeet→modulate recovered | parakeet→soniox recovered / degraded | soniox→unavailable exhausted | | --- | ---: | ---: | ---: | | 15:09–15:29Z (before) | 9–16 | 0 / 0 | 0 | | 15:39–15:59Z (after) | 0–1 | 2–3 / 1–3 | 3–5 | Listen logs show `from=soniox to=unavailable reason=capacity_full outcome=exhausted` followed by `connection closed` within ~100 ms, about 25 times in 25 minutes. The underlying defect (replay into Soniox must be paced or the queue sized for it, and a queue-full Soniox leg should fail over rather than end the session) is a follow-up; this PR restores the order that recovered. ## Rollback Not applicable — this is the rollback. ## Deploy Listen helm only, with the current image tag. ## Product invariants affected INV-MEM-4 — the runtime env manifest is a locked path; this changes the configured provider order and no memory behaviour. 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/20354?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. -->
A managed provider death could be claimed during cleanup after the
client had already left, creating router failures with no real serving
handoff. Fence the first serving claim by explicit client/application
disconnect, inactive state and shutdown; preserve claims already made
while connected. Excluded legs retain actual text as success or settle
censored no-text, and emit no provider-failure fallback.
## Resulting behavior
- One accepted physical socket/leg has one serving-owned settlement.
Repeated Velma error frames, death/send/finish observers and connect
validation cannot count it again. New replay/reconnect sockets are
distinct legs.
- `LiveLegOutcome.claim` receives the leg's client lifecycle and
prior-text callbacks. A first claim after departure or owner teardown is
excluded once; a prior connected claim keeps its cause even after
departure. Existing text success remains in the denominator.
- `omi_stt_cost_routing_ignored_deaths_total{target,reason,boundary}`
exposes excluded claims. Registered targets <=16, bounded reason
vocabulary, two boundaries; labels are preinitialized, with no
UID/socket/content dimensions. This diagnoses exclusions, not all raw
close symptoms.
- Fresh state is `omi:live-stt:cost-v7`: v5 and v6 can contain
post-client failures/backoff strikes. Do not migrate or backfill them.
Gate thresholds, vote budgets, provider registry, ramp cohorts and
serving policy are unchanged relative to current main. Raw
connect-attempt diagnostics and per-process circuits remain a separate,
unchanged scope; this PR fences managed serving-health settlements and
their paired fallback emissions.
- Production remains shadow / on-percent zero. No runtime-env, chart,
provider client, transport/recovery/circuit or workflow changes in the
PR diff. No production access or routing-state writes; no merge/deploy.
## Current main integration
Merged origin/main including #20343 (`6e1ce64f5c`), which landed during
validation. Its serving-owned settlement implementation supersedes this
branch's earlier getter/receipt writers: keep read-only liveness and the
single settlement seam. Main now preserves accepted connect-validation
causes and source reasons across rejected successors, and terminal
managed deaths emit fallback to unavailable. This PR adds the missing
actual-client fence to that seam rather than reinstating parallel
writers. Main's deliberate static-order and other serving changes are
preserved without alteration.
## Reproduction and reconciliation
The initial pre-#20343 base had 17 failures / 6 passes in the initial
23-case regression file. After integration, the 26-case socket file
against current main's runtime had **15 failures / 11 passes**. The
fixed tree passes all 26, plus three disabled-mode diagnostic cases.
Three distinct real Modulate sockets (one connected serving failure, two
first claimed after client departure) reproduce the 3:1 excess: **three
failures / one nonterminal hop before; one failure / one hop plus two
ignored claims after**. Reproduces for serve-error and transport loss.
The real Velma parser receives multiple error frames and each leg is
polled/sent/finished repeatedly; this did not reproduce three writes for
one socket.
A five-socket cohort has **three failures = two settled nonterminal hops
(selection + live) + one connected terminal death**, with two departed
sockets excluded. Same equality is asserted per reason. ko/ja/zh
terminal Soniox deaths have a connected client, stt_failed/1011,
terminal metric +1 and connect-chain exhaustion unchanged. That counter
measures construction exhaustion, not serving terminal decisions. Main
now includes terminal deaths in fallback to unavailable: do not add
terminal session counters to the complete fallback total again.
On the deployed #20332 path, accepted warm serve errors were labelled
modulate_serve_error in health but provider_5xx in selection fallback.
Therefore comparing health only to live-session serve-error hops can
produce a large apparent excess without repeated observations; the
connect-validation test demonstrates it. Main #20343 fixes that
attribution, which is retained here.
The supplied production aggregates cannot allocate all 56 excess
serve-error observations or all 11 Soniox observations among paths.
Selection provider_5xx and terminal totals were omitted. The tests
establish false teardown feed and preserve legitimate terminal evidence;
the runbook explains the exact cohort,
terminal/family/legacy/time-boundary qualifications, and the new
ignored-claim query. Paired settlement/observation counts alone can
agree while both classify client churn wrongly.
## Validation
Direct pytest with worktree TMPDIR, `-p no:cacheprovider`,
`--durations=8`: **688 passed across eleven focused suites**, slowest
**0.32s**; all cases below 0.5s locally. New socket cases are below
0.1s. Synthetic protocol/audio and MemoryRedis only.
Suites: test_live_death_socket_accounting,
test_live_early_provider_deaths, test_live_health_reason_reconciliation,
test_live_cost_router, test_live_stt_chain, test_live_stt_failure,
test_modulate_serve_error_deaths, test_soniox_typed_rejections,
test_fallback_observability, test_live_evidence_settlement,
test_parakeet_window_live.
CI exposed an unchanged window-deadline test comparing
12.000000000000028 to exactly 12. Its one assertion now uses
pytest.approx, consistent with the adjacent test; the full 151-case
window file passes. Production window code is unchanged.
Type check: zero errors (10,029 warnings). Final make preflight: 30/30
checks passed on the integrated head. Runbook, STT architecture and
pipeline owner document client eligibility and state v7.
## Product invariants affected
none — no locked runtime/config paths or client wire models changed
relative to main.
Failure-Class: none
## Review fixes
- Snapshot client/owner eligibility and the bounded provider-death cause
on the managed leg's first death observation. A death observed while
connected remains provider-failure evidence through a later client
departure; a death first observed after departure or owner teardown
remains excluded.
- Added both death/departure/claim orderings and a #20348 bounded
rebuild-exhaustion regression. Repeated exhaustion handling settles that
leg and fallback exactly once under the same eligibility fence.
- Merged current `origin/main`, including #20348 (`live_recovery.py` and
bounded rebuild tests); retained both intents.
Validation: the requested six-suite combined run passed **383 tests**
(7.21s total; slowest case 0.32s). `make preflight` passed **30/30
checks** (96.18s); the shallow-clone 90-day failure-class guard skipped
its enforcement window.
…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. -->
Provider health was inferred from socket liveness and teardown independently of the serving decision. That both censored early Modulate deaths and invented Soniox failures during client churn. This change makes a leg's exactly-once terminal settlement emit both the existing fallback event and router observation, with the original bounded cause frozen before transport cleanup. Liveness getters are read-only; accepted deaths need no VAD minimum; terminal-provider exhaustion is visible too.
cost-v6gives each hashed user at most three classified votes per target/scope/five-minute Redis-time window, enforced by CAS with bounded state. Raw observations remain uncapped for emission accounting. Healthy windows have 2,048 ordinary fingerprints plus an eight-distinct-user outage reserve that resets on every classified success; eight new failures still bench after saturation without failure-only CUSUM sampling. Healthy Redis keys expire after 900 idle seconds; benches/trials persist so expiry cannot bypass staged recovery. Independent chain-opened / terminal-settled / transport-open lifecycle metrics and honestly named emission-acknowledgement/error/vote counters and an intent-to-treat router-canary transcript SLI support the runbook's 60–120 minute shadow qualification and 5→25→100 ramp. The gate remains 8%; reproducible synthetic calibration reports zero false benches in each 400,000-session healthy-floor scenario and p95 detection at 48/21/8 sessions for 40%/60%/100% failures.Production remains
STT_ROUTING_MODE=shadow,STT_ROUTING_ON_PERCENT=0. Deliberate serving changes: configured fallback order becomes Parakeet window → Soniox → Modulate → Deepgram; Soniox timing/configuration, local VAD and other censored input causes no longer accumulate provider circuit failures at connect or terminal settlement; client teardown transport errors cannot start recovery or open provider circuits; local queue/loop/input failures retain non-provider causes; an active router cannot reappend a registry-withdrawn default endpoint as a legacy tail. No-text remains censored and diagnostic; the existing transcript-success alert remains the detector, with no new silent-stream rescue.#20332 merged while this lane was in progress. This branch merges that main revision and supersedes its parallel receipt writers, retaining and extending its real parser/receiver tests and preserving the new
soniox_request_timeoutlabel. No merge or deployment is performed by this lane. Merged origin/main again at 81a51d0 after #20340 landed. Its Parakeet allocation/capacity values are preserved exactly at 100/16; #20344 slow marks remain intact.Validation
Real
LiveLegSocket+ provider parser + receiver tests reconcile 120 accepted deaths, before-audio/subsecond/no-VAD paths, typed terminal causes, connect rejection, exhaustion, cancellation, and client teardown.Fleet CAS tests cover 46 reconnects across pods, concurrent budget admission, bounded fingerprint storage and generation fencing.
Initial STT/provider/runtime regression run before the final review: 2,268 tests passed across 50 isolated files, with
BACKEND_FAST_UNIT_FAIL_SECONDS=1.0; two real listen-runtime parity tests also passed under the same guard with an external--basetemp(their capture validator intentionally rejects checkout-local roots). Type checking: zero errors.make preflight: all 38 selected checks passed with this PR body; normal push hooks passed.Test command:
cd backend && BACKEND_UNIT_TEST_FILE_LIST=<selected file list> BACKEND_FAST_UNIT_FAIL_SECONDS=1.0 BACKEND_PYTEST_WORKERS=3 TMPDIR=$PWD/../.pytest-tmp bash test.sh. Focused real-object cases also used.venv/bin/python -m pytest -q -p no:cacheprovider <files> --durations=8.The separate slow lane also passed all 668 calibration tests and both files are registered in the existing slow-guardrail CI manifest; main's slow marks are retained; the fast baseline sample uses 20k sessions per rate and the full separate calibration retains 400k per scenario. Full realistic-floor calibration was run separately. Exact qualification PromQL and canary/abort conditions:
backend/docs/runbooks/live-stt-routing.md.Synthetic calibration:
cd backend && .venv/bin/python scripts/stt/calibrate_live_gate.py; no user transcript/audio access or production-state writes. Production acceptance is pending coordinator deployment/shadow checks.Product invariants affected
Failure-Class: FC-decoded-outcome-discarded-before-canonical-record
Line-Count-Exception: backend/routers/listen/receiver.py | 1835 -> 1844 | Wire the shared settlement and teardown fence at existing serving-owner boundaries; extracting unrelated receiver/provider logic would widen this incident fix.
Line-Count-Exception: backend/utils/stt/streaming.py | 2186 -> 2188 | Wire the shared settlement and teardown fence at existing serving-owner boundaries; extracting unrelated receiver/provider logic would widen this incident fix.
Review decisions
The 30-second pending-hop bound is intentional:
degradedmeans recovery was unproven by the deadline. Late successor text remains visible in leg/session and router-canary transcript SLIs; it does not emit a second fallback or change the source provider-failure vote. Waiting indefinitely for successor speech would again make outage detection depend on user audio.Review corrections include invalid-percent telemetry fail-open, a teardown recheck after awaited recovery, settlement on engine-mismatch recursion and cancelled replacement retries, aligned prod ConfigMap/inline order, and explicit censored local circuit causes. The long calibration files are now registered in the existing slow-guardrail CI manifest, while the fast lane stays below its per-test CPU budget.
Serving behaviour changes
Luna final review corrections
omi_stt_cost_routing_emission_ack_errors_totalreplaces the misleading reconciliation name. It does not prove classification, settlement coverage or Redis persistence.omi_stt_managed_legs_opened_total - omi_stt_managed_legs_settled_total - omi_stt_managed_legs_openis exported by target/pod. A regression deliberately suppresses settlement and verifies that this gap grows while acknowledgement errors need not change. Go/no-go rejects a nonzero gap persisting two minutes (30s deferred settlement is allowed).Final review-round validation: 1,614 fast tests across 50 isolated files passed with the stricter 0.30s CPU guard, followed by 139 focused tests covering the final overflow/CAS and lifecycle-oracle changes. Re-ran the six 400,000-session calibration scenarios: zero false benches in each; detection median/p95 remains 20/48, 13/21, 8/8 at 40/60/100%. The earlier 2,268 count predates main's additional slow split; it is not the new fast-lane count. Generated runtime env regeneration and
--checkpass. PR metadata preflight passed all 38 checks.Final type check: zero errors. The final main merge includes #20340, with 100% allocation / cap 16 retained and runtime env regenerated and checked.