Repository navigation
fix(parakeet): release abandoned live queue capacity - #20433
Conversation
Failure-Class: FC-shared-batch-pressure-blocks-live Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
Luna round-2 review: all four functional checks pass (queue_timeout → capacity_full with no circuit strike; unmarked/unknown 503 stays provider_5xx; real failover path tested; listen-first rollout order compatible). Its remaining finding is that the 🤖 Generated with Claude Code |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
6 issues found across 8 files
Confidence score: 3/5
backend/parakeet/main.pyrestarts the request budget after multipart upload, so a slow upload can leave a live request queued past its overall timeout. Start the deadline when the request arrives.backend/utils/stt/parakeet_window.pytreats a timeout waiting for the shared semaphore as a provider timeout, which can mark the Parakeet pool unhealthy even though no provider call failed. Keep queue-admission timeouts out of provider failure accounting.backend/parakeet/main.pyupdates the queue gauge only aftersubmit()finishes, so/metricsstays stale while requests wait. Update it on queue admission and removal.- The tests miss two relevant cases:
test_parakeet_window_live.pydoes not verify body-onlyqueue_timeouthandling, andtest_parakeet_batch_engine.pydoes not actually reach a flush blocked on the semaphore. Add coverage for those paths.
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/tests/unit/test_parakeet_window_live.py">
<violation number="1" location="backend/tests/unit/test_parakeet_window_live.py:462">
P2: The unmarked 503 uses `Client`’s default `{"text":"hello"}` body, so body-only `error="queue_timeout"` is never tested without the marker header. Add that negative case and assert `provider_5xx` to lock the exact status/header contract.</violation>
</file>
<file name="backend/parakeet/main.py">
<violation number="1" location="backend/parakeet/main.py:230">
P2: This restarts the caller's remaining budget after the multipart upload, so a slow upload can leave an abandoned live request queued beyond its overall timeout. Start the deadline from request receipt or otherwise account for upload time.</violation>
<violation number="2" location="backend/parakeet/main.py:304">
P2: This updates the gauge only after `batch_engine.submit()` finishes, so queued requests leave `/metrics` at its previous value throughout the wait. Update it on queue admission and removal so Prometheus reflects the current backlog.</violation>
</file>
<file name="backend/utils/stt/parakeet_window.py">
<violation number="1" location="backend/utils/stt/parakeet_window.py:1122">
P2: Budget exhausted at shared-STT-semaphore admission raises a bare `TimeoutError`, which `_post_and_parse` classifies as a provider timeout and records a serve failure on the Parakeet pool circuit — even though the request never reached Parakeet. The PR removes circuit strikes for the analogous queue-timeout condition; use the same treatment here (for example raise a session-local exception handled without `record_serve_failure`, like `QueueTimeout`), keeping `fail('timeout')` without striking the circuit.</violation>
</file>
<file name="backend/tests/unit/test_parakeet_batch_engine.py">
<violation number="1" location="backend/tests/unit/test_parakeet_batch_engine.py:1159">
P2: This setup never starts a flush waiting on the semaphore: three queued requests do not reach the batch size of four, and the flush loop skips dispatch while the blocker is in flight. Set `max_batch_size=3` so the third queued request starts the waiter this regression test is meant to cover.</violation>
</file>
<file name="backend/docs/listen_pusher_pipeline.mdx">
<violation number="1" location="backend/docs/listen_pusher_pipeline.mdx:732">
P2: This queue deadline is not enforced in the supported NIM mode: that mode skips `BatchEngine` and transcribes directly. Qualify this behavior to the batched Nemo path.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| @pytest.mark.parametrize( | ||
| 'status, headers', | ||
| [ | ||
| (503, None), |
There was a problem hiding this comment.
P2: The unmarked 503 uses Client’s default {"text":"hello"} body, so body-only error="queue_timeout" is never tested without the marker header. Add that negative case and assert provider_5xx to lock the exact status/header contract.
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_parakeet_window_live.py, line 462:
<comment>The unmarked 503 uses `Client`’s default `{"text":"hello"}` body, so body-only `error="queue_timeout"` is never tested without the marker header. Add that negative case and assert `provider_5xx` to lock the exact status/header contract.</comment>
<file context>
@@ -347,6 +401,127 @@ async def test_post_failure_benches_leg_and_releases_slot(monkeypatch, fault):
[email protected](
+ 'status, headers',
+ [
+ (503, None),
+ (503, {'X-Omi-STT-Error': 'bogus'}),
+ (500, {'X-Omi-STT-Error': 'queue_timeout'}),
</file context>
| ACTIVE_BATCH.dec() | ||
| if batch_engine is None: | ||
| if batch_engine is not None: | ||
| PENDING_REQUESTS.set(batch_engine.pressure_snapshot()['pending_requests']) |
There was a problem hiding this comment.
P2: This updates the gauge only after batch_engine.submit() finishes, so queued requests leave /metrics at its previous value throughout the wait. Update it on queue admission and removal so Prometheus reflects the current backlog.
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/parakeet/main.py, line 304:
<comment>This updates the gauge only after `batch_engine.submit()` finishes, so queued requests leave `/metrics` at its previous value throughout the wait. Update it on queue admission and removal so Prometheus reflects the current backlog.</comment>
<file context>
@@ -259,7 +300,9 @@ async def transcribe(request: Request, file: UploadFile = File(...)) -> JSONResp
ACTIVE_BATCH.dec()
- if batch_engine is None:
+ if batch_engine is not None:
+ PENDING_REQUESTS.set(batch_engine.pressure_snapshot()['pending_requests'])
+ if not submit_called and not write_orphaned and (file_written or batch_engine is None):
await loop.run_in_executor(_io_pool, _remove_file, file_path)
</file context>
| REQUESTS_TOTAL.labels(endpoint="v1_transcribe", status="error").inc() | ||
| return JSONResponse(status_code=400, content={"detail": f"Invalid {_TIMEOUT_HEADER} budget"}) | ||
| budget = min(budget, supplied) | ||
| queue_deadline = request_start + budget |
There was a problem hiding this comment.
P2: This restarts the caller's remaining budget after the multipart upload, so a slow upload can leave an abandoned live request queued beyond its overall timeout. Start the deadline from request receipt or otherwise account for upload time.
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/parakeet/main.py, line 230:
<comment>This restarts the caller's remaining budget after the multipart upload, so a slow upload can leave an abandoned live request queued beyond its overall timeout. Start the deadline from request receipt or otherwise account for upload time.</comment>
<file context>
@@ -204,19 +206,38 @@ def _remove_file(path: str) -> None:
+ REQUESTS_TOTAL.labels(endpoint="v1_transcribe", status="error").inc()
+ return JSONResponse(status_code=400, content={"detail": f"Invalid {_TIMEOUT_HEADER} budget"})
+ budget = min(budget, supplied)
+ queue_deadline = request_start + budget
upload_id = str(uuid.uuid4())
file_path = f"_temp/{upload_id}_{file.filename}"
</file context>
| ) | ||
| remaining = math.floor(remaining * 1000) / 1000 | ||
| if remaining <= 0: | ||
| raise TimeoutError('post budget exhausted at semaphore admission') |
There was a problem hiding this comment.
P2: Budget exhausted at shared-STT-semaphore admission raises a bare TimeoutError, which _post_and_parse classifies as a provider timeout and records a serve failure on the Parakeet pool circuit — even though the request never reached Parakeet. The PR removes circuit strikes for the analogous queue-timeout condition; use the same treatment here (for example raise a session-local exception handled without record_serve_failure, like QueueTimeout), keeping fail('timeout') without striking the circuit.
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 1122:
<comment>Budget exhausted at shared-STT-semaphore admission raises a bare `TimeoutError`, which `_post_and_parse` classifies as a provider timeout and records a serve failure on the Parakeet pool circuit — even though the request never reached Parakeet. The PR removes circuit strikes for the analogous queue-timeout condition; use the same treatment here (for example raise a session-local exception handled without `record_serve_failure`, like `QueueTimeout`), keeping `fail('timeout')` without striking the circuit.</comment>
<file context>
@@ -1110,13 +1110,23 @@ async def _post_window(self, pcm: bytes) -> httpx.Response:
+ )
+ remaining = math.floor(remaining * 1000) / 1000
+ if remaining <= 0:
+ raise TimeoutError('post budget exhausted at semaphore admission')
return await get_stt_client().post(
self._url,
</file context>
| raise TimeoutError('post budget exhausted at semaphore admission') | |
| raise QueueTimeout('post budget exhausted at semaphore admission') |
| gpu.vram_info = {"total_mb": 0, "baseline_mb": 0, "attention_mode": "full", "auto_threshold_sec": 300} | ||
| gpu.submit.side_effect = mock_submit | ||
|
|
||
| engine = BatchEngine(gpu, max_batch_size=4, max_wait_seconds=0.002, max_inflight=1, vram_safety_factor=0) |
There was a problem hiding this comment.
P2: This setup never starts a flush waiting on the semaphore: three queued requests do not reach the batch size of four, and the flush loop skips dispatch while the blocker is in flight. Set max_batch_size=3 so the third queued request starts the waiter this regression test is meant to cover.
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_parakeet_batch_engine.py, line 1159:
<comment>This setup never starts a flush waiting on the semaphore: three queued requests do not reach the batch size of four, and the flush loop skips dispatch while the blocker is in flight. Set `max_batch_size=3` so the third queued request starts the waiter this regression test is meant to cover.</comment>
<file context>
@@ -1033,3 +1036,317 @@ def test_unlink_existing(self):
+ gpu.vram_info = {"total_mb": 0, "baseline_mb": 0, "attention_mode": "full", "auto_threshold_sec": 300}
+ gpu.submit.side_effect = mock_submit
+
+ engine = BatchEngine(gpu, max_batch_size=4, max_wait_seconds=0.002, max_inflight=1, vram_safety_factor=0)
+ loop = asyncio.new_event_loop()
+ try:
</file context>
| engine = BatchEngine(gpu, max_batch_size=4, max_wait_seconds=0.002, max_inflight=1, vram_safety_factor=0) | |
| engine = BatchEngine(gpu, max_batch_size=3, max_wait_seconds=0.002, max_inflight=1, vram_safety_factor=0) |
| window POST explicitly marks its live lane; unmarked requests remain backfill. | ||
| Each live POST also carries `X-Omi-STT-Timeout-Seconds`, the caller's remaining | ||
| POST budget sampled at local STT-semaphore admission. The service converts it | ||
| into a monotonic queue deadline — request start plus the lesser of the supplied |
There was a problem hiding this comment.
P2: This queue deadline is not enforced in the supported NIM mode: that mode skips BatchEngine and transcribes directly. Qualify this behavior to the batched Nemo path.
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 732:
<comment>This queue deadline is not enforced in the supported NIM mode: that mode skips `BatchEngine` and transcribes directly. Qualify this behavior to the batched Nemo path.</comment>
<file context>
@@ -727,6 +727,28 @@ to report fresh telemetry; busy plus unknown replicas reaching half the pool
window POST explicitly marks its live lane; unmarked requests remain backfill.
+Each live POST also carries `X-Omi-STT-Timeout-Seconds`, the caller's remaining
+POST budget sampled at local STT-semaphore admission. The service converts it
+into a monotonic queue deadline — request start plus the lesser of the supplied
+budget and an 8-second cap, defaulting to 8 when the header is absent; a
+malformed, non-finite, or non-positive budget is rejected 400 before the upload
</file context>
| into a monotonic queue deadline — request start plus the lesser of the supplied | |
| into a monotonic queue deadline in the batched Nemo path — request start plus the lesser of the supplied |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 97b5e0db00
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| REQUESTS_TOTAL.labels(endpoint="v1_transcribe", status="error").inc() | ||
| return JSONResponse(status_code=400, content={"detail": f"Invalid {_TIMEOUT_HEADER} budget"}) | ||
| budget = min(budget, supplied) | ||
| queue_deadline = request_start + budget |
There was a problem hiding this comment.
Reserve time for the queue-timeout response
When a live request remains queued through the advertised budget, this deadline starts the full caller-remaining duration again at server handler entry, which occurs only after the request and multipart upload have reached Parakeet. Consequently the caller's enclosing asyncio.timeout normally expires before the server can send the marked 503; _post_and_parse then handles a local TimeoutError and records a Parakeet serve failure, opening the circuit—the exact false provider outage this signal is intended to avoid. The server deadline must expire sufficiently before the caller's deadline, or the caller must reserve time to receive the response.
Useful? React with 👍 / 👎.
| if remaining <= 0: | ||
| raise TimeoutError('post budget exhausted at semaphore admission') |
There was a problem hiding this comment.
Classify an exhausted admission budget as a queue timeout
If the STT semaphore becomes available with less than one millisecond remaining, flooring makes remaining zero after acquired has already been set. This raises a plain TimeoutError; the outer handler therefore does not convert it to QueueTimeout, and _post_and_parse records a provider serve failure even though no request was sent. Under semaphore contention this can falsely open the process-wide Parakeet circuit; raise QueueTimeout directly or defer marking the semaphore as acquired until this local budget check passes.
Useful? React with 👍 / 👎.
) ## Summary **Supersedes #20357. Merges inert; enabled only on the canary Deployment via `STT_FAILOVER_RECOVERY_ENABLED=true`. No PR merge or deployment performed.** The pod-level switch defaults false in code, dev/prod listen charts, runtime base and overlays. One mode is read at session construction and propagated to the receiver, successor legs, callbacks and spawned writers; a session never switches mid-flight. Unset/false/invalid values retain current main's recovery, replay, capture, paid writer, rejection/circuit and settlement behavior, including #20393's managed `owner_closing` fence. The semantics-preserving PCM ring optimization below remains active in both modes. Failure-Class: FC-live-stt-audio-lost-on-provider-death No provider-order, allocation, routing-default, health namespace or workflow changes. Keep `STT_ROUTING_MODE=shadow`, `STT_ROUTING_ON_PERCENT=0`. Main through `bf48ed0e68674a0d5d3c3e17f57dff042156b15d` was merged normally in `abcadb4bc5b6418d9fe969baa5262e7eda054540`, retaining upstream STT log sanitization, #20418 canary tooling, #20433 abandoned Parakeet queue cleanup and subsequent serving changes. The legacy controller/replay/paid-writer baseline remains `147f77d86a`: later main merges change none of those extracted recovery functions. The new main Parakeet POST-budget/queue-timeout contract applies identically in both flag modes, and unrelated deployment settings retain latest main exactly. The merge hook's unrelated Flutter formatting was restored byte-for-byte to main; locked dependency resolution made all 117 restored files format-stable, and the repair commit passed the normal hook. No stash, rebase, force-push, hook bypass, customer transcript/audio read, cloud mutation, PR merge or deploy. ## PCM ring hot path — independent of recovery enablement `AudioRingBuffer._append_bytes` now keeps the newest capacity-sized suffix with at most two memoryview bulk copies, replacing a Python loop for every byte. Capacity, physical overwrite order, absolute counters, span ledger and read APIs are unchanged. No await, lock, thread or bytearray resize was added; the existing caller ownership/scheduling contract is unchanged. Local Python 3.11.15 microbenchmark, `time.process_time_ns`, median of five runs over 135 s of 16 kHz mono PCM16 (4,320,000 bytes). Allocation/payload creation are outside timing; the public positioned-write path and span recording are included. These are local measurements under load, not production CPU measurements: | Input | Before CPU / 135 s | After CPU / 135 s | CPU per second of audio, before → after | | --- | ---: | ---: | ---: | | 4,500 live 30 ms packets | 127.055 ms | 3.410 ms | 0.941148 → 0.025259 ms (37.3× faster) | | One full-ring write | 125.977 ms | 0.099 ms | 0.933163 → 0.000733 ms (1,272.5× faster) | Both public write APIs have full-ring and live-packet tests asserting <0.10 s CPU, below the unchanged 0.30 s fast-test guard. All four performance cases failed before the optimization and pass after it. Small reference-model tests cover capacities 1/2/7/10, empty/exact-wrap/oversized multi-wrap/subsequent writes, counters, extraction and timestamps. The retained boundaries are asserted exactly: profiling pinned pytest 8.4.1 proved its first scalar `pytest.approx` equality imports NumPy (`is_bool`), dominating the tiny ten-byte test. Removing that unnecessary approximate comparison strengthens the assertions and removes a real cold-import cost; payloads, timed regions and both performance/guard thresholds are unchanged. The profiled NumPy import accounted for 0.485 of 0.487 cumulative profile seconds in that test (diagnostic profile time, not a production CPU measurement). Evidence: `.pytest-tmp/pcm-cold-approx.pstats`; the strengthened ring file passes 24 tests with zero guard warnings (`inert-exact-ring-assertions.log`). Seven selected files through `backend/test.sh`: 336 passed, one slow deselected. Evidence: `.pytest-tmp/pcm_ring_benchmark.py`, `pcm-ring-before.json`, `pcm-ring-after.json`, and `.pytest-tmp/logs/test-sh-selected.log`. The previously unpushed all-cooling/test-isolation round and ring fix were published normally at `e67b5ebfb9cb8d995d57c202bcbff8abd7b494ec`. All local hooks passed, including the 0.30 s CPU guard; `make preflight` passed 31 checks. That intermediate head had a main merge conflict and only CodeQL ran remotely, so it is not a backend-CI receipt. Logs: `.pytest-tmp/logs/pcm-ring-push.log`, `pcm-ring-make-preflight.log`. ## Flag-off equivalence and validation Baseline: main `147f77d86a2de9d68cec63b6adeb69bd282aeeae`. - **Ten extracted function bodies match baseline AST**, normalizing only helper-module qualification, the finishing-helper name and function docstrings: receiver failover/rebuild/monitor/flush; replay reconnect/rejected-successor retry/synchronous send; configured-chain attempt; replacement selection; reconnect admission. Evidence: lead-authored `.pytest-tmp/flag_equivalence_audit.py` and `flag-equivalence-audit.json`. - **285 original main tests passed with false, and the same 285 passed unset**, through `test.sh` and the unchanged guard. The ten test files were byte-identical to pinned main: death monitor, resilient stream, session failover, managed fence, Parakeet exhaustion, Soniox rate-limit/typed rejection, Modulate socket/capacity, configured chain. No assertion edits. Preserved original sources and hashes: `.pytest-tmp/baseline-stt-recovery-sources/`, `baseline-stt-hashes.txt`, `flag-equivalence-audit.json`; logs `test-sh-baseline-{false,unset}.log`. After the ring pin correction, the unmodified original resilient suite passed again both false and unset (22 each). - **42 flag-contract tests passed**: fail-closed parsing; runtime/receiver/ring/VAD/real paid successor pins in both env-flip directions; task/context propagation and cancellation reset; plain 2,000-item queues and unchanged EOS off; legacy vs enabled 429 circuits; 135/150 s caps and legacy reconnect budgets; managed fence retained; departure settlement; no new counter or histogram observations off while baseline replay metrics still emit. File-local fixtures isolate circuits, backoff and health, with no network/Redis access. Initial log: `test-sh-flag-isolated-final.log`; final pin-entry regressions: `inert-ci-pin-fix.log`. - **Flag-on matrix: 97 fast passed; provider-pair suite: 27 passed.** File-local ON fixtures preserve the matrix and branch qualification assertions; there is no global fixture silently forcing production default on. Flag-contract plus matrix/provider-pair narrow run: 162 passed, one slow deselected (`test-sh-narrow-final.log`). Cost-router, speaker/capture-birth and evidence-settlement follow-up files also passed after explicitly enabling their qualification fixtures. After integrating #20433, the window suite (161), matrix (97) and provider pairs (27) passed together with the unchanged guard (`inert-main-queue-composition.log`). Eleven byte-identical newest-main queue-contract cases also passed OFF, including the actual marked-503 receiver failover (`inert-main-queue-off.log`). - **196 deployment/default checks passed** (Helm/env/render/validator/key bindings); runtime compose `--check` and feature-flag registry checks passed. Typecheck: **0 errors** (`typecheck-rework.log`). No timing-guard/duration-allowlist, CI threshold or security-policy relaxations. The proper flag-on slow lane also passed: **1 passed, 97 deselected** (`.pytest-tmp/logs/inert-slow.log`). Final local preflight passed **41 checks**, and PR-body CI-lane preflight passed **40 checks**, after registering the new flag's non-secret/config and listen-only ownership. Evidence: `inert-make-preflight.log`, `inert-pr-preflight.log`; those metadata additions are committed before publication. After the final main merge, compose/registry checks and **24 upstream canary-tooling tests** passed with the default timing guard (`inert-post-merge.log`); the worktree is clean with no app/workflow diff against main. The first inert push was correctly blocked by fixtures that bypassed receiver construction and by two qualification files missing explicit ON mode. A test-only follow-up pins those doubles coherently and enables only the affected test modules; all assertions remain unchanged. The three failing files now pass **192 tests**, and the two affected original-main baseline files pass again false and unset (**42 each**) without silently enabling their imported shared fixture. Logs: `inert-fixture-followup.log`, `inert-baseline-helper-{false,unset}.log`. No production follow-up or timing-budget relaxation was needed. A subsequent full normal-hook retry passed every assertion but blocked on one existing Parakeet case at 0.35 s CPU; the required single-file `test.sh` rerun passed all 151 tests, with that case at 0.24 s under the unchanged 0.30 s guard (`inert-timing-single-file.log`). Normal push and complete remote CI remain pending; the receipt below will be updated on the exact published head. ## Serving behaviour changes — complete gate map Paths below are the final serving surface. OFF preserves pinned-main behavior; ON enables the described recovery changes. Declarative limits/metric registration may exist in OFF images but have no OFF serving consumers/emissions. | File:line | Gate / serving change | | --- | --- | | `backend/utils/audio.py:41` | Ungated, semantics-preserving two-copy PCM hot-path optimization described above. | | `backend/config/live_stt_recovery.py:18,21,28` | Pure fail-closed env/context lookup and explicit owner pin; no per-user cohort or Redis switch. | | `backend/routers/listen/runtime.py:134,410,920` | Session-start snapshot, whole-run context lifetime and ON-only terminal-after-text emission; existing any-text SLI unchanged. | | `backend/routers/listen/receiver.py:243,867,1253,1294,1420,1578,1666,2075` | ON-only controller, unified dial/replay/adoption/ingestion/birth path; OFF dispatches original locked/synchronous recovery, capture and monitor behavior. | | `backend/routers/listen/legacy_recovery.py:27,46,147,183` | OFF-only main failover/rebuild/monitor/flush implementations, including old failure latch, attempt limits and synchronous prefix replay. | | `backend/utils/stt/recovery_state.py:59,115,279` | ON-only controller instantiated by receiver: lifecycle, episode/time/unique-target accounting and candidate-bound recovery proof. | | `backend/utils/stt/resilient_stream.py:73,162,188,323,357,478` | Pinned 135 s OFF / 150 s ON headroom; restored 3-total/2-per-minute/30 s cumulative OFF reconnect budget. Managed owner fence stays in both; unmanaged raw finishing remains authoritative OFF. New bounded capture/paced replay is ON-only. | | `backend/utils/stt/legacy_replay.py:24,120,149` | OFF-only main Soniox reconnect, rejected-successor retry and synchronous replay, with baseline metrics. | | `backend/utils/stt/live_recovery.py:25,32,69` | OFF retains 3 managed / 2 legacy rebuild limits and main rescue condition; ON uses shared controller and the sole qualified Soniox repeat. | | `backend/utils/stt/live_chain.py:139,305,332,520,861` | OFF exact main attempt body, cleanup and 429 breaker semantics; ON target reservations, bounded dials, refusal backoff and one earliest-expiry all-cooling escape. | | `backend/utils/stt/connect_backoff.py:22,108,178` | ON-only serving use via chain gate; per-target 3-in-10 s refusal history, 2/4/8/10 s backoff, exclusive probe, bounded escape and healthy reset. OFF never acquires a lease or mutates this state. | | `backend/utils/stt/streaming.py:419,466,484,521,1403,1531,1593` | OFF legacy-primary 429 failure handling and plain Modulate writer/EOS; ON admission release and recovery-only paced/deadline-aware writer. Parakeet replay declarations at `1856,2095` are consumed only ON. | | `backend/utils/stt/soniox.py:196,263,268,357` | Pinned plain queue/no pacing/original send-finalize-EOS OFF; ON bounded queued/in-flight accounting, writer cadence and capture-age expiry. | | `backend/utils/stt/send_queue.py:16` | `AudioSendQueue` allocated only ON by paid adapters; OFF uses exact `asyncio.Queue(maxsize=2000)`. | | `backend/utils/stt/replay_delivery.py:145,211,354,492` | ON-only serving activation of writer pacing, newest-unanswered prefix, bounded birth ledger and ordered live tail; OFF never enters pump/skip/expiry paths. | | `backend/utils/stt/live_session.py:57,384,463,847,858,947` | Managed leg inherits session pin; ON-only cancellation disposal, waits, typed endpoint limits, controller departure and departing settlement; OFF main lifecycle retained. | | `backend/utils/stt/vad_gate.py:736,762` | VAD wrapper pins underlying mode and forwards new capacity waits only ON. | | `backend/utils/stt/live_failure.py:160,239,577` | Pending settlement inherits source/session mode; departure degradation and extra post-await lifecycle checks only ON; OFF existing exhaustion/termination semantics. | | `backend/utils/stt/live_outcome.py:53` | Mode metadata only; existing single serving-owned emission seam remains authoritative. | | `backend/utils/stt/live_metrics.py:5,24,29,113` | New bounded families can register/preinitialize at zero in either mode; all recovery observation sites and terminal-after-text emission are ON-only. Baseline metrics unchanged OFF. | | `backend/config/live_stt_replay.py:11`; `backend/config/live_stt_registry.py:26`; `backend/utils/stt/safe_socket.py:60` | Typed endpoint/adapter replay declarations are data only OFF and consumed by ON pumps; order/ramp defaults unchanged. | | `backend/deploy/runtime_env/_base.yaml:100`; `backend/deploy/runtime_env/dev.overlay.yaml:50`; `backend/deploy/runtime_env/prod.overlay.yaml:43`; `backend/deploy/runtime_env.yaml:139,2151` | Default-off runtime declaration and composed dev/prod manifests. | | `backend/charts/backend-listen/dev_omi_backend_listen_values.yaml:378`; `backend/charts/backend-listen/prod_omi_backend_listen_values.yaml:405`; `config/feature-flags.yaml:132` | Explicit false chart defaults and reviewed flag registry. | | `config/deployment-setting-classification.json:229`; `backend/scripts/verify_pusher_cohost_env_diff.py:99,203` | Declare the new boolean as non-secret configuration and as listen-only STT ownership in both environments; no secret mappings, shared-finalizer requirements or enforcement thresholds changed. | Line-Count-Exception: backend/routers/listen/receiver.py | 1842 -> 2237 | Default-off main recovery dispatch plus explicit ON session-owner replay/adoption/ingestion integration. Line-Count-Exception: backend/utils/stt/streaming.py | 2205 -> 2322 | Separate pinned OFF writer and ON recovery cadence/deadline branches plus shared target-aware bounded dials. ## Enabled recovery design and known trade-offs Only flag-on sessions use `serving → provider_died → recovering → replaying → recovered`, or terminal `exhausted` / `client_leaving`. Departure is owner/application lifecycle, never managed raw cleanup. One 60 s episode covers actual dials, replay and proof; real dials are capped at min(5 s, episode remaining). Up to 20 unique identities/episodes and one qualified Soniox repeat bound work. Skips consume no dial. Prefix adoption plus current-candidate text or an observed 5 s healthy-connected dwell releases the episode; silence is normal. Connected proof does not synthesize transcript success or settle a hop recovered. Replay defaults: 1× audio time, ≤16 KiB frames, two queued+in-flight slots, ≤2 s capacity wait. [Soniox real-time cadence](https://soniox.com/docs/stt/rt/error-handling#real-time-cadence) supports near-real-time delivery; [Modulate streaming reference](https://docs.modulate.ai/api-reference/stt/streaming.md) supplies no qualified accelerated ceiling, so 1× is conservative. Window/RNNT/Deepgram use conservative pump limits and their existing admission contracts, not a claim of qualified acceleration. Optional endpoint declarations may only tighten limits. **Loss trade-off:** at default 1× and a 20 s prefix wall, a 135 s unanswered backlog keeps the newest 20 s and skips 115 s from successor transcription, explicitly metered and retired once. Capture gaps do not count as audio. Slower endpoint limits, repeated failures and residence expiry can cut additional audio. Transport writes are not transcript acknowledgments. Live ingestion stays ordered in a ≤26 s tail; first capture acceptance is retained in a bounded 8,192-entry birth ledger. Tail writes have a 28 s capture-age bound, or are explicitly cut/rejected. The qualified one-handoff 20 ms consumer case measured ≤25.532 s capture-to-wire at 16 kHz including setup (≤26.044 s at 8 kHz), excluding transcript latency. Continuous 1× speech cannot catch up until admitted audio pauses. Conservative recovery-owned PCM allowance: 8,241,152 B/session; 125.75 MiB for 16 sessions at 16 kHz, 375.75 MiB at 48 kHz, excluding Python/VAD/POST/ordinary queues/RSS. 429s remain session-local refusal evidence ON, not account quarantine or a shared long serving bench. Three refusals in 10 s open 2/4/8/10 s process-local backoff. All-cooling cannot alone deny a fresh session: one earliest-expiry otherwise-admissible dial is allowed; an early lease does not extend/escalate cooldown. Account, withdrawal, failed-target, capability, window admission and recovery budgets remain enforced. Historical paid concurrency was supplied by the coordinator; fake surge tests do not establish current paid headroom. No global paid limiter was added. Historical aggregate exhausted events cannot be individually attributed. Reproductions cover stalled send/finalize queues outside replay and already-claimed failures settling after later departure. OFF keeps main semantics; ON departure settles degraded, with exhausted reserved for active bounded recovery exhaustion. PTT stays unpaced and retains its existing large-frame follow-up: independently supervised disconnect, bounded residual cursor, paced pump and EOS barrier are still needed. ## Canary observation and rollout — coordinator-owned, not performed New metrics are not fleet-wide SLIs while defaults are off. Set `${canary_pods:regex}` / `${control_pods:regex}` to escaped exact enabled-canary / flag-off control pod names and refresh after replacement. Current scrape does not carry `track`; do not filter on it. Missing telemetry/exposure is HOLD, not zero-loss proof. Examples, not executed production measurements: ```promql sum by (source,successor) (increase(omi_stt_recovery_attempts_total{job="backend-listen-metrics",namespace="prod-omi-backend",pod=~"${canary_pods:regex}"}[15m])) histogram_quantile(0.95,sum by (le,source,successor) (rate(omi_stt_replay_wall_seconds_bucket{job="backend-listen-metrics",namespace="prod-omi-backend",pod=~"${canary_pods:regex}"}[5m]))) sum by (source,successor) (increase(omi_stt_replay_skipped_seconds_total{job="backend-listen-metrics",namespace="prod-omi-backend",pod=~"${canary_pods:regex}"}[15m])) sum by (provider) (increase(omi_live_session_terminal_after_text_total{job="backend-listen-metrics",namespace="prod-omi-backend",pod=~"${canary_pods:regex}"}[15m])) sum(increase(omi_stt_recovery_attempts_total{job="backend-listen-metrics",namespace="prod-omi-backend",pod=~"${control_pods:regex}"}[15m])) > 0 ``` Proposed canary alerts (`for: 1m`), scoped rather than mixing inert controls: ```promql sum(increase(omi_fallback_total{job="backend-listen-metrics",namespace="prod-omi-backend",pod=~"${canary_pods:regex}",component="stt_live_session",from_mode=~"soniox|modulate",reason="capacity_full"}[5m])) > 0 sum(increase(omi_live_stt_terminal_failures_total{job="backend-listen-metrics",namespace="prod-omi-backend",phase=~"connection|send"}[25m])) > 3 ``` The latter is the supplied historical fleet 0–3/25 min baseline, not a measured per-canary threshold. Compare same-load controls and retain independent any-text/continuity checks. Two fixed canary pods plus isolated dev soak are the agreed mechanism (#20418), not an action performed here. First 15 min: ≥10 positive replays including both paid families, all canary pods scraped, zero replay-induced terminal/capacity deaths, replay p95 ≤20 s with ≥10 observations, no unexplained fresh skips, no sustained lifecycle residual, ≥50 sockets with ≥95% any-text and ≤2-point decline vs controls. First 60 min: ≥30 positive replays/≥5 per paid family/≥100 sockets, same no-loss/lifecycle gates, first-text p95 <30 s, window POST p95 <2 s, combined pressure/overflow ≤1% with ≥20 admissions. Missing exposure is HOLD; replay-induced terminal loss is ABORT. Approval, paid/public-speech soak, vendor capacity/quality/billing/RSS/backfill and attended rollback remain coordinator gates. Controller/ring/tail state is process/WebSocket memory only. Existing sockets retain their pinned mode through drain; reverting flag false affects new sessions, not in-flight recovery. An older-image rollback is safe for persisted data but restores its known synchronous-overflow defect. Abrupt process death can lose in-memory tails; client offline capture/sync owns cross-process recovery. ## Product invariants affected - **INV-MEM-4 preserved** (`product/invariants/memory-promotion-authority.md`): runtime manifest gains only a false listen STT flag; memory admission, schedules, authority and fences are unchanged. Runtime compose/render/validator checks cover this additive deployment declaration. ## Final publication / CI receipt The inert implementation was published normally at `9ec29a62cba2bffdfe4f2fe5ed81d429f11e54f5`: all hooks passed (41 preflight checks, typecheck 0 errors, selected backend files under the unchanged CPU guard). Receipt: `.pytest-tmp/logs/inert-push-final.log`. Newer main introduced a documentation conflict, preventing full PR CI; main is now integrated locally at `abcadb4bc5b6418d9fe969baa5262e7eda054540`, preserving its queue cleanup and the bounded-replay wording. A merged-head push passed preflight/typecheck/source closure but was blocked when the canonical `.venv` disappeared before unit tests. The documented `scripts/sync-python-deps.sh` route restored Python 3.11.15 from `pylock.macos.toml`, with no tracked dependency or policy edits; environment preflight and 38 flag tests passed (`env-repair-sync.log`, `inert-env-repair.log`). The remover is unknown; no other lane/process was altered. Final local head is `389885f9e7194db42ceae060b52947e0cde5ad77`, adding only the exact ring-assertion/cold-import follow-up to that merge. **Published normally at `389885f9e7194db42ceae060b52947e0cde5ad77`** with all hooks enabled: 41 preflight checks, typecheck 0 errors, selected backend suites passing the unchanged 0.30 s guard, runtime/env/source closure and API contracts. Receipt: `.pytest-tmp/logs/inert-cold-import-fixed-push.log`. GitHub reports this head MERGEABLE and full source CI is running, including all four backend shards. CI on that head passed CodeQL, slow guardrails, hermetic E2E/listen-pusher gauntlet, metadata/hygiene, env and source closure, but its broad unit shards caught five unchanged provider/readiness files calling constructor-bypassing owners without the new pin field, plus a static lifecycle test inspecting the wrapper rather than the serving body. Follow-up `fab2f0754f8ea52d6f828ea022ba80c9019085b8` pins only missing/non-boolean entry fields once (inheriting an already-pinned receiver), leaves fully constructed sessions unchanged, and strengthens the lifecycle guard across `run → _run → finally teardown`. All original provider assertions remain unmodified; six failing suites plus 42 flag cases passed locally (**159 passed, 14 slow deselected**), typecheck 0 errors (`inert-ci-pin-fix.log`, `typecheck-pin-fix.log`). **That follow-up is now published normally at final head `fab2f0754f8ea52d6f828ea022ba80c9019085b8`**. All hooks passed again (41 preflight checks, typecheck 0 errors, selected tests under unchanged 0.30 s CPU guard); receipt `inert-ci-pin-fix-push.log`. GitHub reports it MERGEABLE and exact-head source CI is running; no green unit-CI claim is made yet. PR remains open/draft; do not merge or deploy. #### Test plan - [x] PCM semantic regressions and before/after benchmark; publish prior unpushed fixes normally. - [x] Flag-off original-main false/unset suites; source/body equivalence audit; mode-pinning/metrics/circuit contracts. - [x] Flag-on fast recovery matrix, provider pairs and affected qualification suites; unchanged CPU guard. - [x] Default-off chart/base/overlays/compose and flag registry; typecheck 0 errors. - [ ] Final slow matrix, committed-head preflight, normal inert-head push and complete source CI. - [ ] Independent coordinator approval, paid/public-speech soak, deployment and attended rollout (not performed). Generated with [Devin](https://devin.ai)
Summary
Fix independent-review finding 11 and Luna's queue-expiry classification follow-up. Cancelled submission futures remained in the Parakeet batch queue, inflated pressure, and were still dispatched to the GPU. Prune abandoned work before admission/dispatch/pressure reads, expire queued live work under a caller-supplied remaining budget, and release only files owned by abandoned requests. Preserve live priority and the single aged-backfill turn after four live batches.
Queue expiry now returns HTTP 503 with JSON
error: "queue_timeout"andX-Omi-STT-Error: queue_timeout. Listen recognizes only that exact 503/header pair ascapacity_full, with the bounded log subtypequeue_timeout: the window dies and releases admission promptly, and existing failover proceeds without a Parakeet serve-failure count or circuit strike. Missing/unknown markers and other 5xx statuses retainprovider_5xx. No response-body parsing or free-text reason inference is added.Failure-Class: FC-shared-batch-pressure-blocks-live
Serving behaviour changes
backend/parakeet/batch_engine.py:177backend/parakeet/batch_engine.py:256backend/parakeet/main.py:205/v1/transcribeacceptsX-Omi-STT-Timeout-Seconds, capped at 8 seconds and defaulting to 8 for older clients. Invalid/nonfinite/nonpositive budgets return bounded 400. Backfill ignores the header.backend/parakeet/main.py:276error=queue_timeoutplusX-Omi-STT-Error: queue_timeout; existing detail and lane-refusal metrics remain. Other 503 responses are unchanged.backend/parakeet/main.py:253status=cancelled, not success/RTFX. Pending gauge refreshed on completion.backend/utils/stt/parakeet_window.py:1106backend/utils/stt/parakeet_window.py:1146capacity_full/queue_timeout, recordsWINDOW_POSTS{outcome="queue_timeout"}, and fails the window over withoutrecord_serve_failure. Unsignalled 503/other 5xx still strike the circuit as before.backend/utils/observability/fallback.py:163queue_timeoutas a bounded capacity log subtype; fallback metric reason stayscapacity_full, with no new metric dimension.The server-local deadline starts at handler entry and includes file read/write and queue time. The transmitted relative budget does not compensate for network/multipart time before handler entry. Already-dispatched inference is not preempted. No provider order, allocation, chart, runtime environment, router default, or
.github/changes: production remainsSTT_ROUTING_MODE=shadow,STT_ROUTING_ON_PERCENT=0. Recovery implementation files owned by #20391 are untouched.Test plan
cd backend && TMPDIR=$PWD/../.pytest-tmp .venv/bin/python -m pytest -q -p no:cacheprovider tests/unit/test_parakeet_batch_engine.py tests/unit/test_parakeet_endpoints.py tests/unit/test_parakeet_window_live.py --durations=8: 251 passed.PYTHON=.venv/bin/python bash test-preflight.sh: 18 passed, 0 failed. Standardtest.shwithBACKEND_UNIT_TEST_FILE_LISTselecting those three files: 251 passed. Final isolated window-file rerun after review: 161 passed, with the unchanged 0.30-second local CPU guard.provider_5xx.capacity_full/queue_timeout, settles a recovered hop, and leaves serve-failure calls/events unchanged and the circuit closed. Bounded subtype tests keepqueue_timeoutout of metric reason labels and suppress unbounded content.backend/scripts/typecheck.sh: 0 errors (existing warnings).make preflight: 30 selected checks passed.origin/mainat147f77d86a2de9d68cec63b6adeb69bd282aeeaewas merged normally, without conflicts.Local evidence: ignored
.local/f11/logs, includingpytest-f11-red.log,test-sh-f11.log,test-sh-f11-final-window.log,typecheck-f11.log, andmake-preflight-f11.log. Synthetic data/fake GPU/providers only; no production or dev data/services accessed. The original task reported an accidental temporary stash immediately restored; no stash was used in this review round.Deployment and rollout order
Requires BOTH deployments: a backend-listen image deploy for the remaining-budget header and queue-expiry classification, and a separate Parakeet image deploy via existing
gcp_parakeet.yml/backend/charts/parakeetfor cancellation/queue hygiene and the machine-readable response. A listen-only deploy does not ship the GPU queue fix; a Parakeet-only deploy does not fix listen classification. No deployment is performed by this PR/task.Recommended order: deploy listen first, wait until all listen pods use the new image, then deploy the Parakeet image. This avoids enabling queue expiry while pre-signal listeners can mistake it for provider unavailability. Verify both image SHAs and the response header survives the actual service path.
provider_5xx: it callsrecord_serve_failure()once, immediately opens the process-local Parakeet serve-error circuit, releases the window, and enters existing failover. Repeated queue expiries can extend/escalate the provider bench and influence provider-failure health evidence. This false-outage risk remains until listen is upgraded; Parakeet-first is not classification-safe.provider_5xx, one serve-failure call/open circuit, and existing failover. No heuristic interprets old free-text bodies. Old servers may ignore the request-budget header.capacity_full/queue_timeout; prompt release/failover, no serve-failure call or circuit strike. Capacity is censored rather than provider-failure evidence in the existing health taxonomy. Genuine unmarked 503/other 5xx still behave as provider failures.On the new Parakeet image, use synthetic live-window requests queued behind controlled GPU work, then cancel them or give a short queue budget. Check
/batch/metrics:pending_requests,live_pending_requests, andlive_oldest_pending_secondsreturn to the surviving queue only. Existing Prometheusparakeet_batch_pending_requests/parakeet_batch_lane_pending_requests{lane="live"}must fall rather than retain obsolete work; expiry incrementsparakeet_batch_lane_refusals_total{lane="live",reason="queue_timeout"}andparakeet_requests_total{endpoint="v1_transcribe",status="error"}. Cancelled requests increment the existing request counter withstatus="cancelled". Discarded files must not appear in GPU batch assembly, and must not add observations toparakeet_batch_lane_queue_wait_seconds,parakeet_queue_duration_seconds, orparakeet_batch_size. Verify the queue-expiry response is 503 with the exact header and JSON error. On new listen, checkomi_stt_window_posts_total{outcome="queue_timeout"}and existingomi_fallback_total{component="stt_live_session",reason="capacity_full"}with boundedsubtype=queue_timeoutlogs, without new Parakeet serve strikes/provider-failure health evidence from that expiry. Observe lower obsolete live queue pressure and fewer unnecessaryomi_stt_window_admissions_total{outcome="batch_pressure"}refusals under comparable load, without promising a specific production improvement. Verify owned temp files disappear, unowned files survive, and existing backfill fairness still holds.Coordination / deferred work
PR #20391 owns recovery/replay and Soniox/Modulate send paths. None are changed here. It also edits
test_parakeet_window_live.pyandlisten_pusher_pipeline.mdx, so preserve both changes when resolving nearby test/documentation conflicts. Longer-term GPU preemption/backfill execution quanta or separate capacity remain deferred; this fix removes obsolete queued work, not running kernels. Neither PR merge nor deployment is authorized by this task.Generated with Devin