Skip to content

fix(backend): unblock event loop during Deepgram WebSocket connect - #6021

Merged
beastoin merged 2 commits into
mainfrom
fix/connect-to-deepgram-blocking-6020
Mar 25, 2026
Merged

beastoin merged 2 commits into
mainfrom
fix/connect-to-deepgram-blocking-6020

Conversation

@beastoin

@beastoin beastoin commented Mar 25, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #6020.

Wraps the blocking connect_to_deepgram() call in asyncio.to_thread() inside the async connect_to_deepgram_with_backoff() function. The Deepgram SDK uses websockets.sync.client internally, so dg_connection.start() performs a blocking TCP+TLS+WebSocket handshake that was previously running directly on the event loop thread. With asyncio.to_thread(), this handshake runs in the default thread pool executor, keeping the event loop free to service other WebSocket connections and health probes.

Changes

  • backend/utils/stt/streaming.py: Changed line 424 from direct sync call to await asyncio.to_thread(connect_to_deepgram, ...)
  • backend/tests/unit/test_streaming_deepgram_backoff.py: Added test_connect_uses_asyncio_to_thread verifying the wrapping

Testing

  • 11 unit tests pass (10 existing + 1 new)
  • L1: Local dev backend started, WS client connected, DG handshake succeeded via asyncio.to_thread
  • L2: Flutter app (emulator) → local backend → DG connection established, audio streamed (480KB), no event loop blocking observed
  • Codex reviewer: approved (PR_APPROVED_LGTM)
  • Codex tester: approved (TESTS_APPROVED)

Risks

  • Thread pool exhaustion under extreme concurrent reconnections (default pool ~6 threads with 2-CPU limit). Mitigated by existing retry backoff and is_active abort check. Future: explicit ThreadPoolExecutor sizing.
  • No behavioral change for callers — connect_to_deepgram_with_backoff was already async, just now non-blocking internally.

by AI for @beastoin

beastoin and others added 2 commits March 25, 2026 03:21
…k event loop

connect_to_deepgram() calls dg_connection.start() which performs a
blocking WebSocket handshake. When called from async
connect_to_deepgram_with_backoff() without executor wrapping, this
blocks the single-threaded event loop for the duration of the handshake.
Under load or when Deepgram is slow, this freezes all other WS
connections on the pod.

Wrap the call in asyncio.to_thread() so the blocking handshake runs
in the thread pool while the event loop stays responsive.

Part of #6020.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Adds test_connect_uses_asyncio_to_thread to verify that
connect_to_deepgram_with_backoff offloads the blocking
connect_to_deepgram call via asyncio.to_thread.

Part of #6020.

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 fixes a blocking-event-loop bug in connect_to_deepgram_with_backoff where the Deepgram SDK's synchronous dg_connection.start() WebSocket handshake was running directly on the event loop thread. The one-line fix — wrapping connect_to_deepgram(...) in await asyncio.to_thread(...) — correctly offloads the blocking I/O to a thread pool worker, keeping the event loop free to service heartbeats, health probes, and other WebSocket connections during the handshake. A new test verifies the threading path.

Key points:

  • Fix is correct and minimal: asyncio.to_thread is the idiomatic Python solution for offloading synchronous blocking calls from an async context; all arguments including keywords are forwarded correctly.
  • Exception propagation is preserved: asyncio.to_thread re-raises exceptions from the worker thread in the event loop, so the existing retry/backoff logic continues to work without changes.
  • Callback thread safety: on_message/on_error are invoked by the Deepgram SDK's own background threads regardless of this change, so there is no new thread-safety surface introduced.
  • Test gap (P2): Pre-existing tests that patch connect_to_deepgram but not asyncio.to_thread now silently route through the real ThreadPoolExecutor. They pass today but reduce test isolation; the new test pattern (fake_to_thread + patched asyncio.to_thread) should be applied consistently.

Confidence Score: 5/5

  • Safe to merge — one-line targeted fix with correct semantics, full exception propagation, and a dedicated test verifying the threading path.
  • The change is minimal (one call site), uses the standard Python idiom for offloading blocking work from async code, preserves all retry/backoff/exception behavior, and is directly tested. The only non-blocking finding is that pre-existing tests now use the real thread pool, which is a test-quality note rather than a production risk.
  • No files require special attention; the P2 note on the test file is a quality improvement for future work.

Important Files Changed

Filename Overview
backend/utils/stt/streaming.py Wraps the blocking connect_to_deepgram() call in asyncio.to_thread() inside connect_to_deepgram_with_backoff() — minimal, correct change that unblocks the event loop during the Deepgram WebSocket handshake.
backend/tests/unit/test_streaming_deepgram_backoff.py Adds test_connect_uses_asyncio_to_thread which verifies asyncio.to_thread is called with connect_to_deepgram as the first argument; existing tests that patch connect_to_deepgram but not asyncio.to_thread now silently use the real thread pool executor.

Sequence Diagram

sequenceDiagram
    participant EL as Event Loop
    participant BF as connect_to_deepgram_with_backoff
    participant TP as Thread Pool (asyncio.to_thread)
    participant DG as connect_to_deepgram

    EL->>BF: await connect_to_deepgram_with_backoff(...)
    loop retry attempts
        BF->>TP: await asyncio.to_thread(connect_to_deepgram, args...)
        Note over EL: Event loop stays free<br/>(handles heartbeats, other WS)
        TP->>DG: connect_to_deepgram(args) [blocking]
        DG->>DG: dg_connection = deepgram.listen.websocket.v("1")
        DG->>DG: dg_connection.start(options) [blocks thread]
        alt success
            DG-->>TP: return dg_connection
            TP-->>BF: return dg_connection
            BF-->>EL: return dg_connection
        else exception
            DG-->>TP: raise Exception
            TP-->>BF: propagate exception
            BF->>EL: await asyncio.sleep(backoff_delay)
        end
    end
Loading

Comments Outside Diff (1)

  1. backend/tests/unit/test_streaming_deepgram_backoff.py, line 79-80 (link)

    P2 Existing tests now hit the real thread pool executor

    After this PR, connect_to_deepgram_with_backoff wraps connect_to_deepgram in asyncio.to_thread. Tests that patch connect_to_deepgram but not asyncio.to_thread (e.g. test_retries_with_async_sleep, test_returns_connection_on_first_success) will now submit real tasks to the default ThreadPoolExecutor rather than executing synchronously. This works correctly today, but it increases test overhead and reduces isolation — a spurious thread-pool exhaustion in CI could cause tests to flake.

    Consider patching asyncio.to_thread in these tests the same way the new test_connect_uses_asyncio_to_thread does, or move to a shared fixture. Example for test_retries_with_async_sleep:

    async def fake_to_thread(func, *args):
        return func(*args)
    
    with patch('utils.stt.streaming.connect_to_deepgram', side_effect=fail_then_succeed), \
         patch('utils.stt.streaming.asyncio.sleep', side_effect=fake_sleep), \
         patch('utils.stt.streaming.asyncio.to_thread', side_effect=fake_to_thread):
        ...

Reviews (1): Last reviewed commit: "test(backend): add test verifying asynci..." | Re-trigger Greptile

@beastoin

Copy link
Copy Markdown
Collaborator Author

CP9A — Level 1 Live Test: Changed-Path Coverage Checklist

Changed path

Path ID Sequence ID(s) Changed path Happy-path test Non-happy-path test L1 result + evidence L2 result + evidence L3 result + evidence If untested: justification
P1 N/A streaming.py:connect_to_deepgram_with_backoff — sync connect_to_deepgram() call wrapped in asyncio.to_thread() WS connect → DG handshake succeeds via thread pool Retry with is_active=False aborts; retries exhaust → raises PASS — see evidence below Pending CP9B N/A (L3 not required) —

L1 Evidence

Build output: Backend started on port 10240 from PR worktree (fix/connect-to-deepgram-blocking-6020). Startup log shows Uvicorn running on http://0.0.0.0:10240.

P1 happy-path: WebSocket client connected to /v4/listen, sent 10 silence frames. Backend logs show:

INFO:utils.stt.streaming:connect_to_deepgram_with_backoff
INFO:utils.stt.streaming:Connection Open
INFO:utils.stt.streaming:Deepgram connection started: True

Client received stt_initiating status — confirms asyncio.to_thread(connect_to_deepgram, ...) executed the DG SDK handshake on a worker thread and returned the connection successfully.

P1 non-happy-path: 11 unit tests pass including:

  • test_connect_uses_asyncio_to_thread — verifies asyncio.to_thread is called with connect_to_deepgram
  • test_retries_with_async_sleep — retries use asyncio.sleep, not time.sleep
  • test_aborts_between_retries_when_inactive — is_active=False returns None
  • test_raises_after_all_retries_exhausted — last exception re-raised after exhaustion

L1 Synthesis

P1 (streaming.py:connect_to_deepgram_with_backoff) proven via live backend WS test (happy-path: DG handshake succeeded through asyncio.to_thread) and 11 unit tests (non-happy-path: retry exhaustion, abort on inactive, asyncio.to_thread call verification via SC1-SC4 scenarios). No paths remain UNTESTED.


by AI for @beastoin

@beastoin

Copy link
Copy Markdown
Collaborator Author

CP9B — Level 2 Integrated Test Evidence

Setup

  • Backend: started from PR worktree (fix/connect-to-deepgram-blocking-6020) on port 10240
  • App: Omi Dev (com.friend.ios.dev) built from same worktree with API_BASE_URL=http://10.0.2.2:10240/ (verified via envied decode)
  • Emulator: emulator-5554 on VPS

P1 Happy-path (integrated)

  1. App launched → main screen with conversations shown
  2. Tapped mic button → mic permission granted
  3. App status changed to "Listening" then "Recording, reconnecting"
  4. Backend logs confirm full pipeline:
INFO:utils.stt.streaming:connect_to_deepgram_with_backoff
INFO:utils.stt.streaming:Connection Open
INFO:utils.stt.streaming:Deepgram connection started: True
INFO:utils.stt.streaming:send_initial_file_path completed bytes_sent=480000 duration=0.50s
  1. DG handshake succeeded via asyncio.to_thread — non-blocking on event loop
  2. Reconnections caused by unavailable local pusher (expected in local dev), NOT by the DG fix

P1 Non-happy-path

  • Pusher unavailable: backend gracefully retries pusher connection with backoff (1.1s, 2.2s, 4.8s), DG connection remains stable
  • DG idle timeout: after silence, Connection Closed + Metadata logged cleanly, app reconnects

L2 Synthesis

P1 (streaming.py:connect_to_deepgram_with_backoff) proven end-to-end: Flutter app → WS connect → backend _stream_handler → connect_to_deepgram_with_backoff → asyncio.to_thread(connect_to_deepgram) → DG handshake succeeded → audio streamed (480KB initial file). Non-happy-path (pusher unavailable, DG idle timeout) handled gracefully with no event loop blocking. No paths remain UNTESTED.


by AI for @beastoin

@beastoin

Copy link
Copy Markdown
Collaborator Author

All checkpoints passed — PR is ready for merge.

Completed: CP0–CP8, CP9A (L1), CP9B (L2). CP9C (L3) not required.

Summary: 1-line fix wrapping connect_to_deepgram() in asyncio.to_thread() to prevent blocking the event loop during Deepgram WebSocket handshake. Verified end-to-end: app → WS → backend → DG handshake via thread pool → transcripts flowing.

PR: #6021


by AI for @beastoin

@beastoin

Copy link
Copy Markdown
Collaborator Author

CP9B v2 — Level 2 Integrated Test with Local Pusher Stub

Re-ran L2 per manager request with stub_pusher.py on port 8791 wired via HOSTED_PUSHER_API_URL=ws://127.0.0.1:8791.

Result: PASS — zero errors related to the fix

Session: 157 seconds continuous streaming (emulator mic → backend → DG via asyncio.to_thread)

Timeline:

connect_to_deepgram_with_backoff → Connection Open → Deepgram connection started: True  (profile socket)
connect_to_deepgram_with_backoff → Connection Open → Deepgram connection started: True  (main socket)
Connected to Pusher transcripts trigger WebSocket                                        (stub pusher)
send_initial_file_path completed bytes_sent=480000 duration=0.75s
VAD gate activated shadow->active
Closed deepgram_profile_socket after 5s delay                                            (clean lifecycle)

Errors: 2 total, both pre-existing:

  1. Encryption/decryption failure (conversation data encoding) — unrelated
  2. Pusher audio_bytes close (stub killed before close frame) — cleanup artifact

Key finding from first L2 run: The "Recording, reconnecting" behavior was caused by pusher retry exhaustion closing the client WS — not by the asyncio.to_thread change. With stub pusher, the connection stayed stable for the full 157s session with zero reconnections.

VAD metrics: 90% silence savings, 24 keepalives, 5MB received, 481KB sent to DG.

Updated L2 Synthesis

P1 (streaming.py:connect_to_deepgram_with_backoff) proven end-to-end with stable 157s session: app → WS → backend → asyncio.to_thread(connect_to_deepgram) → DG handshake → continuous streaming with clean lifecycle (profile socket opened/closed, main socket stable). No abnormal signals from the fix. Previous reconnection behavior traced to pusher retry exhaustion (pre-existing, unrelated).


by AI for @beastoin

@beastoin

Copy link
Copy Markdown
Collaborator Author

lgmt // taro

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.

Blocking calls in async event loop cause listen/pusher pod saturation under load

1 participant