Skip to content

fix(stt): reconcile socket deaths at the serving boundary - #20350

Merged
Git-on-my-level merged 8 commits into
mainfrom
fix/stt-router-leg-death-accounting
Oct 2, 2026
Merged

Git-on-my-level merged 8 commits into
mainfrom
fix/stt-router-leg-death-accounting

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

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

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.

@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.

5 issues found across 9 files

Confidence score: 3/5

  • In live_chain.py, late censored validations can still update provider selection and failure metrics, potentially opening a circuit or triggering connect shedding. Keep post-departure validations out of selection and health accounting.
  • In live_session.py, a death raised during raw.finish() can escape owner-teardown reconciliation, leaving ignored-death metrics incomplete. Re-check is_connection_dead after the raw close.
  • In test_live_death_socket_accounting.py, the fake death is first observed only after client disconnect, so the test does not verify connected-client accounting. Observe the death before disconnecting.
  • In live_cost_health.py, values such as OFF can still record ignored-death metrics even though the router treats routing as disabled. Normalize STT_ROUTING_MODE consistently.
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:857">
P3: `application_state == DISCONNECTED` is also set by server-initiated `websocket.close()`, not just by client departure, so a death first observed after an owner close but before `_closing_for_health` is set is labeled boundary `client_gone` in the new `omi_stt_cost_routing_ignored_deaths_total` metric instead of `owner_teardown`. Since `close()` sets both states, keying this check on `client_state` alone (dropping the `application_state` criterion) keeps the client-departure detection without the owner-close conflation.</violation>

<violation number="2" location="backend/utils/stt/live_session.py:864">
P2: `finish()` can miss deaths raised by `raw.finish()`, so the new owner-teardown reconciliation never records the bounded ignored-death metric for those sockets. Re-read `is_connection_dead` after the raw close and pass that result to `_record_cost_outcome()`.</violation>
</file>

<file name="backend/tests/unit/test_live_death_socket_accounting.py">

<violation number="1" location="backend/tests/unit/test_live_death_socket_accounting.py:80">
P2: This test does not actually observe the death while the client is connected. `raw.die()` only latches the fake socket; the first leg observation happens after disconnecting the client, so `_record_cost_outcome` suppresses it and the `before + 1` assertion fails. Observe the leg before changing the client or owner state.</violation>
</file>

<file name="backend/utils/stt/live_chain.py">

<violation number="1" location="backend/utils/stt/live_chain.py:380">
P1: This flag suppresses fallback records but still lets a censored post-departure socket poison selection state and failure metrics. Repeated late validations can open a provider circuit, contribute to connect shedding, and inflate `LEG_ATTEMPTS` despite the intended selection-metric suppression; skip those selection-accounting updates whenever `observed.suppressed` is true.</violation>
</file>

<file name="backend/utils/stt/live_cost_health.py">

<violation number="1" location="backend/utils/stt/live_cost_health.py:207">
P3: Normalize `STT_ROUTING_MODE` before this comparison; with values such as `OFF`, the router treats routing as disabled but this method still records ignored-death metrics. Use the same case-insensitive handling as `live_health.mode()` and `routing_on()`.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread backend/utils/stt/live_chain.py Outdated
**capacity_fallback_kwargs(prior_capacity_subtype),
)
origin, prior_reason, prior_capacity_subtype = service.value, fallback_reason, capacity_subtype
prior_recordable = observed is None or not observed.suppressed

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1: This flag suppresses fallback records but still lets a censored post-departure socket poison selection state and failure metrics. Repeated late validations can open a provider circuit, contribute to connect shedding, and inflate LEG_ATTEMPTS despite the intended selection-metric suppression; skip those selection-accounting updates whenever observed.suppressed is true.

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_chain.py, line 380:

<comment>This flag suppresses fallback records but still lets a censored post-departure socket poison selection state and failure metrics. Repeated late validations can open a provider circuit, contribute to connect shedding, and inflate `LEG_ATTEMPTS` despite the intended selection-metric suppression; skip those selection-accounting updates whenever `observed.suppressed` is true.</comment>

<file context>
@@ -365,16 +367,17 @@ async def attempt(service: STTService, connect: Connect, target=None) -> tuple[S
+                    **capacity_fallback_kwargs(prior_capacity_subtype),
                 )
             origin, prior_reason, prior_capacity_subtype = service.value, fallback_reason, capacity_subtype
+            prior_recordable = observed is None or not observed.suppressed
             return None
         LEG_ATTEMPTS.labels(to_mode=service.value, outcome='success').inc()
</file context>

Comment thread backend/utils/stt/live_session.py Outdated
# First observation defines the serving boundary. Preserve evidence
# already observed with a connected client, but never discover a new
# provider failure retrospectively during client/owner teardown.
if dead and not self._cost_recorded and (self._closing_for_health or self._client_has_left()):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: finish() can miss deaths raised by raw.finish(), so the new owner-teardown reconciliation never records the bounded ignored-death metric for those sockets. Re-read is_connection_dead after the raw close and pass that result to _record_cost_outcome().

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 864:

<comment>`finish()` can miss deaths raised by `raw.finish()`, so the new owner-teardown reconciliation never records the bounded ignored-death metric for those sockets. Re-read `is_connection_dead` after the raw close and pass that result to `_record_cost_outcome()`.</comment>

<file context>
@@ -841,10 +843,53 @@ def finish(self) -> None:
+        # First observation defines the serving boundary. Preserve evidence
+        # already observed with a connected client, but never discover a new
+        # provider failure retrospectively during client/owner teardown.
+        if dead and not self._cost_recorded and (self._closing_for_health or self._client_has_left()):
+            self._cost_recorded = True
+            observed = None
</file context>

Comment thread backend/utils/stt/live_chain.py Resolved
Comment thread backend/utils/stt/live_cost_health.py Outdated
else CostObservation(False, generations, suppressed=True)
)
try:
if os.getenv('STT_ROUTING_MODE', 'off') != 'off' and any(entry.id == target for entry in registry()):

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: Normalize STT_ROUTING_MODE before this comparison; with values such as OFF, the router treats routing as disabled but this method still records ignored-death metrics. Use the same case-insensitive handling as live_health.mode() and routing_on().

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_cost_health.py, line 207:

<comment>Normalize `STT_ROUTING_MODE` before this comparison; with values such as `OFF`, the router treats routing as disabled but this method still records ignored-death metrics. Use the same case-insensitive handling as `live_health.mode()` and `routing_on()`.</comment>

<file context>
@@ -184,6 +189,31 @@ def prefer_recovery(self, target: str, language: str) -> None:
+            else CostObservation(False, generations, suppressed=True)
+        )
+        try:
+            if os.getenv('STT_ROUTING_MODE', 'off') != 'off' and any(entry.id == target for entry in registry()):
+                COST_IGNORED_DEATHS.labels(
+                    target=target,
</file context>
Suggested change
if os.getenv('STT_ROUTING_MODE', 'off') != 'off' and any(entry.id == target for entry in registry()):
if os.getenv('STT_ROUTING_MODE', 'off').strip().lower() != 'off' and any(entry.id == target for entry in registry()):

client = getattr(getattr(host, 'request', None), 'websocket', None)
return (
getattr(client, 'client_state', None) == WebSocketState.DISCONNECTED
or getattr(client, 'application_state', None) == WebSocketState.DISCONNECTED

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: application_state == DISCONNECTED is also set by server-initiated websocket.close(), not just by client departure, so a death first observed after an owner close but before _closing_for_health is set is labeled boundary client_gone in the new omi_stt_cost_routing_ignored_deaths_total metric instead of owner_teardown. Since close() sets both states, keying this check on client_state alone (dropping the application_state criterion) keeps the client-departure detection without the owner-close conflation.

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 857:

<comment>`application_state == DISCONNECTED` is also set by server-initiated `websocket.close()`, not just by client departure, so a death first observed after an owner close but before `_closing_for_health` is set is labeled boundary `client_gone` in the new `omi_stt_cost_routing_ignored_deaths_total` metric instead of `owner_teardown`. Since `close()` sets both states, keying this check on `client_state` alone (dropping the `application_state` criterion) keeps the client-departure detection without the owner-close conflation.</comment>

<file context>
@@ -841,10 +843,53 @@ def finish(self) -> None:
+        client = getattr(getattr(host, 'request', None), 'websocket', None)
+        return (
+            getattr(client, 'client_state', None) == WebSocketState.DISCONNECTED
+            or getattr(client, 'application_state', None) == WebSocketState.DISCONNECTED
+        )
+
</file context>

…ath-accounting

# Conflicts:
#	backend/docs/listen_pusher_pipeline.mdx
#	backend/docs/runbooks/live-stt-routing.md
#	backend/utils/stt/ARCHITECTURE.md
#	backend/utils/stt/live_chain.py
#	backend/utils/stt/live_cost_health.py
#	backend/utils/stt/live_session.py
@Git-on-my-level
Git-on-my-level merged commit 2e878f6 into main Oct 2, 2026
54 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/stt-router-leg-death-accounting branch October 2, 2026 17:03
Git-on-my-level added a commit that referenced this pull request Oct 2, 2026
…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. -->
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