diff --git a/backend/src/backend/services/transcription/__init__.py b/backend/src/backend/services/transcription/__init__.py index cd9585df..3d4ddce5 100644 --- a/backend/src/backend/services/transcription/__init__.py +++ b/backend/src/backend/services/transcription/__init__.py @@ -944,16 +944,29 @@ async def process_audio_chunk( return None async def end_stream(self, stream_id: str) -> dict: - if stream_id not in self._streams: + # Unregister first so no exit path below can leak the stream entry. + stream = self._streams.pop(stream_id, None) + if stream is None: return {"text": "", "words": [], "segments": []} - ws = self._streams[stream_id]["ws"] + ws = stream["ws"] ops = self.model.operations or {} - pending = self._streams[stream_id].get("pending_audio") - if pending: - await ws.send(bytes(pending)) - pending.clear() + pending = stream.get("pending_audio") end_msg = (ops.get("end", {}) or {}).get("message", {"type": "stop"}) - await ws.send(json.dumps(end_msg)) + try: + if pending: + await ws.send(bytes(pending)) + pending.clear() + await ws.send(json.dumps(end_msg)) + except websockets.exceptions.ConnectionClosed as e: + # The provider already closed the socket, e.g. Deepgram's idle + # timeout (NET-0001) after ~10 s without audio. Finals that arrived + # before the close were already published; nothing is left to flush. + logger.warning( + f"Provider closed stream {stream_id} before it ended " + f"(code={e.rcvd.code if e.rcvd else None}, " + f"reason={e.rcvd.reason if e.rcvd else ''})" + ) + return {"text": "", "words": [], "segments": []} expect = ops.get("expect", {}) or {} final_type = expect.get("final_type") @@ -978,8 +991,6 @@ async def end_stream(self, stream_id: str) -> dict: except Exception: pass - self._streams.pop(stream_id, None) - if not isinstance(final, dict): return {"text": "", "words": [], "segments": []} segments = ( diff --git a/backend/tests/test_streaming_end_stream_closed.py b/backend/tests/test_streaming_end_stream_closed.py new file mode 100644 index 00000000..b8a57cb7 --- /dev/null +++ b/backend/tests/test_streaming_end_stream_closed.py @@ -0,0 +1,52 @@ +"""Ending a stream whose provider socket already closed. + +Deepgram closes an idle stream (NET-0001) after about 10 seconds without audio. +When the session then ends, the CloseStream send hits a dead socket. That must +end the stream cleanly, not raise and leave the stream registered. +""" + +import pytest +from websockets.exceptions import ConnectionClosedError +from websockets.frames import Close + +from backend.services.transcription import RegistryStreamingTranscriptionProvider + +IDLE_CLOSE = Close( + 1011, "Deepgram did not receive audio data within the timeout window." +) + + +class ClosedSocket: + def __init__(self): + self.closed_called = False + + async def send(self, _payload): + raise ConnectionClosedError(IDLE_CLOSE, IDLE_CLOSE, rcvd_then_sent=True) + + async def recv(self): + raise ConnectionClosedError(IDLE_CLOSE, IDLE_CLOSE, rcvd_then_sent=True) + + async def close(self): + self.closed_called = True + + +def _provider_with(ws, pending=b""): + provider = object.__new__(RegistryStreamingTranscriptionProvider) + provider.model = type( + "Model", (), {"operations": {"end": {"message": {"type": "CloseStream"}}}} + )() + provider._streams = {"s1": {"ws": ws, "pending_audio": bytearray(pending)}} + return provider + + +@pytest.mark.parametrize("pending", [b"", b"\x00" * 64]) +async def test_end_stream_on_provider_closed_socket_returns_empty_and_unregisters( + pending, +): + ws = ClosedSocket() + provider = _provider_with(ws, pending) + + result = await provider.end_stream("s1") + + assert result == {"text": "", "words": [], "segments": []} + assert "s1" not in provider._streams