omi icon indicating copy to clipboard operation
omi copied to clipboard

Python SDK: Deepgram reconnect hangs on normal close and leaves orphaned stream tasks

Open mcalbyrne opened this issue 2 months ago • 3 comments

In the Python SDK, DeepgramTranscriber.run() in sdks/python/omi/stt/deepgram.py can stop reconnecting after a normal WebSocket close while the audio queue is idle. A receive exception also leaves the previous sender waiting on the shared audio queue, and a send exception leaves the previous receiver running. The cause is await asyncio.gather(send_audio(), receive()): normal receive completion does not finish the endless sender, and an exception does not cancel its sibling.

I reproduced this against source blob fbb0da9626d804425d5a9058992a307a520a7d47 (the local baseline's Git blob hash was verified). On Python 3.13.5 / websockets 16.0, six new hermetic regression cases give 4 failed, 2 passed before the fix and 6 passed after. A separate real loopback WebSocket test with normal close code 1000 also confirms the defect: upstream stays on one connection and never resumes while idle; the patch reconnects and delivers the next audio chunk. No real provider, credentials, user audio or paid API calls were used.

The minimal tested change explicitly owns both connection tasks, waits for either to finish, and cancels/awaits both before retry. No public API or dependency change. I have prepared the patch, six tests and reproducible evidence. Full repository preflight/CI, physical hardware and live Deepgram have not been run; this is not a production-validation claim.

Bounty proposal: this work was prepared with an AI coding assistant on behalf of this GitHub account. Following the contribution guide's invitation to propose new bounties, would @josancamon19 consider a US$10 PayPal bounty if the fix is accepted and merged under the normal contribution process? No bounty approval or payment is assumed. Payment details would be shared only through your documented private claim channel, never in this issue.


Inline review material — 7 September 2026

To make the report directly reviewable, here is the minimal diff and a standalone real-WebSocket reproduction. These are supplied for review, not as a substitute for the project's PR/preflight process. No additional bounty is requested.

The current source was fetched again and its Git blob still matches fbb0da9626d804425d5a9058992a307a520a7d47. A fresh supplementary six-case suite executing that actual module (with only the transport and retry delay substituted) again produced 4 failures / 2 passes before; 6 passes after. The four failures cover idle normal EOF, receive exceptions, JSON decode exceptions, and callback exceptions; the passing controls cover normal audio/transcript delivery and parent cancellation. The following independent loopback script also passed its before/after checks. git apply --check and byte-for-byte equality of the applied patch with the tested patched module passed.

Minimal lifecycle diff

Save as deepgram-lifecycle.patch. Its SHA-256 is 60ee7425dbecd19b314cca41b37cfa99f4e69b1fed25f1c1f683813369dec39f.

--- a/sdks/python/omi/stt/deepgram.py
+++ b/sdks/python/omi/stt/deepgram.py
@@ -48,7 +48,24 @@
                                 else:
                                     print(alt)
 
-                    await asyncio.gather(send_audio(), receive())
+                    tasks = (
+                        asyncio.create_task(send_audio()),
+                        asyncio.create_task(receive()),
+                    )
+                    try:
+                        done, _ = await asyncio.wait(
+                            tasks, return_when=asyncio.FIRST_COMPLETED
+                        )
+                        for task in done:
+                            task.result()
+                        # A clean receive EOF must also trigger the retry loop.
+                        raise ConnectionError("Deepgram connection closed")
+                    finally:
+                        # A connection owns both loops. Drain its tasks before
+                        # reconnecting so old senders cannot consume new audio.
+                        for task in tasks:
+                            task.cancel()
+                        await asyncio.gather(*tasks, return_exceptions=True)
             except Exception as exc:
                 print(f"Deepgram error: {exc}")
                 await asyncio.sleep(1)
Standalone loopback reproduction

Save the script below as reproduce.py and run it with a path to the original or patched deepgram.py. It requires the websockets package; the executed environment was Python 3.13.5 / websockets 16.0. It imports the actual source module, replaces only its connection destination, and uses a real server on 127.0.0.1. The synthetic key is never forwarded, and the only payload is two synthetic bytes. The first connection closes normally with code 1000 while the audio queue remains empty. The 1.5-second observation window includes the existing one-second retry delay.

"""python reproduce.py /path/to/sdks/python/omi/stt/deepgram.py
Requires websockets; makes only loopback connections and sends synthetic bytes.
"""
import asyncio
import contextlib
import importlib.util
import json
import sys
from unittest.mock import patch
import websockets


async def main():
    spec = importlib.util.spec_from_file_location('target', sys.argv[1])
    target = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(target)
    count, received = 0, []
    second, delivered = asyncio.Event(), asyncio.Event()
    queue = asyncio.Queue()

    async def handler(ws):
        nonlocal count
        count += 1
        if count == 1:
            await ws.close(code=1000)
            return
        second.set()
        try:
            received.append((await ws.recv()).hex())
            delivered.set()
            await ws.wait_closed()
        except websockets.ConnectionClosed:
            pass

    real_connect = websockets.connect
    async with websockets.serve(handler, '127.0.0.1', 0) as server:
        port = server.sockets[0].getsockname()[1]
        def connect_locally(_url, **_kwargs):
            return real_connect(f'ws://127.0.0.1:{port}')
        with patch('websockets.connect', connect_locally):
            task = asyncio.create_task(
                target.DeepgramTranscriber('LOCAL-FAKE-KEY').run(queue))
            try:
                try:
                    await asyncio.wait_for(second.wait(), 1.5)
                    reconnected = True
                except TimeoutError:
                    reconnected = False
                idle_count = count
                if reconnected:
                    await queue.put(b'\x00\x01')
                    await asyncio.wait_for(delivered.wait(), 1)
                print(json.dumps({'connections_while_idle': idle_count,
                                  'reconnected': reconnected,
                                  'received_hex': received}))
            finally:
                task.cancel()
                with contextlib.suppress(asyncio.CancelledError):
                    await task


if __name__ == '__main__':
    asyncio.run(main())

Observed original result:

{"connections_while_idle": 1, "reconnected": false, "received_hex": []}

Observed patched result (after the expected Deepgram error: Deepgram connection closed retry log):

{"connections_while_idle": 2, "reconnected": true, "received_hex": ["0001"]}

This establishes the idle normal-close regression locally; it does not claim live Deepgram compatibility, hardware validation, exhaustive cancellation interleavings, or full repository CI. Prepared and executed by an AI coding assistant on this account's behalf.

mcalbyrne avatar Sep 07 '26 21:09 mcalbyrne

Submitted a fix for this issue in PR #13083: https://github.com/BasedHardware/omi/pull/13083

  • Replaced asyncio.gather(send_audio(), receive()) with explicit task creation and asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED).
  • On normal close (EOF), raises ConnectionError("Deepgram connection closed") so that the outer while True: loop triggers reconnect and throttle sleep cleanly.
  • In finally:, cancels both tasks and drains with await asyncio.gather(*tasks, return_exceptions=True) to prevent orphaned tasks from consuming audio intended for subsequent connections.
  • Added 6 hermetic lifecycle unit tests in sdks/python/tests/test_deepgram_lifecycle.py covering normal close, retry reconnection, send/receive errors, callback exceptions, and caller cancellation.
  • All 13 SDK unit tests and repository pr-preflight manifest checks pass.

Aj2280 avatar Sep 08 '26 09:09 Aj2280

Hi @mcalbyrne @josancamon19 @Git-on-my-level,

Following up on the attribution question:

Full credit to @mcalbyrne for the lifecycle fix design published here in #12945. I packaged the fix with a comprehensive hermetic test suite (13/13 passing tests) and repository preflight checks into PR #13083 to help land it into main.

I've credited @mcalbyrne in PR #13083 and defer completely to @josancamon19 on how to handle the allocation of the proposed $10 bounty. Glad to collaborate on this fix!

Aj2280 avatar Sep 08 '26 12:09 Aj2280

Hi @josancamon19 and @kodjima33,

Now that PR #13083 has been merged into main, could you please confirm if the proposed bounty for this contribution is approved?

Once approved, I will submit my claim details to [email protected] as per the contribution guidelines. Thank you!

Aj2280 avatar Sep 10 '26 07:09 Aj2280