Repository navigation
fix(stt): bound exhaustion retries and preserve the Soniox rescue path - #20348
Conversation
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
There was a problem hiding this comment.
7 issues found and verified against the latest diff
Confidence score: 2/5
live_recovery.pycan 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.pyfails before testing the regression because its historical commit references cannot be resolved. Make those cases work with history available in the repository.parakeet_window.pycan 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.pycan spend up to the shared 12-second deadline polling when a half-open circuit has no probe budget, delayingconnect. 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)) |
There was a problem hiding this comment.
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'], |
There was a problem hiding this comment.
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'))) |
There was a problem hiding this comment.
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>
| 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 |
There was a problem hiding this comment.
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>
| 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 |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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>
| 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 |
There was a problem hiding this comment.
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>
| 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 |
…apacity-failover # Conflicts: # backend/utils/stt/live_chain.py
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.
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
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_fullon 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.Changes
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_capsstill 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 regressiontest_rate_limiting::TestRouterWiring::test_sensitive_read_page_caps. Listen/Pusher Stack Gauntlet, Hermetic Backend E2E, static checks and the other three shards passed.make preflightpasses 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