From 536f1e178a5b008344ba5723239f331dc3e770fc Mon Sep 17 00:00:00 2001 From: Mark Backman Date: Fri, 6 Mar 2026 21:01:31 -0500 Subject: [PATCH] Fix race condition in Deepgram STT disconnect causing error flood Clear self._connection before sending close stream so run_stt stops sending audio immediately during the WebSocket close handshake. --- src/pipecat/services/deepgram/stt.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/pipecat/services/deepgram/stt.py b/src/pipecat/services/deepgram/stt.py index caa6233b3..17570911a 100644 --- a/src/pipecat/services/deepgram/stt.py +++ b/src/pipecat/services/deepgram/stt.py @@ -594,13 +594,16 @@ class DeepgramSTTService(STTService): return logger.debug("Disconnecting from Deepgram") - # Ask Deepgram to close the stream gracefully before cancelling the task. - if self._connection: - await self._connection.send_close_stream() + # Clear self._connection first to prevent run_stt from sending audio + # during the close handshake, then close gracefully on the saved ref. + connection = self._connection + self._connection = None + + if connection: + await connection.send_close_stream() await self.cancel_task(self._connection_task) self._connection_task = None - self._connection = None async def _connection_handler(self): """Manages the full WebSocket lifecycle inside a single async with block.