Repository navigation
Add close-reason logging for DG WebSocket disconnects (#5870) - #6036
Conversation
Capture WHY DG connections die instead of just that they died. - death_reason property: stores exception type + message on send/keepalive failure - set_close_reason(): external callers (DG on_close/on_error) can feed close info - First reason wins (one-way latch — root cause preserved) Part of DG close-reason logging for #5870. Co-Authored-By: Claude Opus 4.6 <[email protected]>
After wrapping with SafeDeepgramSocket, register additional on_close and on_error handlers on the DG connection that call set_close_reason(). This captures DG-side close events before they reach SafeDeepgramSocket's send/keepalive dead detection. Part of DG close-reason logging for #5870. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Delegates to SafeDeepgramSocket.death_reason so transcribe.py can access close reason through the GatedDeepgramSocket wrapper. Part of DG close-reason logging for #5870. Co-Authored-By: Claude Opus 4.6 <[email protected]>
When SafeDeepgramSocket detects a dead connection, include the death_reason in the error log so operators can immediately see if it was a DG server close, network drop, timeout, etc. Part of DG close-reason logging for #5870. Co-Authored-By: Claude Opus 4.6 <[email protected]>
7 new tests covering: - death_reason None when alive - death_reason on send False / exception - death_reason on keepalive False / exception - set_close_reason stores first reason only - set_close_reason doesn't override send death Co-Authored-By: Claude Opus 4.6 <[email protected]>
Greptile SummaryThis PR adds structured close-reason logging to Key changes:
Issues found:
Confidence Score: 3/5
Important Files Changed
Sequence DiagramsequenceDiagram
participant DG as Deepgram Server
participant SDK as DG SDK Callbacks
participant Safe as SafeDeepgramSocket
participant VAD as GatedDeepgramSocket
participant TX as transcribe.py
Note over DG,TX: Normal close path (server-initiated)
DG-->>SDK: Close frame
SDK->>Safe: on_dg_close(close)
Safe->>Safe: set_close_reason("DG close event: ...")
Note over Safe: _death_reason set, _dg_dead still False
TX->>VAD: send(audio_chunk)
VAD->>Safe: send(audio_chunk)
Safe->>DG: _conn.send(data) → returns False
Safe->>Safe: _death_reason = "send returned False" ⚠️ overwrites!
Safe->>Safe: _dg_dead = True
TX->>VAD: is_connection_dead → True
VAD->>Safe: death_reason
Safe-->>TX: "send returned False" (DG close reason lost)
TX->>TX: logger.error("DG connection died ... reason=send returned False")
Note over DG,TX: Ideal path after fix (if None guard added)
TX->>TX: logger.error("DG connection died ... reason=DG close event: CloseResponse(...)")
Reviews (1): Last reviewed commit: "Add tests for death_reason and set_close..." | Re-trigger Greptile |
| @@ -114,14 +122,26 @@ def send(self, data: bytes) -> None: | |||
| try: | |||
| ret = self._conn.send(data) | |||
| if ret is False: | |||
| self._death_reason = 'send returned False' | |||
| logger.warning('DG send returned False, connection dead') | |||
| self._dg_dead = True | |||
| else: | |||
| self._last_activity = self._clock() | |||
| except Exception: | |||
| logger.warning('DG send exception, connection dead') | |||
| except Exception as e: | |||
| self._death_reason = f'send {type(e).__name__}: {e}' | |||
| logger.warning('DG send exception, connection dead: %s: %s', type(e).__name__, e) | |||
| self._dg_dead = True | |||
There was a problem hiding this comment.
send() / _send_keepalive_locked() unconditionally overwrite _death_reason
The PR description says "First reason wins" and set_close_reason() correctly implements a no-op when a reason is already recorded. However, send() (line 125/131) and _send_keepalive_locked() (lines 91/98) assign to self._death_reason unconditionally — they will silently overwrite any reason previously stored by set_close_reason.
The most common real-world sequence is:
- DG server sends a close frame →
on_dg_closefires →set_close_reason("DG close event: CloseResponse(…)")stores the informative reason. - The next audio chunk arrives and
send()is called on the now-closed connection → returnsFalse→self._death_reason = 'send returned False'overwrites the DG close reason.
After this, the log in transcribe.py will show reason=send returned False instead of reason=DG close event: CloseResponse(…), defeating the main purpose of this PR.
The fix is to add the same if self._death_reason is None: guard used by set_close_reason:
# in send():
if ret is False:
if self._death_reason is None:
self._death_reason = 'send returned False'
...
except Exception as e:
if self._death_reason is None:
self._death_reason = f'send {type(e).__name__}: {e}'
...
# in _send_keepalive_locked():
if ret is False:
if self._death_reason is None:
self._death_reason = 'keep_alive returned False'
...
except Exception as e:
if self._death_reason is None:
self._death_reason = f'keep_alive {type(e).__name__}: {e}'
...Note that test_set_close_reason_does_not_override_send_death covers only the reverse direction (send fails first, set_close_reason called after). There is no test for the scenario above (close event first, send failure second), which is why this slipped through.
| # Register close-reason handlers that feed into SafeDeepgramSocket | ||
| def on_dg_close(self, close, **kwargs): | ||
| reason = f'DG close event: {close}' | ||
| logger.info('Deepgram connection closed: %s', close) | ||
| safe_conn.set_close_reason(reason) | ||
|
|
||
| def on_dg_error(self, error, **kwargs): | ||
| reason = f'DG error event: {error}' | ||
| logger.warning('Deepgram error (close-reason capture): %s', error) | ||
| safe_conn.set_close_reason(reason) | ||
|
|
||
| dg_connection.on(LiveTranscriptionEvents.Close, on_dg_close) | ||
| dg_connection.on(LiveTranscriptionEvents.Error, on_dg_error) |
There was a problem hiding this comment.
Duplicate log entries on every Error and Close event
Two separate handlers are now registered for both LiveTranscriptionEvents.Error and LiveTranscriptionEvents.Close, causing each event to produce two log lines.
Error events:
on_error(registered insideconnect_to_deepgramviaconnect_to_deepgram_with_backoff, line ~472) logs:ERROR "Deepgram error: {error}"on_dg_error(new, line 405–408) logs:WARNING "Deepgram error (close-reason capture): {error}"
Close events:
- The existing
on_closeinconnect_to_deepgram(line ~486–487) logs:INFO "Connection Closed" on_dg_close(new, line 400–403) logs:INFO "Deepgram connection closed: {close}"
Since the original on_error/on_close handlers already emit the event details, the new handlers could drop their logger.* calls and only call set_close_reason. This halves the log noise without losing any information:
def on_dg_close(self, close, **kwargs):
safe_conn.set_close_reason(f'DG close event: {close}')
def on_dg_error(self, error, **kwargs):
safe_conn.set_close_reason(f'DG error event: {error}')…#6036) CODEx review found that send() and _send_keepalive_locked() unconditionally overwrote _death_reason, breaking the first-reason-wins contract when a DG close/error callback had already set the reason. Now all write paths guard with `if self._death_reason is None` before setting. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Two new tests verify that set_close_reason() is preserved when send() or keepalive subsequently fails — the reverse of the existing test_set_close_reason_does_not_override_send_death. Co-Authored-By: Claude Opus 4.6 <[email protected]>
… permutations (#6036) Closes 3 coverage gaps from CP8 tester: 1. DG callback wiring: verify process_audio_dg registers Close/Error handlers and invoking them sets death_reason on SafeDeepgramSocket 2. Gated socket delegation: verify GatedDeepgramSocket.death_reason delegates to SafeDeepgramSocket (and returns None for non-safe sockets) 3. Exception permutations: close-reason-first then send/keepalive exception (completes the first-reason-wins matrix) Co-Authored-By: Claude Opus 4.6 <[email protected]>
All checkpoints passed — ready for merge
Changed-path coverage
Deployment: by AI for @beastoin |
dg_socket is always SafeDeepgramSocket or GatedDeepgramSocket, both of which have death_reason. No need for defensive getattr. Co-Authored-By: Claude Opus 4.6 <[email protected]>
_conn is always SafeDeepgramSocket (streaming.py guarantees this), so the getattr/_is_safe_dg_socket guard is unnecessary. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Replace non-safe-socket fallback test with alive-state delegation test, matching the simplified GatedDeepgramSocket.death_reason. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Closes 2 tester gaps: 1. DG Error handler assertion (not just Close) in callback wiring test 2. Keepalive-first then set_close_reason reverse direction test Co-Authored-By: Claude Opus 4.6 <[email protected]>
Updated Evidence — 39/39 tests, getattr removed, 5 files changedTest results (all 39 pass)Commits (12 total)
Changed files (5 files, +405 / -6)
Changed-path coverage (updated)
Key design decisions
5-minute live audio test running next. by AI for @beastoin |
L1 Integration Test Evidence — Close-reason code path fires on DG closeSetup
DG API key expired — but this exercises the close-reason pathThe local DG API key is expired. DG connects, immediately closes with "keepalive ping timeout", which actually exercises the exact code path this PR adds:
Backend log evidence (close handlers firing)What this proves
5-minute test blockedA 5-minute audio test requires a valid DG API key. Options:
Unit test coverage (primary evidence)by AI for @beastoin |
5-Minute Live Audio Test — SafeDeepgramSocket with Real DeepgramSetup
Results — 300s, 81 transcripts, death_reason capturedKey observations
Transcript samplesWhat this proves (mapped to changed paths)
Verdict: PASSAll PR code paths verified with real DG connection over 5 minutes. by AI for @beastoin |
…BasedHardware#6036) CODEx review found that send() and _send_keepalive_locked() unconditionally overwrote _death_reason, breaking the first-reason-wins contract when a DG close/error callback had already set the reason. Now all write paths guard with `if self._death_reason is None` before setting. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Two new tests verify that set_close_reason() is preserved when send() or keepalive subsequently fails — the reverse of the existing test_set_close_reason_does_not_override_send_death. Co-Authored-By: Claude Opus 4.6 <[email protected]>
… permutations (BasedHardware#6036) Closes 3 coverage gaps from CP8 tester: 1. DG callback wiring: verify process_audio_dg registers Close/Error handlers and invoking them sets death_reason on SafeDeepgramSocket 2. Gated socket delegation: verify GatedDeepgramSocket.death_reason delegates to SafeDeepgramSocket (and returns None for non-safe sockets) 3. Exception permutations: close-reason-first then send/keepalive exception (completes the first-reason-wins matrix) Co-Authored-By: Claude Opus 4.6 <[email protected]>
…rdware#6036) dg_socket is always SafeDeepgramSocket or GatedDeepgramSocket, both of which have death_reason. No need for defensive getattr. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…rdware#6036) _conn is always SafeDeepgramSocket (streaming.py guarantees this), so the getattr/_is_safe_dg_socket guard is unnecessary. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ardware#6036) Replace non-safe-socket fallback test with alive-state delegation test, matching the simplified GatedDeepgramSocket.death_reason. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Closes 2 tester gaps: 1. DG Error handler assertion (not just Close) in callback wiring test 2. Keepalive-first then set_close_reason reverse direction test Co-Authored-By: Claude Opus 4.6 <[email protected]>
…5870) (BasedHardware#6036) ## Summary When a Deepgram WebSocket connection dies, we now capture and log **why** — not just that it died. This enables operators to distinguish DG server closures, network drops, idle timeouts, and billing limits from Cloud Logging. ### Problem SafeDeepgramSocket (PR BasedHardware#5944) detects dead connections but swallows the close reason. The `except Exception` blocks log generic "connection dead" without the exception type or message. Current prod error rate (~60/hr at peak) cannot be triaged because all disconnects look the same. ### Changes | File | Change | |------|--------| | `utils/stt/safe_socket.py` | `death_reason` property + `set_close_reason()` method. First-reason-wins latch on ALL write paths (send, keepalive, external close). | | `utils/stt/streaming.py` | Register `on_close` / `on_error` handlers on DG connection that feed into `safe_conn.set_close_reason()` | | `utils/stt/vad_gate.py` | `GatedDeepgramSocket.death_reason` delegates to SafeDeepgramSocket | | `routers/transcribe.py` | "DG connection died mid-session" log now includes `reason=` field | | `tests/unit/test_streaming_deepgram_backoff.py` | 14 new tests (37 total) for death_reason, set_close_reason, callback wiring, delegation | ### How it works 1. **SafeDeepgramSocket** captures exception details when `send()` or `keep_alive()` fails: - `send ConnectionResetError: Connection reset by peer` - `keep_alive TimeoutError: timed out` - `send returned False` 2. **DG SDK callbacks** feed close events into SafeDeepgramSocket via `set_close_reason()`: - `DG close event: CloseResponse(type='Close')` - `DG error event: ErrorResponse(...)` 3. **First reason wins** — ALL write paths guard with `if self._death_reason is None`. The first close event is the root cause; subsequent failures are no-ops. 4. **transcribe.py** includes the reason in the operator-facing log: ``` DG connection died mid-session uid=abc session=xyz reason=send ConnectionResetError: Connection reset by peer ``` ### Example Cloud Logging queries after deploy ``` # See all disconnect reasons "DG connection died mid-session" "reason=" # Network issues (code 1006 = abnormal) "reason=" "ConnectionResetError" # DG server errors "reason=" "DG error event" # Keepalive failures specifically "reason=" "keep_alive" ``` ### Review cycle - **CODEx review (R1)**: Found first-reason-wins bug — `send()`/`_send_keepalive_locked()` unconditionally overwrote `_death_reason`. Fixed with `if None` guard on all write paths. - **CODEx review (R2)**: Approved (`PR_APPROVED_LGTM`). Thread safety confirmed, PII risk low. - **Tester (T1)**: Found 3 coverage gaps: (1) DG callback wiring untested, (2) gated delegation untested, (3) exception permutations incomplete. - **Tester (T2)**: Approved (`TESTS_APPROVED`). All 3 gaps closed with 5 new tests. ### Testing - 37 tests passing (23 existing + 14 new) - Coverage: death_reason lifecycle, exception capture, first-reason-wins matrix (all orderings), DG callback wiring, gated delegation, non-safe socket fallback ## Deployment **Services affected**: `backend-listen` **No env vars needed** **Risk**: Low — logging-only change, no behavior change Relates to BasedHardware#5870 _by AI for @beastoin_
Summary
When a Deepgram WebSocket connection dies, we now capture and log why — not just that it died. This enables operators to distinguish DG server closures, network drops, idle timeouts, and billing limits from Cloud Logging.
Problem
SafeDeepgramSocket (PR #5944) detects dead connections but swallows the close reason. The
except Exceptionblocks log generic "connection dead" without the exception type or message. Current prod error rate (~60/hr at peak) cannot be triaged because all disconnects look the same.Changes
utils/stt/safe_socket.pydeath_reasonproperty +set_close_reason()method. First-reason-wins latch on ALL write paths (send, keepalive, external close).utils/stt/streaming.pyon_close/on_errorhandlers on DG connection that feed intosafe_conn.set_close_reason()utils/stt/vad_gate.pyGatedDeepgramSocket.death_reasondelegates to SafeDeepgramSocketrouters/transcribe.pyreason=fieldtests/unit/test_streaming_deepgram_backoff.pyHow it works
SafeDeepgramSocket captures exception details when
send()orkeep_alive()fails:send ConnectionResetError: Connection reset by peerkeep_alive TimeoutError: timed outsend returned FalseDG SDK callbacks feed close events into SafeDeepgramSocket via
set_close_reason():DG close event: CloseResponse(type='Close')DG error event: ErrorResponse(...)First reason wins — ALL write paths guard with
if self._death_reason is None. The first close event is the root cause; subsequent failures are no-ops.transcribe.py includes the reason in the operator-facing log:
Example Cloud Logging queries after deploy
Review cycle
send()/_send_keepalive_locked()unconditionally overwrote_death_reason. Fixed withif Noneguard on all write paths.PR_APPROVED_LGTM). Thread safety confirmed, PII risk low.TESTS_APPROVED). All 3 gaps closed with 5 new tests.Testing
Deployment
Services affected:
backend-listenonlyNo new env vars needed
No migrations needed
Risk: Low — logging-only change, no behavior change to audio/transcription flow
Deployment steps
Trigger prod deploy:
Monitor rollout (wait for pods to be healthy):
Verify deployment — check Cloud Logging for death_reason appearing in disconnect logs:
Post-deploy monitoring (T+1h):
reason=field populated in disconnect logsRelates to #5870
by AI for @beastoin