Skip to content

fix(stt): reconcile router health with bounded socket death reasons - #20304

Merged
Git-on-my-level merged 5 commits into
mainfrom
fix/stt-router-bounded-death-reasons
Oct 2, 2026
Merged

Git-on-my-level merged 5 commits into
mainfrom
fix/stt-router-bounded-death-reasons

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

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

  • Free-text death_reason won over the cost path's connection-loss default; it was absent from the health allowlist. Unknown serving deaths now become connection_lost (or a direct send symptom send_failed), without parsing/exporting diagnostics.
  • The Modulate dead latch was published before its typed cause. A deterministic observer between diagnostic and typed-cause publication reproduces a censored typed serve error against the v4 source. Typed errors already present classify correctly; aggregates cannot prove which scheduling/earlier-observation path caused all six reported typed-error censored observations. Publish metadata first and latch one bounded cause shared with fallback. An early-client-teardown censor cannot hide a subsequent genuine death. Explicit VAD attribution retains the legacy terminal local circuit protection; it is censored only for fleet evidence.
  • A window cause must beat an observing send symptom. A fully published typed window cause already censored correctly in v4; the local reproduction demonstrates a bounded raw cause without the typed proxy being overridden by send_failed. The three production provider-failure observations could also include connect failures and cannot be uniquely attributed from reasonless aggregates. Window failures also publish metadata before their dead latch. Deadline/empty-streak/capacity cases remain censored through both a false send and a send exception.
  • Snapshot gauges defaulted to zero until the first complete refresh. Idle registry-wide refresh already exists from fix(stt): calibrate fleet health on provider failures #20260; never-refreshed now means NaN, finite old timestamp means stale. No production access was used, so individual pod identities cannot be diagnosed from aggregates.
  • Failed hops formerly replaced the source reason with the successor rejection, often other. Settlement now retains the source cause for recovered, degraded and exhausted hops. Account fallback labels remain quota / auth; the cost-health observation retains the precise bounded account token. Account serving protection is unchanged.

Metric label changes

  • omi_fallback_total account rejection labels remain quota for budget exhaustion and auth for account authentication rejection. Other bounded source causes retain their established labels, including modulate_serve_error, connection_lost, first_text_deadline, and capacity_full.
  • Mid-session exhausted / degraded hops now carry the source cause where they used to say other; this is intentional for reconciliation with router cost health. No monitoring alert rule keys on the omi_fallback_total reason label; 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_observation rejects 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.

Source Bounded reason Health class
Typed Modulate serve error modulate_serve_error provider_failure
Untyped transport death/free-text diagnostic connection_lost provider_failure
False/exceptional send without a socket-owned cause send_failed provider_failure
Typed timeout/5xx/429/rate-limit matching typed token provider_failure
Window deadline/empty/capacity first_text_deadline/empty_streak/capacity_full censored
Account rejection, rotation, idle timeout, VAD/client cause matching bounded token censored
Completed text / completed no-text text / no_text success / censored
Unknown connect configuration other censored

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.

Failure-Class: FC-typed-failure-collapsed-to-generic
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 issues found across 20 files

Confidence score: 4/5

  • In backend/utils/stt/live_session.py, when sending returns false, finish() runs before _dead is set and this branch never records _local_death_reason, so the resulting death reason can be None. Record the local reason before calling finish().
  • The heading in backend/docs/runbooks/live-stt-routing.md starts with the broken fragment “On requires,” which makes the go/no-go criterion hard to understand. Restore the intended heading about Modulate’s provider_failure counts.
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

Comment thread backend/utils/stt/live_failure.py Resolved
Comment thread backend/utils/observability/fallback.py Resolved
Comment thread backend/utils/stt/live_cost_health.py Resolved
Comment thread backend/utils/stt/live_session.py Outdated
@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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>

Comment on lines +175 to +176
**On requires Modulate's `provider_failure` counts to track its attributable
mid-session failovers by reason.** `modulate-velma-2` maps to fallback

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
Suggested change
**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

@Git-on-my-level
Git-on-my-level merged commit 6a26acc into main Oct 2, 2026
53 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/stt-router-bounded-death-reasons branch October 2, 2026 08:31
Git-on-my-level added a commit that referenced this pull request Oct 2, 2026
#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)
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