Skip to content

Add close-reason logging for DG WebSocket disconnects (#5870) - #6036

Merged
beastoin merged 12 commits into
mainfrom
fix/dg-close-reason-logging-5870
Mar 26, 2026
Merged

beastoin merged 12 commits into
mainfrom
fix/dg-close-reason-logging-5870

Conversation

@beastoin

@beastoin beastoin commented Mar 25, 2026 •

Copy link
Copy Markdown
Collaborator

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 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
  • 5-min live DG test: 300s connection, 81 transcripts, death_reason captured on close

Deployment

Services affected: backend-listen only
No new env vars needed
No migrations needed
Risk: Low — logging-only change, no behavior change to audio/transcription flow

Deployment steps

  1. Trigger prod deploy:

    gh workflow run gcp_backend.yml -f environment=prod -f branch=main
  2. Monitor rollout (wait for pods to be healthy):

    gh run list --workflow=gcp_backend.yml --limit=3
  3. Verify deployment — check Cloud Logging for death_reason appearing in disconnect logs:

    resource.type="k8s_container"
    resource.labels.container_name="backend-listen"
    "DG connection died mid-session" "reason="
    
  4. Post-deploy monitoring (T+1h):

    • Confirm no increase in DG disconnects (this PR only adds logging, no behavior change)
    • Verify reason= field populated in disconnect logs
    • Check pod health: all backend-listen pods Running, no CrashLoopBackOff

Relates to #5870

by AI for @beastoin

beastoin and others added 5 commits March 25, 2026 11:08
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-apps

greptile-apps Bot commented Mar 25, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds structured close-reason logging to SafeDeepgramSocket so operators can distinguish DG server closures, network resets, keepalive timeouts, and billing limits in Cloud Logging — a logging-only change with no behavioral impact on the audio pipeline.

Key changes:

  • safe_socket.py: New _death_reason field, death_reason property, and set_close_reason() method; exception blocks now log type(e).__name__: {e}
  • streaming.py: on_dg_close / on_dg_error callbacks registered on the DG connection feed close events into SafeDeepgramSocket.set_close_reason()
  • vad_gate.py: GatedDeepgramSocket.death_reason delegates to SafeDeepgramSocket via the _is_safe_dg_socket marker
  • transcribe.py: Operator-facing error log now includes reason= field
  • 7 new unit tests covering the death-reason lifecycle

Issues found:

  • send() and _send_keepalive_locked() assign to _death_reason unconditionally, breaking the "first reason wins" contract for the most common production path (DG server closes the connection first → set_close_reason("DG close event: …") is stored → next send() fails → reason is silently overwritten with "send returned False"). The fix is to add if self._death_reason is None: guards in both places, matching set_close_reason()'s own guard.
  • on_dg_error and on_dg_close both emit log lines that duplicate what the pre-existing on_error/on_close handlers in connect_to_deepgram already log, producing two log entries per event.

Confidence Score: 3/5

  • Safe to deploy (logging-only), but the primary goal of capturing informative close reasons is undermined by an overwrite bug in the most common production path.
  • The change is low-risk (no behavioral impact on the audio pipeline), but the core value proposition — knowing why a DG connection died — is compromised for the most common scenario (server-initiated close followed by a failed send). In that path the logged reason will always be "send returned False" rather than the informative "DG close event: CloseResponse(…)". A one-line if self._death_reason is None: guard in send() and _send_keepalive_locked() fixes it. The duplicate log entries are minor but add noise at 60 disconnects/hr.
  • backend/utils/stt/safe_socket.py — the _death_reason assignment in send() and _send_keepalive_locked() needs a None guard to preserve the first-wins semantics.

Important Files Changed

Filename Overview
backend/utils/stt/safe_socket.py Adds _death_reason field, death_reason property, and set_close_reason(). The set_close_reason() correctly implements "first reason wins" with a None guard, but send() and _send_keepalive_locked() still overwrite _death_reason unconditionally, so a DG-initiated close reason can be silently replaced by a subsequent "send returned False".
backend/utils/stt/streaming.py Registers on_dg_close and on_dg_error handlers that feed close reasons into SafeDeepgramSocket. Correct approach, but both handlers add redundant log lines since the existing on_close/on_error handlers (registered in connect_to_deepgram) already log the same events.
backend/utils/stt/vad_gate.py Adds death_reason property that correctly delegates to SafeDeepgramSocket via the existing _is_safe_dg_socket duck-type marker. Clean, consistent with the is_connection_dead delegation pattern.
backend/routers/transcribe.py Uses getattr(dg_socket, 'death_reason', None) or 'unknown' to safely access the new property and include it in the operator-facing error log. Defensive and correct.
backend/tests/unit/test_streaming_deepgram_backoff.py 7 new tests cover the happy path, exception capture, set_close_reason idempotency, and send-first / external-second ordering. Missing a test for the reverse ordering (DG close event first, then send() failure), which is where the overwrite bug manifests.

Sequence Diagram

sequenceDiagram
    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(...)")
Loading

Reviews (1): Last reviewed commit: "Add tests for death_reason and set_close..." | Re-trigger Greptile

Comment thread backend/utils/stt/safe_socket.py Outdated
Comment on lines 91 to 133
@@ -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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. DG server sends a close frame → on_dg_close fires → set_close_reason("DG close event: CloseResponse(…)") stores the informative reason.
  2. The next audio chunk arrives and send() is called on the now-closed connection → returns False → 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.

Comment on lines +399 to +411
# 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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 inside connect_to_deepgram via connect_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_close in connect_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}')

beastoin and others added 3 commits March 25, 2026 11:18
…#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]>
@beastoin

Copy link
Copy Markdown
Collaborator Author

All checkpoints passed — ready for merge

Checkpoint Status Details
CP0-CP6 PASS Implementation complete, PR created
CP7 (reviewer) PASS PR_APPROVED_LGTM — thread safety confirmed, first-reason-wins correct on all write paths
CP8 (tester) PASS TESTS_APPROVED — 37 tests, 3 coverage gaps closed (callback wiring, delegation, exception permutations)
CP9A (L1) PASS 37/37 tests pass, imports verified, runtime behavior correct
CP9B (L2) PASS Integration chain verified: process_audio_dg → SafeDeepgramSocket → DG handlers → death_reason → transcribe.py logging
CP9C (L3) SKIP Not required (logging-only, no cluster/remote deps)

Changed-path coverage

Path Description Tests
P1 keepalive death_reason latch test_death_reason_on_keepalive_false, test_death_reason_on_keepalive_exception
P2 send death_reason latch test_death_reason_on_send_false, test_death_reason_on_send_exception
P3 set_close_reason first-wins test_set_close_reason_stores_first_reason, test_set_close_reason_does_not_override_send_death, + 4 reverse-ordering tests
P4 DG callback wiring test_process_audio_dg_registers_close_error_handlers
P5 Gated delegation test_gated_socket_death_reason_delegates_to_safe_socket, test_gated_socket_death_reason_returns_none_for_non_safe_socket
P6 transcribe.py reason= log test_profile_socket_routing_when_main_dies (exercises same dead-detection path)

Deployment: backend-listen only. No env vars. Logging-only change, no behavior change.

by AI for @beastoin

beastoin and others added 4 commits March 25, 2026 11:41
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]>
@beastoin

Copy link
Copy Markdown
Collaborator Author

Updated Evidence — 39/39 tests, getattr removed, 5 files changed

Test results (all 39 pass)

backend/tests/unit/test_streaming_deepgram_backoff.py    39 passed in 3.56s

Commits (12 total)

Commit Description
08e05fce3 Add death_reason and set_close_reason to SafeDeepgramSocket
ff434fbf8 Register DG close/error handlers that feed into SafeDeepgramSocket
2d0f55cba Expose death_reason through GatedDeepgramSocket
d5fdc5d75 Include close reason in 'DG connection died mid-session' log
a86121be8 Add tests for death_reason and set_close_reason
26ea94bad Fix first-reason-wins: send/keepalive must not overwrite death_reason
d246d8bd9 Add regression tests for first-reason-wins fix
8b72b94ec Add tester-requested coverage: callback wiring, delegation, exception permutations
a56b49c22 Remove unnecessary getattr for death_reason in transcribe.py
0d78b356e Simplify GatedDeepgramSocket.death_reason — always delegates
3c2c2f8e9 Update test: gated delegation always wraps SafeDeepgramSocket
535df9d7f Add Error handler and keepalive-first reverse tests

Changed files (5 files, +405 / -6)

File Change
safe_socket.py +32 — _death_reason field, death_reason property, set_close_reason(), first-reason-wins guards
streaming.py +16 — Register on_dg_close and on_dg_error handlers on DG connection
vad_gate.py +5 — death_reason property delegates directly (no getattr)
transcribe.py +8/-6 — Log reason= in DG-died-mid-session message (direct access, no getattr)
test_streaming_deepgram_backoff.py +350 — 16 new tests covering death_reason lifecycle, first-reason-wins matrix, callback wiring, delegation

Changed-path coverage (updated)

Path ID Changed path Happy-path test Non-happy-path test
P1 safe_socket.py:_send_keepalive_locked — death_reason latch test_death_reason_on_keepalive_false test_death_reason_on_keepalive_exception (TimeoutError)
P2 safe_socket.py:send — death_reason latch test_death_reason_on_send_false test_death_reason_on_send_exception (ConnectionResetError)
P3 safe_socket.py:set_close_reason — first-wins test_set_close_reason_stores_first_reason 6 reverse-ordering tests: close→send, close→keepalive, send→close, keepalive→close, send_raise→close, keepalive_raise→close
P4 streaming.py:on_dg_close/on_dg_error — callback wiring test_process_audio_dg_registers_close_error_handlers test_process_audio_dg_error_handler_sets_death_reason
P5 vad_gate.py:death_reason — gated delegation test_gated_socket_death_reason_delegates_to_safe_socket test_gated_socket_death_reason_delegates_none_when_alive
P6 transcribe.py — reason= log Covered by integration chain (P1-P5 feed into this log line) Same — dead socket + reason flows through

Key design decisions

  • No getattr: Manager confirmed connections are always SafeDeepgramSocket — direct property access used everywhere
  • First-reason-wins: All 4 write paths guard with if self._death_reason is None — DG on_close callback preserves root cause even when send/keepalive fail after
  • Thread-safe: set_close_reason() acquires _lock, same as send/keepalive paths

5-minute live audio test running next.

by AI for @beastoin

@beastoin

Copy link
Copy Markdown
Collaborator Author

L1 Integration Test Evidence — Close-reason code path fires on DG close

Setup

  • Branch fix/dg-close-reason-logging-5870 running on local backend (port 10160)
  • WS connected via ws://localhost:10160/v4/listen with ADMIN_KEY auth

DG API key expired — but this exercises the close-reason path

The local DG API key is expired. DG connects, immediately closes with "keepalive ping timeout", which actually exercises the exact code path this PR adds:

  1. DG SDK fires Close event → on_dg_close handler → safe_conn.set_close_reason('DG close event: ...')
  2. DG SDK fires Error event → on_dg_error handler → safe_conn.set_close_reason('DG error event: ...')

Backend log evidence (close handlers firing)

INFO:utils.stt.streaming:Connection Closed
INFO:utils.stt.streaming:Deepgram connection closed: {
    "type": "Close"
}
INFO:utils.stt.streaming:Metadata: {
    "type": "Metadata",
    "request_id": "4c57543b-4ff9-463b-9008-a753ed1bb6fa",
    "duration": 0.0,
    "channels": 0
}

What this proves

  • on_dg_close handler registered and firing (P4)
  • set_close_reason() called with formatted reason string (P3)
  • SafeDeepgramSocket.finish() runs clean (P1-P2 cleanup)

5-minute test blocked

A 5-minute audio test requires a valid DG API key. Options:

  1. Dev GKE deploy (classified as not required for this logging-only PR)
  2. Update local DG API key

Unit test coverage (primary evidence)

39 passed in 3.56s — all 16 new tests cover death_reason lifecycle,
first-reason-wins matrix, DG callback wiring, and gated delegation

by AI for @beastoin

@beastoin

Copy link
Copy Markdown
Collaborator Author

5-Minute Live Audio Test — SafeDeepgramSocket with Real Deepgram

Setup

  • DG API key from dev GCP secret (valid — verified with GET /v1/projects)
  • SafeDeepgramSocket wraps real DG LiveConnection directly (same code as PR)
  • Audio: 406s WAV, mono 16kHz PCM16, real speech content
  • DG model: nova-2-general, language: en

Results — 300s, 81 transcripts, death_reason captured

Duration: 300.0s
Chunks sent: 3000
Transcripts: 81 (542 words)
DG errors: 0
Keepalives sent: 0 (expected: continuous audio = no idle period > 5s)
Death reason: "DG close event: {"type": "Close"}"

Key observations

  1. Connection survived 5 minutes — SafeDeepgramSocket keepalive thread running, connection stayed alive for full 300s
  2. 81 transcripts received — DG processing audio correctly through SafeDeepgramSocket.send()
  3. death_reason = None before close — no mid-session death (connection healthy throughout)
  4. death_reason captured on finish() — set_close_reason called by on_dg_close handler:
    SafeDeepgramSocket state before close:
      death_reason: None         ← healthy during streaming
    
    Calling safe_conn.finish()...
      set_close_reason: DG close event: {"type": "Close"}
    
    SafeDeepgramSocket state after close:
      death_reason: DG close event: {"type": "Close"}  ← captured!
    
  5. Keepalives = 0 — correct behavior: audio streamed continuously (100ms chunks), so idle threshold (5s) never reached. Unit tests verify keepalive fires during idle.

Transcript samples

First: [8.6s] The development of artificial intelligence has been one of the most transformative technological,
Last:  [300.3s] The research community continues to make progress on

What this proves (mapped to changed paths)

Path Evidence
P1 safe_socket keepalive Thread ran for 300s, connection stayed alive. 0 keepalives correct (no idle)
P2 safe_socket send 3000 chunks sent successfully, is_connection_dead=False throughout
P3 set_close_reason Called on DG Close event, captured "DG close event: {type: Close}"
P4 streaming.py callback wiring on_dg_close handler fired on DG Close, called set_close_reason
P5 death_reason property None during streaming, set after close — lifecycle correct

Verdict: PASS

All PR code paths verified with real DG connection over 5 minutes.

by AI for @beastoin

@beastoin beastoin left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@beastoin
beastoin merged commit 045fe6d into main Mar 26, 2026
2 checks passed
@beastoin
beastoin deleted the fix/dg-close-reason-logging-5870 branch March 26, 2026 07:40
Glucksberg pushed a commit to Glucksberg/omi-local that referenced this pull request Apr 28, 2026
…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]>
Glucksberg pushed a commit to Glucksberg/omi-local that referenced this pull request Apr 28, 2026
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]>
Glucksberg pushed a commit to Glucksberg/omi-local that referenced this pull request Apr 28, 2026
… 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]>
Glucksberg pushed a commit to Glucksberg/omi-local that referenced this pull request Apr 28, 2026
…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]>
Glucksberg pushed a commit to Glucksberg/omi-local that referenced this pull request Apr 28, 2026
…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]>
Glucksberg pushed a commit to Glucksberg/omi-local that referenced this pull request Apr 28, 2026
…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]>
Glucksberg pushed a commit to Glucksberg/omi-local that referenced this pull request Apr 28, 2026
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]>
Glucksberg pushed a commit to Glucksberg/omi-local that referenced this pull request Apr 28, 2026
…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_
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant