Repository navigation
fix(stt): reconcile router health with bounded socket death reasons - #20304
Conversation
Failure-Class: FC-typed-failure-collapsed-to-generic
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
There was a problem hiding this comment.
2 issues found across 20 files
Confidence score: 4/5
- In
backend/utils/stt/live_session.py, when sending returns false,finish()runs before_deadis set and this branch never records_local_death_reason, so the resulting death reason can beNone. Record the local reason before callingfinish(). - The heading in
backend/docs/runbooks/live-stt-routing.mdstarts with the broken fragment “On requires,” which makes the go/no-go criterion hard to understand. Restore the intended heading about Modulate’sprovider_failurecounts.
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_session.py">
<violation number="1" location="backend/utils/stt/live_session.py:560">
P3: The send-return-false path can lose its local cause: `finish()` runs before `_dead` is set, and this branch never populates `_local_death_reason`, so `death_reason` and `typed_death_reason` become `None` when the raw socket returns `False` without metadata. Set `_local_death_reason = 'send_failed'` before recording/finishing in both send-failure branches, or preserve an equivalent bounded fallback in these properties.</violation>
</file>
<file name="backend/docs/runbooks/live-stt-routing.md">
<violation number="1" location="backend/docs/runbooks/live-stt-routing.md:175">
P3: The bolded heading starts with a broken fragment "**On requires...". The PR description and the surrounding go/no-go section indicate this should read "Go/no-go requires Modulate's `provider_failure` counts to track attributable mid-session failovers by reason." As written, the sentence is ungrammatical and the runbook's key reconciliation requirement is unclear to on-call readers.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| @property | ||
| def death_reason(self) -> str | None: | ||
| return self._replay_failure_reason or ('vad_failed' if self._dead else self.raw.death_reason) | ||
| return self._replay_failure_reason or self._local_death_reason or self.raw.death_reason |
There was a problem hiding this comment.
P3: The send-return-false path can lose its local cause: finish() runs before _dead is set, and this branch never populates _local_death_reason, so death_reason and typed_death_reason become None when the raw socket returns False without metadata. Set _local_death_reason = 'send_failed' before recording/finishing in both send-failure branches, or preserve an equivalent bounded fallback in these properties.
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_session.py, line 560:
<comment>The send-return-false path can lose its local cause: `finish()` runs before `_dead` is set, and this branch never populates `_local_death_reason`, so `death_reason` and `typed_death_reason` become `None` when the raw socket returns `False` without metadata. Set `_local_death_reason = 'send_failed'` before recording/finishing in both send-failure branches, or preserve an equivalent bounded fallback in these properties.</comment>
<file context>
@@ -554,11 +557,16 @@ def _release_open_gauge(self) -> None:
@property
def death_reason(self) -> str | None:
- return self._replay_failure_reason or ('vad_failed' if self._dead else self.raw.death_reason)
+ return self._replay_failure_reason or self._local_death_reason or self.raw.death_reason
@property
</file context>
| **On requires Modulate's `provider_failure` counts to track its attributable | ||
| mid-session failovers by reason.** `modulate-velma-2` maps to fallback |
There was a problem hiding this comment.
P3: The bolded heading starts with a broken fragment "**On requires...". The PR description and the surrounding go/no-go section indicate this should read "Go/no-go requires Modulate's provider_failure counts to track attributable mid-session failovers by reason." As written, the sentence is ungrammatical and the runbook's key reconciliation requirement is unclear to on-call readers.
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/docs/runbooks/live-stt-routing.md, line 175:
<comment>The bolded heading starts with a broken fragment "**On requires...". The PR description and the surrounding go/no-go section indicate this should read "Go/no-go requires Modulate's `provider_failure` counts to track attributable mid-session failovers by reason." As written, the sentence is ungrammatical and the runbook's key reconciliation requirement is unclear to on-call readers.</comment>
<file context>
@@ -162,6 +164,39 @@ sum by (target) (rate(omi_stt_cost_routing_observations_total{job="backend-liste
+count(omi_stt_cost_routing_snapshot_timestamp_seconds{job="backend-listen-metrics"} != omi_stt_cost_routing_snapshot_timestamp_seconds{job="backend-listen-metrics"}) or vector(0)
+```
+
+**On requires Modulate's `provider_failure` counts to track its attributable
+mid-session failovers by reason.** `modulate-velma-2` maps to fallback
+`from_mode="modulate"`; `parakeet-window` maps to `parakeet`. Fallbacks use family
</file context>
| **On requires Modulate's `provider_failure` counts to track its attributable | |
| mid-session failovers by reason.** `modulate-velma-2` maps to fallback | |
| **Go/no-go requires Modulate's `provider_failure` counts to track its attributable | |
| mid-session failovers by reason.** `modulate-velma-2` maps to fallback |
#20348) ## Summary Fix static/shadow live STT recovery after a local full/open window: continue to an eligible non-account rescue provider, and latch terminal recovery failure so audio/monitor races cannot repeat rebuilds. No cost-router implementation or rollout defaults change. Failure-Class: none ## Product invariants affected none ## Evidence and mechanism - The supplied 35-event burst is not a count of distinct sessions. Read-only Prometheus samples on the affected pod show chain exhaustion 0 → 35 but terminal-session failures only 2 → 4 over 13:46:30–13:49Z. A deterministic test reproduces 35 competing rebuild calls against one receiver before the fix; distinct failed-provider cardinality is not an attempt budget. - Timestamp-only logging queries find all 35 rebuild errors within 0.64s (13:47:35.490–13:47:36.131Z), immediately after a pending Soniox→Modulate connection_lost hop settles degraded. Soniox's local selection/account gauges are both zero and its connect-success count stays 30: it was not dialed during the burst. Its permanent session exclusion after that earlier transport loss explains the absence of Soniox skip/attempt events; the aggregate evidence does not require 35 independent sessions. Add one bounded re-entry of that already-used Soniox leg when the circuit is closed, never after account/connect rejection, and keep untried configured Deepgram ahead of re-entry. - A separate reproduced corner (not the production Soniox circuit state): Soniox selection benches are not proof it cannot accept a new stream. The old last-resort suffix required every callback's circuit to be benched, including an already-excluded Modulate callback. A closed circuit for that failed source suppressed rescue. A window capacity refusal also set `attempted`, suppressing the same suffix. The historical configured-chain functions on 6a26acc, afa7800 and 0ba6edb all exhaust the same open-window/open-Soniox/failed-Modulate input. This is not introduced by #20304 or #20332. - `reason=capacity_full` on a source Modulate hop is the latched source cause, not evidence the proposed Parakeet successor was dialed. Managed replacement replay-ring pressure can produce that cause; the selection event with circuit_open is consistent with no actual connection in that rebuild. - The affected live-session exhausted counter first appears at 35, then stays 35: Prometheus increase cannot recover increments before its first sample. The helper increments and logs identical labels. Initialize bounded exhausted STT children at zero to make subsequent first bursts observable. ## Changes - Exclude already-failed providers from the local all-benched decision. - Check actual local window admission before socket/VAD construction, counting these refused selections in the existing admission-overflow metric; respect existing five-second target capacity cooldown in shadow serving, without enabling the cost router. - Try each remaining non-TDT rescue provider once after an open/refused window; never bypass account cooldown, failed providers, known capacity or TDT shedding. Preserve the half-open probe count; competing rescue handshakes wait at most twelve seconds in total for a slot instead of failing immediately. At 300ms liveness grace, 35 otherwise healthy serialized handshakes take about 10.5s, excluding actual provider connect latency. - Count actual rebuild attempts, at most three on managed sessions and two on legacy sessions. A single healthy Soniox re-entry consumes that same budget; the failed window never re-arms. - Latch failed rebuilds under the receiver lock, and send unrecoverable ring pressure through the ordinary idempotent terminal-close path. - Preserve source numeric/capacity diagnostics when settling a failed hop. Replay snapshots and timestamp fencing remain on the existing path. ## Verification Direct focused pytest suites (TMPDIR inside the worktree): new capacity/failover suite, configured-chain suite, session-failover suite, Parakeet replacement/replay suite, cost-router suite and resilient-stream suite. Tests include 35 concurrent deaths with a real full eight-slot admission and an in-flight recovery handshake, exact replay of a pending window-origin span, terminal ring-pressure closure once, shadow capacity cooldown, occupied/account probe limits, historical reproductions and zero-baseline telemetry. Each test is below 0.5s. Final run after merging current main: 236 passed in 5.52s; slowest test 0.32s. Exact command (from backend): `TMPDIR=$PWD/../.pytest-tmp .venv/bin/python -m pytest -q -p no:cacheprovider tests/unit/test_modulate_capacity_failover.py tests/unit/test_live_stt_chain.py tests/unit/test_stt_session_failover.py tests/unit/test_parakeet_failover_exhausted.py tests/unit/test_live_cost_router.py tests/unit/test_live_stt_resilient_stream.py --durations=8`. CI found and this revision fixes a helper policy mismatch: replacement selection now consumes the receiver's managed-chain decision, preserving the partial-replay retry budget. The other failed shard is an unrelated main regression: `test_rate_limiting::TestRouterWiring::test_sensitive_read_page_caps` still expects the old developer conversation-list limit after #13955 raised it. Those source and test files are unchanged by this PR. Terminal CI at `b9d6eace43f4ca293fef4f5cb7e1092af572817e`: 29 passed, 23 skipped, two failed checks (backend shard 3 and its aggregate). The only failed test is the unchanged main regression `test_rate_limiting::TestRouterWiring::test_sensitive_read_page_caps`. Listen/Pusher Stack Gauntlet, Hermetic Backend E2E, static checks and the other three shards passed. `make preflight` passes all 31 selected gates. Backend type checking reports zero errors (existing warning inventory remains). No provider/network/content is used by tests. Production reads were bounded aggregate metric samples and timestamp-only logging queries; no uid, transcript or audio was read. ## Not covered The aggregate evidence cannot identify the exact number of WebSocket sessions without session identifiers; no identifiers were retrieved. A session that never entered the window replay path still lacks a cross-provider replay ring; this fixes chain continuation for it but does not add capture retention. Genuine account exhaustion, no eligible provider, confirmed fleet outage, and an occupied rescue slot lasting beyond the bound remain terminal. No merge or deploy is included. ## After deploy Watch chain-exhausted vs terminal-session counters, recovered Modulate→Soniox hops, local window admission overflow, fallback exhausted series and Soniox connect error/first-text latency. Check that exhaustion bursts no longer multiply a single terminal incident; compare headline transcript success across window/control. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Live shadow reported censored Modulate deaths and window provider failures alongside deadline failovers; v4 had no reason label to join those aggregates. This shares one bounded reason normalizer between health and source-leg fallback telemetry, preserves socket causes before send symptoms, and starts fresh v5 evidence. Serving selection in shadow, runtime defaults (shadow/on-percent zero), provider protocols, ramps and gate thresholds stay unchanged.
Root causes and fix
death_reasonwon over the cost path's connection-loss default; it was absent from the health allowlist. Unknown serving deaths now becomeconnection_lost(or a direct send symptomsend_failed), without parsing/exporting diagnostics.other. Settlement now retains the source cause for recovered, degraded and exhausted hops. Account fallback labels remainquota/auth; the cost-health observation retains the precise bounded account token. Account serving protection is unchanged.Metric label changes
omi_fallback_totalaccount rejection labels remainquotafor budget exhaustion andauthfor account authentication rejection. Other bounded source causes retain their established labels, includingmodulate_serve_error,connection_lost,first_text_deadline, andcapacity_full.exhausted/degradedhops now carry the source cause where they used to sayother; this is intentional for reconciliation with router cost health. No monitoring alert rule keys on theomi_fallback_totalreasonlabel; those queries filter by component, outcome, or destination mode.Bounded normalization
27 reason tokens, at most 16 registry target IDs, three observation outcomes. Socket typed cause precedes bounded raw cause, then send/monitor symptom. Shared fallback vocabulary admits the same tokens.
provider_observationrejects unbounded reason strings. Observation labels are target/outcome/reason; target/reason series are initialized before traffic. No UID, content or free-text diagnostic is emitted.Redis prefix is
omi:live-stt:cost-v5; v4 evidence is not migrated or reinterpreted. Keep the fresh namespace in shadow until it has a full warm traffic/language cycle.Validation
LiveLegSocket tests exercise typed/untyped monitor deaths, false and exceptional sends, actual Modulate/window metadata publication, early teardown versus actual death, normal close, account/idle/rotation, idempotence, and both recovered/exhausted fallback settlement. Existing receiver replay tests now assert source attribution without changing the serving chain.
Direct worktree-TMPDIR focused suites: 1,419 passed (9 warnings; 69.09s), including source-hop reconciliation and late-rejection session tests; slowest test 0.61s. Final type check: zero errors (existing warnings remain). Async blocker scan: zero selected findings. Four local source-level v4 reproductions passed and are not committed. Final repository preflight: 31 checks passed. Normal push hooks passed, including type checking, selected guarded unit tests, source closure, pinned formatting and supplied-body validation. CI has no failed or pending checks on exact head 162db67; unit shard 3's passing tests first exceeded the wall budget (620s/600s), then passed the unchanged budget on retry.
Both listen and push-to-talk create source-attributed hops from the shared socket helper. Other hop constructors require an explicit reason. A connect fallback may change the successor but preserves the source cause, and managed socket death properties expose the same latched bounded reason. Rejection tests continue to prevent false recovery. Runbook and architecture describe v5, reason reconciliation queries, unknown/stale snapshots, and the requirement that Modulate provider failures track attributable mid-session failovers before enabling on. Account/endpoint/settlement timing differences are documented; no instantaneous exact equality claim.
Product invariants affected
none — no locked runtime/configuration paths or client wire models changed. Shadow/on-percent zero and Parakeet cohort assignment remain unchanged.
Failure-Class: FC-typed-failure-collapsed-to-generic
This is the existing typed-failure provenance class: the terminal observer must preserve the already-typed source cause. This repairs the provider-death attribution contract with a shared normalizer and reusable serving-leg reconciliation tests. No .github files changed. No merge or deployment.