Skip to content

fix(stt): bound exhaustion retries and preserve the Soniox rescue path - #20348

Merged
Git-on-my-level merged 9 commits into
mainfrom
fix/modulate-window-capacity-failover
Oct 2, 2026
Merged

Git-on-my-level merged 9 commits into
mainfrom
fix/modulate-window-capacity-failover

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

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 fix(stt): reconcile router health with bounded socket death reasons #20304 or fix(stt): count accepted provider deaths without a speech gate #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

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

7 issues found and verified against the latest diff

Confidence score: 2/5

  • live_recovery.py can keep the Deepgram failure guard active when a fallback model is configured, preventing Soniox from re-entering. Use the canonical Deepgram provider key in the guard.
  • test_modulate_capacity_failover.py fails before testing the regression because its historical commit references cannot be resolved. Make those cases work with history available in the repository.
  • parakeet_window.py can raise on a non-integer cap before routing reaches rescue providers. Parse invalid cap values safely so the configured fallback chain can continue.
  • live_chain.py can spend up to the shared 12-second deadline polling when a half-open circuit has no probe budget, delaying connect. Avoid waiting out the full deadline for an exhausted probe.
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/docs/operational/windowed-live-stt.md">

<violation number="1" location="backend/docs/operational/windowed-live-stt.md:399">
P3: This wording also covers local admission refusals, but those skip before the code sets the target cooldown. Limit the claim to provider-side capacity rejections, or add cooldown handling for admission skips.</violation>
</file>

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

<violation number="1" location="backend/utils/stt/live_recovery.py:21">
P1: `_stt_failed_providers` records Deepgram as `deepgram_cloud`, so this guard remains true after Deepgram fails whenever its fallback model is configured; Soniox never gets its promised re-entry. Check the canonical Deepgram provider token instead.</violation>
</file>

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

<violation number="1" location="backend/tests/unit/test_modulate_capacity_failover.py:81">
P1: The historical cases fail before exercising the regression: `git show` cannot resolve `6a26acc` or `afa7800` in the available repository history, and `check=True` raises `CalledProcessError`. Store these historical sources as test fixtures or avoid depending on unavailable commits.</violation>
</file>

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

<violation number="1" location="backend/utils/stt/parakeet_window.py:236">
P2: A non-integer cap raises `ValueError` before `attempt()` can handle the failure, aborting configured routing instead of reaching rescue providers; parse invalid values safely here.</violation>

<violation number="2" location="backend/utils/stt/parakeet_window.py:238">
P2: When this check returns false, routing skips `acquire()` and its overflow increment, undercounting capacity refusals in the documented saturation metric; record the overflow here.</violation>
</file>

<file name="backend/docs/listen_pusher_pipeline.mdx">

<violation number="1" location="backend/docs/listen_pusher_pipeline.mdx:768">
P3: This line reads as if the full-window admission gate and the five-second capacity cooldown are bypassed in static/shadow serving, which is the opposite of what the PR does. In `live_chain.py` these gates were canary-gated before (`if canary and capacity_target is not None and not capacity_available(...)`, plus canary-only `capacity_targets` population) and are now applied unconditionally, and the new window admission check (`window.admission.available()`) runs for every path. The sibling doc in this same PR says the opposite correctly: "Full local window admission is checked before constructing the window socket, including static/shadow serving." Reword so operators don't conclude static/shadow traffic bypasses these gates.</violation>
</file>

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

<violation number="1" location="backend/utils/stt/live_chain.py:513">
P2: `_allow_rescue_probe` spins in a 10 ms poll until the shared 12 s deadline, and the deadline is computed once for the whole candidate loop. A single half-open circuit with an exhausted probe budget now makes `connect_configured_chain` block up to 12 s before the next candidate is even tried — during a mid-session rebuild this stall is serialized under `_stt_failover_lock` while audio keeps buffering, and the first (typically primary) leg can burn the entire rescue window for immediately-available fallbacks. Give each candidate its own short deadline slice (or poll at a coarser interval) so an in-flight recovery handshake cannot starve the rest of the chain.</violation>
</file>

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

Re-trigger cubic

or 'soniox' in receiver._stt_rescue_retries
or receiver._stt_failed_reasons.get('soniox') not in {'connection_lost', 'send_failed'}
or st._circuit_for_primary(st.STTService.soniox).state != 'closed' # type: ignore[reportPrivateUsage] # shared circuit owner
or ('deepgram' not in receiver._stt_failed_providers and st.deepgram_fallback_model(receiver.host.stt_language))

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: _stt_failed_providers records Deepgram as deepgram_cloud, so this guard remains true after Deepgram fails whenever its fallback model is configured; Soniox never gets its promised re-entry. Check the canonical Deepgram provider token instead.

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_recovery.py, line 21:

<comment>`_stt_failed_providers` records Deepgram as `deepgram_cloud`, so this guard remains true after Deepgram fails whenever its fallback model is configured; Soniox never gets its promised re-entry. Check the canonical Deepgram provider token instead.</comment>

<file context>
@@ -0,0 +1,55 @@
+        or 'soniox' in receiver._stt_rescue_retries
+        or receiver._stt_failed_reasons.get('soniox') not in {'connection_lost', 'send_failed'}
+        or st._circuit_for_primary(st.STTService.soniox).state != 'closed'  # type: ignore[reportPrivateUsage] # shared circuit owner
+        or ('deepgram' not in receiver._stt_failed_providers and st.deepgram_fallback_model(receiver.host.stt_language))
+    ):
+        return
</file context>

@pytest.mark.parametrize('previous_soniox', [False, True])
async def test_historical_open_window_and_soniox_exhaust_with_failed_modulate(revision, previous_soniox):
source = subprocess.run(
['git', 'show', f'{revision}:backend/utils/stt/live_chain.py'],

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: The historical cases fail before exercising the regression: git show cannot resolve 6a26acc or afa7800 in the available repository history, and check=True raises CalledProcessError. Store these historical sources as test fixtures or avoid depending on unavailable commits.

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/tests/unit/test_modulate_capacity_failover.py, line 81:

<comment>The historical cases fail before exercising the regression: `git show` cannot resolve `6a26acc` or `afa7800` in the available repository history, and `check=True` raises `CalledProcessError`. Store these historical sources as test fixtures or avoid depending on unavailable commits.</comment>

<file context>
@@ -0,0 +1,316 @@
[email protected]('previous_soniox', [False, True])
+async def test_historical_open_window_and_soniox_exhaust_with_failed_modulate(revision, previous_soniox):
+    source = subprocess.run(
+        ['git', 'show', f'{revision}:backend/utils/stt/live_chain.py'],
+        capture_output=True,
+        text=True,
</file context>

self._lock = threading.Lock()

def available(self) -> bool:
cap = max(0, int(os.getenv('PARAKEET_WINDOW_MAX_SESSIONS', '1')))

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: A non-integer cap raises ValueError before attempt() can handle the failure, aborting configured routing instead of reaching rescue providers; parse invalid values safely here.

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/parakeet_window.py, line 236:

<comment>A non-integer cap raises `ValueError` before `attempt()` can handle the failure, aborting configured routing instead of reaching rescue providers; parse invalid values safely here.</comment>

<file context>
@@ -232,6 +232,11 @@ def __init__(self) -> None:
         self._lock = threading.Lock()
 
+    def available(self) -> bool:
+        cap = max(0, int(os.getenv('PARAKEET_WINDOW_MAX_SESSIONS', '1')))
+        with self._lock:
+            return self.active < cap
</file context>
Suggested change
cap = max(0, int(os.getenv('PARAKEET_WINDOW_MAX_SESSIONS', '1')))
try:
cap = max(0, int(os.getenv('PARAKEET_WINDOW_MAX_SESSIONS', '1')))
except ValueError:
cap = 1

def available(self) -> bool:
cap = max(0, int(os.getenv('PARAKEET_WINDOW_MAX_SESSIONS', '1')))
with self._lock:
return self.active < cap

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: When this check returns false, routing skips acquire() and its overflow increment, undercounting capacity refusals in the documented saturation metric; record the overflow here.

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/parakeet_window.py, line 238:

<comment>When this check returns false, routing skips `acquire()` and its overflow increment, undercounting capacity refusals in the documented saturation metric; record the overflow here.</comment>

<file context>
@@ -232,6 +232,11 @@ def __init__(self) -> None:
+    def available(self) -> bool:
+        cap = max(0, int(os.getenv('PARAKEET_WINDOW_MAX_SESSIONS', '1')))
+        with self._lock:
+            return self.active < cap
+
     def acquire(self) -> Callable[[], None]:
</file context>
Suggested change
return self.active < cap
available = self.active < cap
WINDOW_CAP.set(cap)
if not available:
WINDOW_ADMISSION.labels(outcome='overflow').inc()
return available

# an earlier leg already attempted admission. Failed/account/cooled legs
# stay excluded; force only relaxes a non-account selection bench.
if not active:
rescue_deadline = asyncio.get_running_loop().time() + 12.0

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: _allow_rescue_probe spins in a 10 ms poll until the shared 12 s deadline, and the deadline is computed once for the whole candidate loop. A single half-open circuit with an exhausted probe budget now makes connect_configured_chain block up to 12 s before the next candidate is even tried — during a mid-session rebuild this stall is serialized under _stt_failover_lock while audio keeps buffering, and the first (typically primary) leg can burn the entire rescue window for immediately-available fallbacks. Give each candidate its own short deadline slice (or poll at a coarser interval) so an in-flight recovery handshake cannot starve the rest of the chain.

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

<comment>`_allow_rescue_probe` spins in a 10 ms poll until the shared 12 s deadline, and the deadline is computed once for the whole candidate loop. A single half-open circuit with an exhausted probe budget now makes `connect_configured_chain` block up to 12 s before the next candidate is even tried — during a mid-session rebuild this stall is serialized under `_stt_failover_lock` while audio keeps buffering, and the first (typically primary) leg can burn the entire rescue window for immediately-available fallbacks. Give each candidate its own short deadline slice (or poll at a coarser interval) so an in-flight recovery handshake cannot starve the rest of the chain.</comment>

<file context>
@@ -468,26 +504,12 @@ async def attempt(service: STTService, connect: Connect, target=None) -> tuple[S
+    # an earlier leg already attempted admission. Failed/account/cooled legs
+    # stay excluded; force only relaxes a non-account selection bench.
+    if not active:
+        rescue_deadline = asyncio.get_running_loop().time() + 12.0
         for service in configured_candidates:
             connect = callbacks.get(service)
</file context>

hops across four providers.

Full local window admission is checked before constructing the window socket,
including static/shadow serving. Capacity refusals also engage the existing

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: This wording also covers local admission refusals, but those skip before the code sets the target cooldown. Limit the claim to provider-side capacity rejections, or add cooldown handling for admission skips.

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/operational/windowed-live-stt.md, line 399:

<comment>This wording also covers local admission refusals, but those skip before the code sets the target cooldown. Limit the claim to provider-side capacity rejections, or add cooldown handling for admission skips.</comment>

<file context>
@@ -392,6 +395,15 @@ non-account bench. The flag-enabled preflight therefore leaves admission to the
 hops across four providers.
 
+Full local window admission is checked before constructing the window socket,
+including static/shadow serving. Capacity refusals also engage the existing
+five-second target cooldown in shadow. A refused window does not consume a
+remaining non-account rescue provider's attempt. That rescue may relax its
</file context>
Suggested change
including static/shadow serving. Capacity refusals also engage the existing
Provider-side `capacity_full` rejections also engage the existing

emitting `stt_failed` and closing the client WebSocket with 1011; recovery then
requires a client reconnect. Configured and circuit-open candidate skipping
continues to be enforced by the connector.
A process-local full window and its five-second capacity cooldown are skipped

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: This line reads as if the full-window admission gate and the five-second capacity cooldown are bypassed in static/shadow serving, which is the opposite of what the PR does. In live_chain.py these gates were canary-gated before (if canary and capacity_target is not None and not capacity_available(...), plus canary-only capacity_targets population) and are now applied unconditionally, and the new window admission check (window.admission.available()) runs for every path. The sibling doc in this same PR says the opposite correctly: "Full local window admission is checked before constructing the window socket, including static/shadow serving." Reword so operators don't conclude static/shadow traffic bypasses these gates.

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/listen_pusher_pipeline.mdx, line 768:

<comment>This line reads as if the full-window admission gate and the five-second capacity cooldown are bypassed in static/shadow serving, which is the opposite of what the PR does. In `live_chain.py` these gates were canary-gated before (`if canary and capacity_target is not None and not capacity_available(...)`, plus canary-only `capacity_targets` population) and are now applied unconditionally, and the new window admission check (`window.admission.available()`) runs for every path. The sibling doc in this same PR says the opposite correctly: "Full local window admission is checked before constructing the window socket, including static/shadow serving." Reword so operators don't conclude static/shadow traffic bypasses these gates.</comment>

<file context>
@@ -765,6 +765,24 @@ Only an actual failure to find a serving replacement terminates live STT,
 emitting `stt_failed` and closing the client WebSocket with 1011; recovery then
 requires a client reconnect. Configured and circuit-open candidate skipping
 continues to be enforced by the connector.
+A process-local full window and its five-second capacity cooldown are skipped
+in static/shadow serving as well. A refused or circuit-open Parakeet primary
+cannot block the remaining non-account rescue leg. Terminal rebuild failure
</file context>
Suggested change
A process-local full window and its five-second capacity cooldown are skipped
A process-local full window and its five-second capacity cooldown are no longer skipped

@Git-on-my-level
Git-on-my-level merged commit 85530e7 into main Oct 2, 2026
51 of 53 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/modulate-window-capacity-failover branch October 2, 2026 16:06
Git-on-my-level added a commit that referenced this pull request Oct 2, 2026
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.
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