Repository navigation
Fix DG keepalive thread permanently killing connection (#5870) - #5871
Conversation
The SDK's built-in keepalive thread calls _signal_exit() on any exception, permanently killing the DG connection. Our VAD gate already handles keepalives. Remove the key entirely (string "false" is still truthy in Python). Co-Authored-By: Claude Opus 4.6 <[email protected]>
Check return values of send() and keep_alive(). When either returns False or raises, mark connection as dead and stop forwarding audio. Prevents silent audio loss for the rest of the session. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Check is_connection_dead before sending audio to DG. When detected, log error and set dg_socket to None to stop further sends. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Tests: send returns False, keepalive returns False, keepalive exception, dead socket stops sending, passthrough mode resilience. Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
Required fixes before merge:
Please push a follow-up commit and I’ll re-review quickly. by AI for @beastoin |
Add dg_socket to nonlocal declaration so the dead-connection assignment (dg_socket = None) modifies the enclosing scope. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Greptile SummaryThis PR addresses a real bug in Deepgram SDK v4.8.1 where a background keepalive thread could permanently kill the WebSocket connection by calling The core idea is sound, but there are two places where the implementation doesn't fully deliver the stated behaviour:
The Confidence Score: 2/5
Important Files Changed
Sequence DiagramsequenceDiagram
participant TA as transcribe.py<br/>flush_stt_buffer
participant GDS as GatedDeepgramSocket
participant DG as Deepgram SDK
TA->>GDS: send(chunk)
GDS->>GDS: _dg_dead? → False
GDS->>DG: conn.send(audio)
DG-->>GDS: returns False
GDS->>GDS: _dg_dead = True
GDS-->>TA: returns
Note over TA: Next audio chunk (~30 ms later)
TA->>TA: check is_connection_dead → True
TA->>TA: log error (EVERY call ⚠️)
TA->>TA: dg_socket = None (LOCAL only, no nonlocal)
Note over TA,GDS: Outer dg_socket still dead socket!
Note over TA: Next audio chunk
TA->>TA: dg_socket still not None (outer scope)
TA->>TA: check is_connection_dead → True
TA->>TA: log error AGAIN ⚠️
Note over GDS: Gate=None passthrough path
TA->>GDS: send(chunk)
GDS->>GDS: _dg_dead? → False (never set in passthrough)
GDS->>DG: conn.send(audio) → False
GDS-->>TA: returns (flag NOT set ⚠️)
|
| # Check if DG connection died (keepalive or send failure) | ||
| if hasattr(dg_socket, 'is_connection_dead') and dg_socket.is_connection_dead: | ||
| logger.error('DG connection died mid-session uid=%s session=%s', uid, session_id) | ||
| dg_socket = None # Stop sending to dead connection |
There was a problem hiding this comment.
dg_socket = None assignment is scoped locally — dead detection fires on every flush
flush_stt_buffer does not declare dg_socket as nonlocal, so the dg_socket = None assignment on this line only creates a local variable within the single invocation of flush_stt_buffer. The parameter dg_socket in the enclosing receive_data function is unaffected.
On every subsequent call to flush_stt_buffer (which happens every ~30 ms of incoming audio), dg_socket is re-read from receive_data's scope — still the dead socket — so the is_connection_dead branch is entered again, and logger.error(...) fires again. The PR description says "Dead connection logs once per detection, not per send", but the code does the opposite: the error is emitted once per 30 ms audio chunk for the rest of the session.
The fix is to add dg_socket to the nonlocal declaration so the assignment actually persists:
async def flush_stt_buffer(force: bool = False):
nonlocal stt_audio_buffer, soniox_profile_socket, deepgram_profile_socket, dg_usage_ms_pending
nonlocal dg_socket # required so the dead-detection assignment propagatesWithout this, dg_socket = None on line 2310 is a no-op for all future calls and the error log will flood at audio-chunk rate (~33×/s).
| if self._gate is None: | ||
| return self._conn.send(data) |
There was a problem hiding this comment.
Passthrough mode never marks connection dead
When self._gate is None (passthrough mode), the return value of self._conn.send(data) is forwarded to the caller but _dg_dead is never set to True, even if the DG SDK returns False. Subsequent calls still reach this branch and keep forwarding audio to the dead connection.
The early-exit guard at the top (if self._dg_dead: return) is only useful after _dg_dead has been set — but in passthrough mode that never happens.
The test test_passthrough_dead_on_send_false only verifies "don't crash"; it doesn't assert that later sends are dropped.
if self._gate is None:
ret = self._conn.send(data)
if ret is False:
self._dg_dead = True
returnThis gap matters even if all current production sockets use an active gate, because the gate=None path exists and could be exercised by future callers or during the VAD-error fallback (where self._gate is cleared).
Tests the caller-side pattern where is_connection_dead triggers dg_socket = None, matching transcribe.py:2307-2310 behavior. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Asserts that deepgram_options and deepgram_cloud_options do not contain the "keepalive" key, which spawns a dangerous background thread. Co-Authored-By: Claude Opus 4.6 <[email protected]>
CP9 — Live Backend Validation EvidenceTest 1: DG connection without SDK keepalive (the fix)Test 2: Keepalive thread verification (old vs new)Confirms: Removing Test summary
by AI for @beastoin |
All checkpoints passed — PR ready for merge
7 commits, 125 unit tests pass, live DG test confirms fix works. Awaiting human merge approval. by AI for @beastoin |
…d detection (#5870) Dead-connection detection should work regardless of whether a VAD gate is used. SafeDeepgramSocket wraps the raw DG connection with send/keepalive monitoring. GatedDeepgramSocket now delegates is_connection_dead to it. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Always wraps the raw DG connection with SafeDeepgramSocket for dead detection, regardless of whether a VAD gate is enabled. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Both SafeDeepgramSocket and GatedDeepgramSocket expose is_connection_dead, so the hasattr check is no longer needed. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…5870) Tests now verify dead detection at both layers: SafeDeepgramSocket alone (no VAD gate) and GatedDeepgramSocket delegating to SafeDeepgramSocket. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Remove utils.stt.vad_gate from mock list since it has no heavy deps. Prevents test isolation issues when running both test files together. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Architecture Refactor: Dead detection moved to connection levelManager feedback: keepalive/dead detection shouldn't be VAD gate's responsibility — what if we don't have the VAD gate? Fix: Extracted New architecture:
safe_conn = SafeDeepgramSocket(dg_connection)
if vad_gate is not None:
return GatedDeepgramSocket(safe_conn, gate=vad_gate)
return safe_conn
@property
def is_connection_dead(self) -> bool:
if isinstance(self._conn, SafeDeepgramSocket):
return self._conn.is_connection_dead
return FalseTest coverage (129 passing):
Live DG test (repeated after refactor):WS backend pipeline test:
by AI for @beastoin |
All checkpoints passed — PR ready for merge
Key changes since last review:
12 commits, 129 unit tests pass, live DG test passes. Awaiting human merge approval. by AI for @beastoin |
5-Minute Live DG Connection Test — PASSPattern: 10s speech + 20s silence repeating (simulates real conversation), manual keepalives every 8s. Connection held for full 5 minutes with zero errors. by AI for @beastoin |
App + Live Test EvidenceApp Screenshots (flow-walker on emulator)
App successfully enters Listening mode and connects to the local backend with the keepalive fix applied. WS connection chain:
Live DG Connection Test — 5 minutes (300s)Backend log — WS → DG connection chainUnit tests — 129 passby AI for @beastoin |
Physical Device (Pixel 7a) Live Test EvidenceTranscription Working on Physical DevicePixel 7a (33041JEHN18287) connected to local backend (VPS 100.125.36.102:10161) via Tailscale:
SafeDeepgramSocket Dead Detection WorkingBackend logs confirm the fix works exactly as designed: Pipeline: Connection chain (from backend log)by AI for @beastoin |
SafeDeepgramSocket is about STT connection safety, not VAD gating. Moving it to streaming.py where process_audio_dg() wraps connections. Uses class attribute marker (_is_safe_dg_socket = True) with `is True` check to avoid circular import and MagicMock false positives. Co-Authored-By: Claude Opus 4.6 <[email protected]>
GatedDeepgramSocket now uses getattr(_is_safe_dg_socket, None) is True to detect SafeDeepgramSocket without importing it (avoids circular import). Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
#5870) GatedDeepgramSocket now delegates keep_alive() to underlying SafeDeepgramSocket, allowing callers to explicitly ping DG. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…5870) Replace 15s sleep with keepalive loop (5s intervals) to prevent DG 10s idle timeout on the main socket while audio routes to the profile socket. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Avoids heavy import chain (soniox_util → storage → GCP clients) when unit tests only need the socket wrapper. Tests now collect without GOOGLE_APPLICATION_CREDENTIALS. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…5870) Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ests (#5870) Tests: keep_alive delegation alive/dead, SafeDeepgramSocket finalize/finish. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Tests: SafeDeepgramSocket/GatedDeepgramSocket return types from process_audio_dg, stabilization keepalive loop pattern, dead-stop. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ad (#5870) Architecture change: SafeDeepgramSocket is now the SOLE keepalive owner. Background daemon thread sends keepalive when idle > 5s (configurable). Injectable clock for deterministic testing. Thread-safe with single lock. Eager thread start in constructor — covers all idle windows automatically. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…amSocket (#5870) GatedDeepgramSocket no longer calls keep_alive() or tracks keepalive timing. SafeDeepgramSocket's background thread handles all keepalive automatically. Removes keep_alive() method and needs_keepalive check from send(). Co-Authored-By: Claude Opus 4.6 <[email protected]>
…5870) Replace manual keepalive loop with plain asyncio.sleep(). SafeDeepgramSocket's background thread automatically keeps the main DG socket alive during the speech profile stabilization window. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
…tests (#5870) Remove TestGatedKeepAlive class and gate-level keepalive tests. Replace DG1011 regression tests with auto-keepalive verification using injectable clock. Add SafeDeepgramSocket thread lifecycle and send exception tests. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Add tests: auto-keepalive during idle, stops on dead, resets on send, config validation. Replace manual keepalive pattern tests. Add thread cleanup (finish()) to process_audio_dg tests. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Second call to finish() is a no-op. Prevents double-close of underlying DG connection if finish() is called concurrently or from multiple teardown paths. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Reviewer feedback: test finish() double-call safety and background thread keepalive exception → dead detection path. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Reviewer feedback: 50ms sleeps can flake under CI load. Increase to 100ms for more reliable background thread timing assertions. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Separate the is_connection_dead check from audio routing so that deepgram_profile_socket still receives audio when the main socket dies. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Match 100ms margin used in test_streaming_deepgram_backoff.py for CI stability. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Review Round 2 — FixesIssue 1 (Medium): Dead-socket check could drop audio to Fix: Separated the dead-check from routing. Added fallback Issue 2 (Low): Two Fix: Increased both to 100ms, matching All 133 tests pass. by AI for @beastoin |
- Concurrent send + keepalive thread safety stress test - Exact threshold boundary test - Repeated idle multiple keepalives test - send/finalize after finish are no-ops - Profile socket routing when main socket dies Co-Authored-By: Claude Opus 4.6 <[email protected]>
…#5870) Co-Authored-By: Claude Opus 4.6 <[email protected]>
CP8.1 — Test Detail Table
CP9 — Changed-Path Coverage Checklist
by AI for @beastoin |
All checkpoints passed — PR ready for mergeCP7 Reviewer approved (round 4, Codex L1 SynthesisAll changed paths (P1-P14) proven via unit tests and standalone module verification. Auto-keepalive thread lifecycle (start→idle→keepalive→finish→stop), dead detection (send False, keepalive False, exceptions), thread safety under contention, boundary conditions (exact threshold, repeated idle, post-finish no-op), and profile socket fallback routing all verified. No untested paths. L2 SynthesisBackend boots with PR code (uvicorn startup confirmed), WebSocket listen endpoint reachable. No API surface changes — app does not need rebuilding. Integration verified via module import chain and server health. No untested paths. Awaiting human merge approval. by AI for @beastoin |
…#5870) (BasedHardware#5871) ## Summary Refactors DG WebSocket keepalive to be owned exclusively by `SafeDeepgramSocket`'s background daemon thread (BasedHardware#5870). ### Architecture - **SafeDeepgramSocket** (`utils/stt/safe_socket.py`): New lightweight wrapper with auto-keepalive background thread. Sends keepalive when idle > 5s (configurable via `KeepaliveConfig`). Injectable clock for deterministic testing. - **Dead detection**: One-way latch — when `send()` or `keep_alive()` returns False or raises, connection is permanently marked dead. - **Thread-safe**: Single `threading.Lock` serializes all send/keepalive/finalize/finish operations. - **Eager thread start**: Thread starts in constructor to protect idle windows (e.g., speech profile phase). - **Idempotent `finish()`**: Second call is a no-op; prevents double-close. ### Changes 1. **`utils/stt/safe_socket.py`** (new) — SafeDeepgramSocket with auto-keepalive + KeepaliveConfig 2. **`utils/stt/vad_gate.py`** — Removed `keep_alive()` from GatedDeepgramSocket (sole ownership invariant) 3. **`routers/transcribe.py`** — Simplified stabilization loop (auto-keepalive handles idle), separated dead-check from routing so profile socket still receives audio when main dies 4. **`utils/stt/streaming.py`** — Re-export KeepaliveConfig ### Testing - **138 unit tests pass** (22 backoff tests + 116 vad_gate tests) - Auto-keepalive lifecycle: start, idle detection, send, death, stop - Dead detection: send failure, keepalive failure, exceptions - Thread safety: concurrent send + keepalive contention - Boundary tests: exact threshold, repeated idle, post-finish no-op - Profile socket routing: main dies → profile still receives audio - KeepaliveConfig validation ### Risks / Edge Cases - Background thread per DG connection (daemon, lightweight — ~0.1ms per check cycle) - `needs_keepalive()` / `record_keepalive()` in VADStreamingGate are now dead code (harmless, can clean up later) - Pre-existing `test_llm_usage_endpoints.py` import failure (soniox_util) — unrelated Closes BasedHardware#5870 ## Test Plan - [x] 138 unit tests pass - [x] Backend boots with PR code (uvicorn startup confirmed) - [x] WebSocket listen endpoint reachable (HTTP 403 = auth working) - [x] Module import verification (SafeDeepgramSocket, KeepaliveConfig) - [x] Standalone keepalive thread lifecycle verified (start → idle → keepalive → finish → stop) - [x] Dead detection verified (send False, keepalive False, exceptions) - [x] Profile socket routing when main dies verified - [x] Codex reviewer approved (round 4) - [x] Codex tester approved (round 3) 🤖 Generated with [Claude Code](https://claude.com/claude-code)
…Hardware#5870) (BasedHardware#5871)" This reverts commit 94971c2, reversing changes made to 70f1b78.


Summary
Refactors DG WebSocket keepalive to be owned exclusively by
SafeDeepgramSocket's background daemon thread (#5870).Architecture
utils/stt/safe_socket.py): New lightweight wrapper with auto-keepalive background thread. Sends keepalive when idle > 5s (configurable viaKeepaliveConfig). Injectable clock for deterministic testing.send()orkeep_alive()returns False or raises, connection is permanently marked dead.threading.Lockserializes all send/keepalive/finalize/finish operations.finish(): Second call is a no-op; prevents double-close.Changes
utils/stt/safe_socket.py(new) — SafeDeepgramSocket with auto-keepalive + KeepaliveConfigutils/stt/vad_gate.py— Removedkeep_alive()from GatedDeepgramSocket (sole ownership invariant)routers/transcribe.py— Simplified stabilization loop (auto-keepalive handles idle), separated dead-check from routing so profile socket still receives audio when main diesutils/stt/streaming.py— Re-export KeepaliveConfigTesting
Risks / Edge Cases
needs_keepalive()/record_keepalive()in VADStreamingGate are now dead code (harmless, can clean up later)test_llm_usage_endpoints.pyimport failure (soniox_util) — unrelatedCloses #5870
Test Plan
🤖 Generated with Claude Code