From 0abbfe7730653a3e4133bc5764a023e52aa42342 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:12:05 -0800 Subject: [PATCH 1/9] feat(asr): add model parameter to transcribe transcribe() and its async twin take an optional model, sent as the model header (e.g. "transcribe-1-pro"). Without it no header is sent and the request runs on the API's default model, as before. It replaces the RequestOptions(additional_headers={"model": ...}) workaround in the README and docstrings; an explicit model wins over that header. Co-Authored-By: Claude Fable 5.2 --- README.md | 9 +---- src/fishaudio/resources/asr.py | 30 ++++++++------- tests/unit/test_asr.py | 70 ++++++++++++++++++++++++++++++++++ 3 files changed, 88 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 4c44bd6..a442058 100644 --- a/README.md +++ b/README.md @@ -159,14 +159,9 @@ audio = client.tts.stream(text="Hello!").collect() ### Speech-to-Text ```python -from fishaudio.core import RequestOptions - -# transcribe-1-pro is the recommended model. Select it with the model header; -# without it, the request runs on transcribe-1. -pro = RequestOptions(additional_headers={"model": "transcribe-1-pro"}) - +# transcribe-1-pro is the recommended model; without model, the request runs on transcribe-1. with open("meeting.wav", "rb") as f: - result = client.asr.transcribe(audio=f.read(), request_options=pro) + result = client.asr.transcribe(audio=f.read(), model="transcribe-1-pro") # On transcribe-1-pro, text keeps <|speaker:N|> markers; speaker_turns has clean text per speaker. print(result.text) diff --git a/src/fishaudio/resources/asr.py b/src/fishaudio/resources/asr.py index c13a8fc..e8bd93e 100644 --- a/src/fishaudio/resources/asr.py +++ b/src/fishaudio/resources/asr.py @@ -20,6 +20,7 @@ def transcribe( audio: bytes, language: Optional[str] = OMIT, include_timestamps: bool = True, + model: Optional[str] = None, request_options: Optional[RequestOptions] = None, ) -> ASRResponse: """ @@ -30,6 +31,8 @@ def transcribe( language: Language code (e.g., "en", "zh"). Auto-detected if not provided. include_timestamps: Whether to include timestamp information for segments (and speaker turns, on models that return them) + model: ASR model, e.g. "transcribe-1-pro" (recommended). If not provided, + the request runs on the API's default model, transcribe-1 request_options: Request-level overrides Returns: @@ -38,18 +41,13 @@ def transcribe( Example: ```python - from fishaudio.core import RequestOptions - client = FishAudio(api_key="...") with open("audio.mp3", "rb") as f: audio_bytes = f.read() result = client.asr.transcribe( - audio=audio_bytes, - request_options=RequestOptions( - additional_headers={"model": "transcribe-1-pro"} - ), + audio=audio_bytes, model="transcribe-1-pro" ) print(result.text) for segment in result.segments: @@ -67,7 +65,10 @@ def transcribe( response = self._client.request( "POST", "/v1/asr", - headers={"Content-Type": "application/msgpack"}, + headers={ + "Content-Type": "application/msgpack", + **({"model": model} if model is not None else {}), + }, content=ormsgpack.packb(payload), request_options=request_options, ) @@ -88,6 +89,7 @@ async def transcribe( audio: bytes, language: Optional[str] = OMIT, include_timestamps: bool = True, + model: Optional[str] = None, request_options: Optional[RequestOptions] = None, ) -> ASRResponse: """ @@ -98,6 +100,8 @@ async def transcribe( language: Language code (e.g., "en", "zh"). Auto-detected if not provided. include_timestamps: Whether to include timestamp information for segments (and speaker turns, on models that return them) + model: ASR model, e.g. "transcribe-1-pro" (recommended). If not provided, + the request runs on the API's default model, transcribe-1 request_options: Request-level overrides Returns: @@ -106,18 +110,13 @@ async def transcribe( Example: ```python - from fishaudio.core import RequestOptions - client = AsyncFishAudio(api_key="...") async with aiofiles.open("audio.mp3", "rb") as f: audio_bytes = await f.read() result = await client.asr.transcribe( - audio=audio_bytes, - request_options=RequestOptions( - additional_headers={"model": "transcribe-1-pro"} - ), + audio=audio_bytes, model="transcribe-1-pro" ) print(result.text) for segment in result.segments: @@ -135,7 +134,10 @@ async def transcribe( response = await self._client.request( "POST", "/v1/asr", - headers={"Content-Type": "application/msgpack"}, + headers={ + "Content-Type": "application/msgpack", + **({"model": model} if model is not None else {}), + }, content=ormsgpack.packb(payload), request_options=request_options, ) diff --git a/tests/unit/test_asr.py b/tests/unit/test_asr.py index dabc60c..c425bb0 100644 --- a/tests/unit/test_asr.py +++ b/tests/unit/test_asr.py @@ -2,9 +2,11 @@ from unittest.mock import AsyncMock, Mock +import httpx import ormsgpack import pytest +from fishaudio import AsyncFishAudio, FishAudio from fishaudio.core import AsyncClientWrapper, ClientWrapper, RequestOptions from fishaudio.resources.asr import ASRClient, AsyncASRClient from fishaudio.types import ASRResponse @@ -301,3 +303,71 @@ async def test_transcribe_pro_model_response( call_args = async_mock_client_wrapper.request.call_args assert call_args[1]["request_options"] is request_options + + +class TestTranscribeModel: + """The model parameter, checked on the HTTP request that leaves the client.""" + + @staticmethod + def _handler(seen, response): + def handler(request): + seen.append(request) + return httpx.Response(200, json=response) + + return handler + + def test_model_is_sent_as_header(self, sample_asr_response): + seen = [] + http = httpx.Client( + base_url="https://api.test.fish.audio", + transport=httpx.MockTransport(self._handler(seen, sample_asr_response)), + ) + client = FishAudio(api_key="test-key", httpx_client=http) + + client.asr.transcribe(audio=b"fake_audio", model="transcribe-1-pro") + + assert seen[0].headers["model"] == "transcribe-1-pro" + assert seen[0].headers["content-type"] == "application/msgpack" + + def test_no_model_header_by_default(self, sample_asr_response): + seen = [] + http = httpx.Client( + base_url="https://api.test.fish.audio", + transport=httpx.MockTransport(self._handler(seen, sample_asr_response)), + ) + client = FishAudio(api_key="test-key", httpx_client=http) + + client.asr.transcribe(audio=b"fake_audio") + + assert "model" not in seen[0].headers + + def test_model_wins_over_request_options_header(self, sample_asr_response): + seen = [] + http = httpx.Client( + base_url="https://api.test.fish.audio", + transport=httpx.MockTransport(self._handler(seen, sample_asr_response)), + ) + client = FishAudio(api_key="test-key", httpx_client=http) + + client.asr.transcribe( + audio=b"fake_audio", + model="transcribe-1-pro", + request_options=RequestOptions(additional_headers={"model": "other"}), + ) + + assert seen[0].headers["model"] == "transcribe-1-pro" + + async def test_model_is_sent_as_header_async(self, sample_asr_response): + seen = [] + http = httpx.AsyncClient( + base_url="https://api.test.fish.audio", + transport=httpx.MockTransport(self._handler(seen, sample_asr_response)), + ) + client = AsyncFishAudio(api_key="test-key", httpx_client=http) + + await client.asr.transcribe(audio=b"fake_audio", model="transcribe-1-pro") + await client.asr.transcribe(audio=b"fake_audio") + await client.close() + + assert seen[0].headers["model"] == "transcribe-1-pro" + assert "model" not in seen[1].headers From f7337df1b380eda169387b829f6fcb5d51aa3a92 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:12:19 -0800 Subject: [PATCH 2/9] feat(asr): add realtime speech-to-text Wrap wss://api.fish.audio/v1/asr/realtime (transcribe-stream-1, Preview) as client.asr.stream_websocket(), sync and async, in the shape of tts.stream_websocket(): pass an iterator of PCM chunks, iterate typed events (draft, committed, eager_end_of_turn, ...). - The returned ASRRealtimeStream / AsyncASRRealtimeStream also sends control messages during the session: finalize(), agent_speaking(), add_context(), configure(). Control messages can be yielded from the audio iterator too, to keep their position in the audio. - ASRRealtimeConfig mirrors the config message (turn detection, results, context); sample_rate, turn_detection, eager, drafts, diarize and terms are direct parameters that override it. The server adds speaker tags to the text by default; diarize=False removes them. - A non-recoverable error event or an abnormal close raises ASRRealtimeError (a WebSocketError) with error_type, code, request_id and close_code; recoverable errors are yielded as events. A refused upgrade raises the matching APIError (401 -> AuthenticationError). - The connection closes when the session ends, on error, and when the consumer leaves the loop early. The async session runs in its own task, because httpx-ws's task group must be exited by the task that entered it, which an async generator finalized by the event loop cannot guarantee. - When the session ends before the audio does, the sender stops at the next chunk and closes the audio stream if it is a generator (sync: from the sender thread; async: when the sender task is cancelled). A sync audio stream that is blocked cannot be interrupted. - The async session buffers at most 256 events for a slow consumer and then stops reading from the socket. Tests run the real client against a scripted WebSocket server on a local socket, on httpx-ws 0.7 and 0.10. Co-Authored-By: Claude Fable 5.2 --- README.md | 26 +- src/fishaudio/__init__.py | 25 +- src/fishaudio/core/client_wrapper.py | 28 +- src/fishaudio/exceptions.py | 40 + src/fishaudio/resources/asr.py | 289 ++++++- src/fishaudio/resources/asr_realtime.py | 611 ++++++++++++++ src/fishaudio/types/__init__.py | 63 ++ src/fishaudio/types/asr_realtime.py | 518 ++++++++++++ tests/unit/realtime_server.py | 193 +++++ tests/unit/test_asr_realtime.py | 1004 +++++++++++++++++++++++ 10 files changed, 2780 insertions(+), 17 deletions(-) create mode 100644 src/fishaudio/resources/asr_realtime.py create mode 100644 src/fishaudio/types/asr_realtime.py create mode 100644 tests/unit/realtime_server.py create mode 100644 tests/unit/test_asr_realtime.py diff --git a/README.md b/README.md index a442058..44f4d15 100644 --- a/README.md +++ b/README.md @@ -180,6 +180,30 @@ print(result.language_code) # e.g. "en" [Learn more](https://docs.fish.audio/developer-guide/sdk-guide/python/speech-to-text) +**Realtime (Preview):** stream live audio to `transcribe-stream-1` and get the transcript turn by turn. Send 16-bit mono PCM in 20–40 ms chunks as you capture it: + +```python +import wave + +def audio_chunks(): + with wave.open("speech.wav", "rb") as wav: # 16-bit mono PCM, 16 kHz + while chunk := wav.readframes(640): # 40 ms + yield chunk + +# diarize=False gives plain text; by default it starts with a speaker tag: "<|speaker:0|> Hello." +for event in client.asr.stream_websocket( + audio_chunks(), sample_rate=16000, drafts=True, diarize=False +): + if event.type == "draft": # live text of the open turn, not final + print("...", event.text) + elif event.type == "committed": # final transcript of the turn + print(event.text) +``` + +With `AsyncFishAudio`, pass an async iterator and use `async for`. The returned stream also sends control messages during the session, such as `stream.finalize()` for push-to-talk and `stream.agent_speaking(True)` for voice agents. + +[Learn more](https://docs.fish.audio/features/speech-to-text/realtime) + ### Real-time Streaming Stream dynamically generated text for conversational AI and live applications: @@ -253,7 +277,7 @@ audio = client.tts.convert( | Resource | Description | Key Methods | |----------|-------------|-------------| | `client.tts` | Text-to-speech | `convert()`, `stream()`, `stream_websocket()` | -| `client.asr` | Speech recognition | `transcribe()` | +| `client.asr` | Speech recognition | `transcribe()`, `stream_websocket()` | | `client.voices` | Voice management | `list()`, `get()`, `create()`, `update()`, `delete()` | | `client.account` | Account info | `get_credits()`, `get_package()` | diff --git a/src/fishaudio/__init__.py b/src/fishaudio/__init__.py index ce383a2..f067bb0 100644 --- a/src/fishaudio/__init__.py +++ b/src/fishaudio/__init__.py @@ -32,6 +32,7 @@ from .core.websocket_options import WebSocketOptions from .exceptions import ( APIError, + ASRRealtimeError, AuthenticationError, DependencyError, FishAudioError, @@ -42,7 +43,19 @@ ValidationError, WebSocketError, ) -from .types import FlushEvent, ReferenceAudio, TextEvent, TTSConfig +from .resources.asr_realtime import ASRRealtimeStream, AsyncASRRealtimeStream +from .types import ( + ASRContext, + ASRContextItem, + ASRFinalizeEvent, + ASRRealtimeConfig, + ASRResults, + ASRTurnDetection, + FlushEvent, + ReferenceAudio, + TextEvent, + TTSConfig, +) from .utils import play, save, stream # Main exports @@ -57,15 +70,25 @@ # Audio streams "AudioStream", "AsyncAudioStream", + # Realtime speech-to-text sessions + "ASRRealtimeStream", + "AsyncASRRealtimeStream", # Configuration + "ASRContext", + "ASRRealtimeConfig", + "ASRResults", + "ASRTurnDetection", "TTSConfig", "WebSocketOptions", # Types + "ASRContextItem", + "ASRFinalizeEvent", "FlushEvent", "ReferenceAudio", "TextEvent", # Exceptions "APIError", + "ASRRealtimeError", "AuthenticationError", "DependencyError", "FishAudioError", diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index 4164ba2..790e714 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -19,6 +19,21 @@ from .request_options import RequestOptions +def _api_error(status: int, message: str, body: Optional[str] = None) -> APIError: + """Build the exception that matches an HTTP error status.""" + if status == 401: + return AuthenticationError(status, message, body) + if status == 403: + return PermissionError(status, message, body) + if status == 404: + return NotFoundError(status, message, body) + if status == 429: + return RateLimitError(status, message, body) + if status >= 500: + return ServerError(status, message, body) + return APIError(status, message, body) + + def _raise_for_status(response: httpx.Response) -> None: """Raise appropriate exception based on status code.""" status = response.status_code @@ -30,18 +45,7 @@ def _raise_for_status(response: httpx.Response) -> None: except JSONDecodeError: message = response.text or httpx.codes.get_reason_phrase(status) - # Raise specific exception based on status code - if status == 401: - raise AuthenticationError(status, message, response.text) - if status == 403: - raise PermissionError(status, message, response.text) - if status == 404: - raise NotFoundError(status, message, response.text) - if status == 429: - raise RateLimitError(status, message, response.text) - if status >= 500: - raise ServerError(status, message, response.text) - raise APIError(status, message, response.text) + raise _api_error(status, message, response.text) class BaseClientWrapper: diff --git a/src/fishaudio/exceptions.py b/src/fishaudio/exceptions.py index 236dcee..e8ac4ac 100644 --- a/src/fishaudio/exceptions.py +++ b/src/fishaudio/exceptions.py @@ -55,6 +55,46 @@ class WebSocketError(FishAudioError): pass +class ASRRealtimeError(WebSocketError): + """Raised when a realtime speech-to-text session ends with an error. + + Attributes: + message: A short English description, for humans + error_type: Machine-readable error type from the server's error event + (e.g., "invalid_config", "idle_timeout"). None if the connection closed + without one + code: HTTP-style status from the server's error event. None if not sent + request_id: Identifier of the request; quote it when reporting a problem + close_code: WebSocket close code (e.g., 4400, 4408, 1012). None if the error + was raised before the connection closed + """ + + def __init__( + self, + message: str, + *, + error_type: Optional[str] = None, + code: Optional[int] = None, + request_id: Optional[str] = None, + close_code: Optional[int] = None, + ): + self.message = message + self.error_type = error_type + self.code = code + self.request_id = request_id + self.close_code = close_code + details = [ + f"close code {close_code}" if close_code is not None else None, + f"request {request_id}" if request_id else None, + ] + suffix = ", ".join(d for d in details if d) + super().__init__( + (f"{error_type}: " if error_type else "") + + message + + (f" ({suffix})" if suffix else "") + ) + + class ValidationError(FishAudioError): """Raised when request validation fails.""" diff --git a/src/fishaudio/resources/asr.py b/src/fishaudio/resources/asr.py index e8bd93e..d6d0c17 100644 --- a/src/fishaudio/resources/asr.py +++ b/src/fishaudio/resources/asr.py @@ -1,11 +1,62 @@ """ASR (Automatic Speech Recognition) namespace client.""" -from typing import Optional +from collections.abc import AsyncIterable, Iterable +from typing import Optional, Union import ormsgpack +from httpx_ws import aconnect_ws, connect_ws -from fishaudio.core import OMIT, AsyncClientWrapper, ClientWrapper, RequestOptions -from fishaudio.types import ASRResponse +from fishaudio.core import ( + OMIT, + AsyncClientWrapper, + ClientWrapper, + RequestOptions, + WebSocketOptions, +) +from fishaudio.types import ( + ASRContext, + ASRRealtimeConfig, + ASRRealtimeControl, + ASRResponse, + ASRResults, + ASRSampleRate, + ASRTurnDetection, + TurnDetectionMode, +) + +from .asr_realtime import REALTIME_PATH, ASRRealtimeStream, AsyncASRRealtimeStream + + +def _realtime_config( + config: ASRRealtimeConfig, + *, + sample_rate: Optional[ASRSampleRate], + turn_detection: Optional[TurnDetectionMode], + eager: Optional[bool], + drafts: Optional[bool], + diarize: Optional[bool], + terms: Optional[list[str]], +) -> ASRRealtimeConfig: + """Apply direct parameters on top of config (they win when provided).""" + config = config.model_copy(deep=True) + if sample_rate is not None: + config.sample_rate = sample_rate + if turn_detection is not None or eager is not None: + config.turn_detection = config.turn_detection or ASRTurnDetection() + if turn_detection is not None: + config.turn_detection.mode = turn_detection + if eager is not None: + config.turn_detection.eager = eager + if drafts is not None or diarize is not None: + config.results = config.results or ASRResults() + if drafts is not None: + config.results.drafts = drafts + if diarize is not None: + config.results.diarize = diarize + if terms is not None: + config.context = config.context or ASRContext() + config.context.terms = terms + return config class ASRClient: @@ -76,6 +127,122 @@ def transcribe( # Parse and return response return ASRResponse.model_validate(response.json()) + def stream_websocket( + self, + audio_stream: Iterable[Union[bytes, ASRRealtimeControl]], + *, + sample_rate: Optional[ASRSampleRate] = None, + turn_detection: Optional[TurnDetectionMode] = None, + eager: Optional[bool] = None, + drafts: Optional[bool] = None, + diarize: Optional[bool] = None, + terms: Optional[list[str]] = None, + config: ASRRealtimeConfig = ASRRealtimeConfig(), + model: str = "transcribe-stream-1", + ws_options: Optional[WebSocketOptions] = None, + ) -> ASRRealtimeStream: + """ + Stream audio and receive transcripts in real-time via WebSocket. + + Audio is divided into turns. Each turn ends with one committed event that + holds its final transcript; with drafts=True you also get live draft events + while the turn is open. The session ends with a session_done event once + audio_stream is exhausted. + + By default the transcript text starts with a speaker tag, e.g. + ``<|speaker:0|> Hello.``, and can contain sound tags such as ``[laughter]``. + Pass diarize=False for text without speaker tags; sound tags are turned off + with config=ASRRealtimeConfig(results=ASRResults(tag_audio_events=False)). + + Args: + audio_stream: Iterator of raw audio chunks: 16-bit little-endian mono PCM, + ideally 20-40 ms each, sent as you capture them. It can also yield + control messages (e.g. ASRFinalizeEvent()), which are sent at that + position in the audio + sample_rate: Sample rate of the audio in Hz: 8000, 12000, 16000, 22050, + 24000, 32000, 44100 or 48000 (overrides config.sample_rate if provided) + turn_detection: When a turn ends - "auto" (the server judges that the user + has finished), "vad" (after a fixed silence) or "manual" (when you send + finalize) (overrides config.turn_detection.mode if provided) + eager: Send eager_end_of_turn events in auto mode + (overrides config.turn_detection.eager if provided) + drafts: Send live draft events (overrides config.results.drafts if provided) + diarize: Speaker tags such as ``<|speaker:0|>`` in the transcript text. The + server adds them by default; pass False for plain text + (overrides config.results.diarize if provided) + terms: Names, products and jargon to recognize + (overrides config.context.terms if provided) + config: Session configuration (audio, turn detection, results, context) + model: Realtime speech-to-text model + ws_options: WebSocket connection options for configuring timeouts, message size limits, etc. + See WebSocketOptions class for available parameters. + + Returns: + ASRRealtimeStream: an iterator of typed events (check event.type), with + methods to send control messages during the session: finalize(), + agent_speaking(), add_context() and configure() + + Raises: + ASRRealtimeError: If the server reports an error that ends the session, or + closes the connection abnormally (see error_type and close_code) + APIError: If the connection is refused (e.g. AuthenticationError for 401) + WebSocketError: If the connection is lost + + Example: + ```python + import wave + + from fishaudio import FishAudio + + client = FishAudio(api_key="...") + + def audio_chunks(): + with wave.open("speech.wav", "rb") as wav: # 16-bit mono PCM + while chunk := wav.readframes(640): # 40 ms at 16 kHz + yield chunk + + # Final transcript of each turn (diarize=False: no <|speaker:0|> tags) + for event in client.asr.stream_websocket( + audio_chunks(), sample_rate=16000, diarize=False + ): + if event.type == "committed": + print(event.text) + + # Live captions: drafts while the turn is open, then the final text + for event in client.asr.stream_websocket(audio_chunks(), drafts=True): + if event.type == "draft": + print("...", event.text) + elif event.type == "committed": + print(event.text) + + # Voice agent: answer the user's turns, and tell the server while you speak + with client.asr.stream_websocket(audio_chunks(), eager=True) as stream: + for event in stream: + if event.type == "committed" and event.user_turn: + stream.agent_speaking(True) + ... # reply, then stream.agent_speaking(False) + ``` + """ + ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} + headers = self._client.get_headers({"model": model}) + client = self._client.client + + return ASRRealtimeStream( + lambda: connect_ws( + REALTIME_PATH, client=client, headers=headers, **ws_kwargs + ), + _realtime_config( + config, + sample_rate=sample_rate, + turn_detection=turn_detection, + eager=eager, + drafts=drafts, + diarize=diarize, + terms=terms, + ), + audio_stream, + ) + class AsyncASRClient: """Asynchronous ASR operations.""" @@ -144,3 +311,119 @@ async def transcribe( # Parse and return response return ASRResponse.model_validate(response.json()) + + def stream_websocket( + self, + audio_stream: AsyncIterable[Union[bytes, ASRRealtimeControl]], + *, + sample_rate: Optional[ASRSampleRate] = None, + turn_detection: Optional[TurnDetectionMode] = None, + eager: Optional[bool] = None, + drafts: Optional[bool] = None, + diarize: Optional[bool] = None, + terms: Optional[list[str]] = None, + config: ASRRealtimeConfig = ASRRealtimeConfig(), + model: str = "transcribe-stream-1", + ws_options: Optional[WebSocketOptions] = None, + ) -> AsyncASRRealtimeStream: + """ + Stream audio and receive transcripts in real-time via WebSocket (async). + + Audio is divided into turns. Each turn ends with one committed event that + holds its final transcript; with drafts=True you also get live draft events + while the turn is open. The session ends with a session_done event once + audio_stream is exhausted. + + By default the transcript text starts with a speaker tag, e.g. + ``<|speaker:0|> Hello.``, and can contain sound tags such as ``[laughter]``. + Pass diarize=False for text without speaker tags; sound tags are turned off + with config=ASRRealtimeConfig(results=ASRResults(tag_audio_events=False)). + + Args: + audio_stream: Async iterator of raw audio chunks: 16-bit little-endian mono PCM, + ideally 20-40 ms each, sent as you capture them. It can also yield + control messages (e.g. ASRFinalizeEvent()), which are sent at that + position in the audio + sample_rate: Sample rate of the audio in Hz: 8000, 12000, 16000, 22050, + 24000, 32000, 44100 or 48000 (overrides config.sample_rate if provided) + turn_detection: When a turn ends - "auto" (the server judges that the user + has finished), "vad" (after a fixed silence) or "manual" (when you send + finalize) (overrides config.turn_detection.mode if provided) + eager: Send eager_end_of_turn events in auto mode + (overrides config.turn_detection.eager if provided) + drafts: Send live draft events (overrides config.results.drafts if provided) + diarize: Speaker tags such as ``<|speaker:0|>`` in the transcript text. The + server adds them by default; pass False for plain text + (overrides config.results.diarize if provided) + terms: Names, products and jargon to recognize + (overrides config.context.terms if provided) + config: Session configuration (audio, turn detection, results, context) + model: Realtime speech-to-text model + ws_options: WebSocket connection options for configuring timeouts, message size limits, etc. + See WebSocketOptions class for available parameters. + + Returns: + AsyncASRRealtimeStream: an async iterator of typed events (check event.type), with + methods to send control messages during the session: finalize(), + agent_speaking(), add_context() and configure() + + Raises: + ASRRealtimeError: If the server reports an error that ends the session, or + closes the connection abnormally (see error_type and close_code) + APIError: If the connection is refused (e.g. AuthenticationError for 401) + WebSocketError: If the connection is lost + + Example: + ```python + import wave + + from fishaudio import AsyncFishAudio + + client = AsyncFishAudio(api_key="...") + + async def audio_chunks(): + with wave.open("speech.wav", "rb") as wav: # 16-bit mono PCM + while chunk := wav.readframes(640): # 40 ms at 16 kHz + yield chunk + + # Final transcript of each turn (diarize=False: no <|speaker:0|> tags) + async for event in client.asr.stream_websocket( + audio_chunks(), sample_rate=16000, diarize=False + ): + if event.type == "committed": + print(event.text) + + # Live captions: drafts while the turn is open, then the final text + async for event in client.asr.stream_websocket(audio_chunks(), drafts=True): + if event.type == "draft": + print("...", event.text) + elif event.type == "committed": + print(event.text) + + # Voice agent: answer the user's turns, and tell the server while you speak + async with client.asr.stream_websocket(audio_chunks(), eager=True) as stream: + async for event in stream: + if event.type == "committed" and event.user_turn: + await stream.agent_speaking(True) + ... # reply, then await stream.agent_speaking(False) + ``` + """ + ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} + headers = self._client.get_headers({"model": model}) + client = self._client.client + + return AsyncASRRealtimeStream( + lambda: aconnect_ws( + REALTIME_PATH, client=client, headers=headers, **ws_kwargs + ), + _realtime_config( + config, + sample_rate=sample_rate, + turn_detection=turn_detection, + eager=eager, + drafts=drafts, + diarize=diarize, + terms=terms, + ), + audio_stream, + ) diff --git a/src/fishaudio/resources/asr_realtime.py b/src/fishaudio/resources/asr_realtime.py new file mode 100644 index 0000000..1292676 --- /dev/null +++ b/src/fishaudio/resources/asr_realtime.py @@ -0,0 +1,611 @@ +"""Realtime speech-to-text sessions over WebSocket.""" + +from __future__ import annotations + +import asyncio +import contextlib +import inspect +import logging +import queue +import threading +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Optional, + Union, +) + +import httpx +import ormsgpack +from httpx_ws import HTTPXWSException, WebSocketDisconnect, WebSocketUpgradeError + +from fishaudio.core._ws_utils import drain_reader +from fishaudio.core.client_wrapper import _api_error +from fishaudio.exceptions import ASRRealtimeError, WebSocketError +from fishaudio.types.asr_realtime import ( + ASRAgentSpeakingEvent, + ASRCommittedEvent, + ASRConfiguredEvent, + ASRConfigureEvent, + ASRContext, + ASRContextAddEvent, + ASRContextItem, + ASRDraftEvent, + ASREagerEndOfTurnEvent, + ASREotProbEvent, + ASRErrorEvent, + ASRFinalizeEvent, + ASRKeepaliveEvent, + ASRProgressEvent, + ASRRealtimeConfig, + ASRRealtimeControl, + ASRRealtimeEvent, + ASRResults, + ASRSessionDoneEvent, + ASRSessionStartedEvent, + ASRSpeechStartEvent, + ASRTurnDetection, + ASRTurnResumedEvent, + ASRUserBackchannelEvent, + ASRUserTurnTakenEvent, + ASRVadEvent, +) + +if TYPE_CHECKING: + from collections.abc import AsyncIterable, Generator, Iterable, Iterator + from contextlib import AbstractAsyncContextManager, AbstractContextManager + + from httpx_ws import AsyncWebSocketSession, WebSocketSession + +logger = logging.getLogger(__name__) + +REALTIME_PATH = "/v1/asr/realtime" + +# Events the async session may hold for a consumer that reads slowly. When it is +# full the session stops reading from the socket, so the server sees backpressure +# instead of the SDK buffering without limit. +_EVENT_QUEUE_SIZE = 256 + +# How often a blocked receive wakes up to check that the audio sender is alive. +_POLL_SECONDS = 0.25 +# Once the sender has failed, only messages that already arrived are read. +_DRAIN_SECONDS = 0.05 + +_EVENT_TYPES: dict[str, type[ASRRealtimeEvent]] = { + "session_started": ASRSessionStartedEvent, + "speech_start": ASRSpeechStartEvent, + "user_turn_taken": ASRUserTurnTakenEvent, + "draft": ASRDraftEvent, + "eager_end_of_turn": ASREagerEndOfTurnEvent, + "turn_resumed": ASRTurnResumedEvent, + "user_backchannel": ASRUserBackchannelEvent, + "committed": ASRCommittedEvent, + "vad": ASRVadEvent, + "eot_prob": ASREotProbEvent, + "configured": ASRConfiguredEvent, + "progress": ASRProgressEvent, + "error": ASRErrorEvent, + "session_done": ASRSessionDoneEvent, +} + +_AUDIO_DONE = ormsgpack.packb({"type": "audio_done"}) + + +def encode_config(config: ASRRealtimeConfig) -> bytes: + """Pack the ``config`` message that opens a session.""" + return ormsgpack.packb( + { + "type": "config", + "audio": { + "format": "pcm_s16le", + "sample_rate": config.sample_rate, + "channels": 1, + }, + **config.model_dump(exclude_none=True, exclude={"sample_rate"}), + } + ) + + +def encode_message(item: Union[bytes, ASRRealtimeControl]) -> bytes: + """Pack an audio chunk or a control message for the wire.""" + if isinstance(item, (bytes, bytearray, memoryview)): + # MessagePack bin: the server drops audio sent as a string or an array. + return ormsgpack.packb({"type": "audio", "data": bytes(item)}) + return ormsgpack.packb(item.model_dump(exclude_none=True)) + + +def decode_event(message: bytes) -> Optional[ASRRealtimeEvent]: + """Parse a server message. Returns None for message types this SDK does not know.""" + data = ormsgpack.unpackb(message) + event_type = _EVENT_TYPES.get(data.get("type")) if isinstance(data, dict) else None + return event_type.model_validate(data) if event_type else None + + +def _upgrade_error(response: httpx.Response) -> Exception: + """The WebSocket upgrade was refused (401, 402, 429, ...): map the HTTP status.""" + status = response.status_code + # httpx-ws closes the response before the body can be read. + return _api_error(status, httpx.codes.get_reason_phrase(status) or "Upgrade failed") + + +class _Protocol: + """Turns server messages and closes into events or exceptions (sync and async).""" + + def __init__(self) -> None: + self._last_error: Optional[ASRErrorEvent] = None + + def on_message(self, message: bytes) -> Optional[ASRRealtimeEvent]: + event = decode_event(message) + if event is None: + return None + if not isinstance(event, ASRErrorEvent): + self._last_error = None + return event + if not event.recoverable: + raise ASRRealtimeError( + event.message, + error_type=event.error_type, + code=event.code, + request_id=event.request_id, + ) + # server_restarting is recoverable but is followed by close 1012. + self._last_error = event + return event + + def on_close(self, code: int, reason: str) -> None: + if code == 1000: + return + error = self._last_error + raise ASRRealtimeError( + (error.message if error else reason) or "WebSocket closed unexpectedly", + error_type=error.error_type if error else None, + code=error.code if error else None, + request_id=error.request_id if error else None, + close_code=code, + ) + + +def _configure_event( + turn_detection: Optional[ASRTurnDetection], + results: Optional[ASRResults], + terms: Optional[list[str]], +) -> ASRConfigureEvent: + return ASRConfigureEvent( + turn_detection=turn_detection, + results=results, + context=ASRContext(terms=terms) if terms is not None else None, + ) + + +_NOT_OPEN = "Realtime session is not open" + + +# Synchronous + + +class _Link: + """The open connection, shared by the audio sender thread and control methods.""" + + def __init__(self) -> None: + self._ws: Optional[WebSocketSession] = None + self._lock = threading.Lock() + self.closed = False + + def open(self, ws: WebSocketSession) -> None: + with self._lock: + self._ws = ws + + def close(self) -> None: + with self._lock: + self._ws = None + self.closed = True + + def send(self, data: bytes) -> None: + with self._lock: + if self._ws is None: + raise WebSocketError(_NOT_OPEN) + try: + self._ws.send_bytes(data) + except HTTPXWSException as e: + raise WebSocketError("Failed to send: WebSocket closed") from e + + +def _send_audio( + link: _Link, + audio_stream: Iterable[Union[bytes, ASRRealtimeControl]], + failure: list[BaseException], +) -> None: + try: + for item in audio_stream: + if link.closed: # the session is over: stop at the next chunk + return + if item: + link.send(encode_message(item)) + link.send(_AUDIO_DONE) + except BaseException as e: + if not link.closed: # otherwise the consumer left: nobody to tell + failure.append(e) + finally: + # Closed here, by the thread that runs it: a generator cannot be closed + # from another thread while it is executing. + if inspect.isgenerator(audio_stream): + try: + audio_stream.close() + except Exception: + logger.debug("Closing the audio stream failed", exc_info=True) + + +def _iter_session( + link: _Link, + connect: Callable[[], AbstractContextManager[WebSocketSession]], + config: bytes, + audio_stream: Iterable[Union[bytes, ASRRealtimeControl]], +) -> Generator[ASRRealtimeEvent, None, None]: + protocol = _Protocol() + failure: list[BaseException] = [] + sender: Optional[threading.Thread] = None + try: + with connect() as ws: + try: + ws.send_bytes(config) + while True: + try: + message = ws.receive_bytes( + timeout=_DRAIN_SECONDS if failure else _POLL_SECONDS + ) + except (queue.Empty, TimeoutError): # httpx-ws < 0.8 / >= 0.8 + if failure: + raise failure[0] from None + continue + except WebSocketDisconnect as e: + protocol.on_close(e.code, e.reason) + return + except HTTPXWSException as e: + raise WebSocketError("WebSocket connection lost") from e + + event = protocol.on_message(message) + if event is None: + continue + if isinstance(event, ASRSessionStartedEvent) and sender is None: + link.open(ws) + sender = threading.Thread( + target=_send_audio, + args=(link, audio_stream, failure), + name="fishaudio-asr-realtime-sender", + daemon=True, + ) + sender.start() + yield event + if isinstance(event, ASRSessionDoneEvent): + return + finally: + link.close() + # Stop httpx-ws's reader thread before the socket is closed so it + # cannot read from a reused fd belonging to the next connection. + drain_reader(ws) + except WebSocketUpgradeError as e: + raise _upgrade_error(e.response) from e + + +class ASRRealtimeStream: + """A realtime speech-to-text session (sync). + + Iterate it for the server's events. The connection opens on the first + iteration and closes when the session ends, when an error is raised, or when + you leave the loop early. Use it as a context manager (or call ``close()``) + if you keep a reference to it after leaving the loop. + + The audio stream is read on a background thread. When the session ends + before the audio does, that thread stops as soon as the audio stream yields + its next chunk, and closes the stream if it is a generator. The SDK cannot + interrupt an audio stream that is blocked waiting for audio (for example a + microphone read with no timeout): make your audio source end, or yield + regularly, so the thread can exit. + + The control methods send a message at the current position in the audio + stream; they can be called from any thread once ``session_started`` has + been received. + """ + + def __init__( + self, + connect: Callable[[], AbstractContextManager[WebSocketSession]], + config: ASRRealtimeConfig, + audio_stream: Iterable[Union[bytes, ASRRealtimeControl]], + ): + # The generator must not reference this object: it is closed, and the + # connection with it, as soon as the stream is garbage collected. + self._link = _Link() + self._events = _iter_session( + self._link, connect, encode_config(config), audio_stream + ) + + def __iter__(self) -> Iterator[ASRRealtimeEvent]: + return self + + def __next__(self) -> ASRRealtimeEvent: + return next(self._events) + + def __enter__(self) -> ASRRealtimeStream: + return self + + def __exit__(self, *exc_info: Any) -> None: + self.close() + + def close(self) -> None: + """Close the connection. Safe to call more than once.""" + self._events.close() + + def send(self, message: ASRRealtimeControl) -> None: + """Send a control message. + + Raises: + WebSocketError: If the session is not open (not started yet, or closed) + """ + self._link.send(encode_message(message)) + + def finalize(self) -> None: + """Commit the current turn now (push-to-talk: the button was released).""" + self.send(ASRFinalizeEvent()) + + def agent_speaking(self, speaking: bool) -> None: + """Tell the server that your voice agent started or stopped speaking.""" + self.send(ASRAgentSpeakingEvent(speaking=speaking)) + + def add_context( + self, items: list[ASRContextItem], *, reset_history: bool = False + ) -> None: + """Add conversation context, typically each line your agent speaks.""" + self.send(ASRContextAddEvent(items=items, reset_history=reset_history)) + + def configure( + self, + *, + turn_detection: Optional[ASRTurnDetection] = None, + results: Optional[ASRResults] = None, + terms: Optional[list[str]] = None, + ) -> None: + """Change settings during the session. The server answers with a configured event.""" + self.send(_configure_event(turn_detection, results, terms)) + + def keepalive(self) -> None: + """Keep an idle session open. Rarely needed: WebSocket pings count as activity.""" + self.send(ASRKeepaliveEvent()) + + +# Asynchronous + + +class _AsyncLink: + """The open connection, shared by the audio sender task and control methods.""" + + def __init__(self) -> None: + self._ws: Optional[AsyncWebSocketSession] = None + + def open(self, ws: AsyncWebSocketSession) -> None: + self._ws = ws + + def close(self) -> None: + self._ws = None + + async def send(self, data: bytes) -> None: + if self._ws is None: + raise WebSocketError(_NOT_OPEN) + try: + await self._ws.send_bytes(data) + except HTTPXWSException as e: + raise WebSocketError("Failed to send: WebSocket closed") from e + + +async def _asend_audio( + link: _AsyncLink, audio_stream: AsyncIterable[Union[bytes, ASRRealtimeControl]] +) -> None: + try: + async for item in audio_stream: + if item: + await link.send(encode_message(item)) + await link.send(_AUDIO_DONE) + finally: + # A cancelled task leaves an async generator suspended at its yield; + # close it now rather than whenever the event loop finalizes it. + if inspect.isasyncgen(audio_stream): + try: + await audio_stream.aclose() + except Exception: + logger.debug("Closing the audio stream failed", exc_info=True) + + +def _failure(task: Optional[asyncio.Task[None]]) -> Optional[BaseException]: + if task is None or not task.done() or task.cancelled(): + return None + return task.exception() + + +class _End: + """Queue marker: the session is over, normally or with an error.""" + + def __init__(self, error: Optional[BaseException] = None) -> None: + self.error = error + + +async def _run_session( + link: _AsyncLink, + events: asyncio.Queue[Union[ASRRealtimeEvent, _End]], + connect: Callable[[], AbstractAsyncContextManager[AsyncWebSocketSession]], + config: bytes, + audio_stream: AsyncIterable[Union[bytes, ASRRealtimeControl]], +) -> None: + """Run one session from connect to close, inside a single task. + + httpx-ws keeps an anyio task group open for the lifetime of the connection, + and a task group must be exited by the task that entered it. An async + generator cannot promise that: when the consumer leaves ``async for`` early, + asyncio finalizes the generator from a different task. So the connection + lives in this task, which is simply cancelled to close it. + """ + protocol = _Protocol() + sender: Optional[asyncio.Task[None]] = None + error: Optional[BaseException] = None + try: + async with connect() as ws: + try: + await ws.send_bytes(config) + while True: + failure = _failure(sender) + try: + message = await ws.receive_bytes( + timeout=_DRAIN_SECONDS if failure else _POLL_SECONDS + ) + except TimeoutError: + if failure: + raise failure from None + continue + except WebSocketDisconnect as e: + protocol.on_close(e.code, e.reason) + break + except HTTPXWSException as e: + raise WebSocketError("WebSocket connection lost") from e + + event = protocol.on_message(message) + if event is None: + continue + if isinstance(event, ASRSessionStartedEvent) and sender is None: + link.open(ws) + sender = asyncio.create_task(_asend_audio(link, audio_stream)) + await events.put(event) # waits while the consumer is behind + if isinstance(event, ASRSessionDoneEvent): + break + except Exception as e: + # Leave the connection block without an exception: newer httpx-ws + # wraps one that crosses it in an ExceptionGroup. + error = e + finally: + link.close() + if sender is not None: + sender.cancel() + await asyncio.wait({sender}) + _failure(sender) # mark a late exception as retrieved + except WebSocketUpgradeError as e: + error = _upgrade_error(e.response) + error.__cause__ = e + except Exception as e: + error = error or e # keep the session's own error over one from closing + # The connection is closed by now. If the queue is full this waits for the + # consumer; one that has left cancels the task (aclose, or garbage collection). + await events.put(_End(error)) + + +class AsyncASRRealtimeStream: + """A realtime speech-to-text session (async). + + Iterate it with ``async for`` for the server's events. The connection opens + on the first iteration and closes when the session ends, when an error is + raised, or when you leave the loop early. Use it as an async context manager + (or call ``aclose()``) if you keep a reference to it after leaving the loop. + + Closing cancels the task that reads the audio stream and closes the stream + if it is an async generator. Up to 256 events are buffered for a consumer + that reads slowly; beyond that the session stops reading from the server + until the consumer catches up. + + The control methods send a message at the current position in the audio + stream; they can be awaited once ``session_started`` has been received. + """ + + def __init__( + self, + connect: Callable[[], AbstractAsyncContextManager[AsyncWebSocketSession]], + config: ASRRealtimeConfig, + audio_stream: AsyncIterable[Union[bytes, ASRRealtimeControl]], + ): + self._link = _AsyncLink() + self._connect = connect + self._config = encode_config(config) + self._audio_stream = audio_stream + self._events: Optional[asyncio.Queue[Union[ASRRealtimeEvent, _End]]] = None + self._task: Optional[asyncio.Task[None]] = None + self._finished = False + + def __aiter__(self) -> AsyncASRRealtimeStream: + return self + + async def __anext__(self) -> ASRRealtimeEvent: + if self._finished: + raise StopAsyncIteration + if self._events is None: + # The session task must not reference this object: it is cancelled, + # and the connection closed, when the stream is garbage collected. + self._events = asyncio.Queue(_EVENT_QUEUE_SIZE) + self._task = asyncio.create_task( + _run_session( + self._link, + self._events, + self._connect, + self._config, + self._audio_stream, + ) + ) + item = await self._events.get() + if isinstance(item, _End): + self._finished = True + if item.error is not None: + raise item.error + raise StopAsyncIteration + return item + + async def __aenter__(self) -> AsyncASRRealtimeStream: + return self + + async def __aexit__(self, *exc_info: Any) -> None: + await self.aclose() + + async def aclose(self) -> None: + """Close the connection. Safe to call more than once.""" + self._finished = True + if self._task is not None: + self._task.cancel() + await asyncio.wait({self._task}) + + def __del__(self) -> None: + task = getattr(self, "_task", None) + if task is not None and not task.done(): + # RuntimeError: the event loop is already closed + with contextlib.suppress(RuntimeError): + task.cancel() + + async def send(self, message: ASRRealtimeControl) -> None: + """Send a control message. + + Raises: + WebSocketError: If the session is not open (not started yet, or closed) + """ + await self._link.send(encode_message(message)) + + async def finalize(self) -> None: + """Commit the current turn now (push-to-talk: the button was released).""" + await self.send(ASRFinalizeEvent()) + + async def agent_speaking(self, speaking: bool) -> None: + """Tell the server that your voice agent started or stopped speaking.""" + await self.send(ASRAgentSpeakingEvent(speaking=speaking)) + + async def add_context( + self, items: list[ASRContextItem], *, reset_history: bool = False + ) -> None: + """Add conversation context, typically each line your agent speaks.""" + await self.send(ASRContextAddEvent(items=items, reset_history=reset_history)) + + async def configure( + self, + *, + turn_detection: Optional[ASRTurnDetection] = None, + results: Optional[ASRResults] = None, + terms: Optional[list[str]] = None, + ) -> None: + """Change settings during the session. The server answers with a configured event.""" + await self.send(_configure_event(turn_detection, results, terms)) + + async def keepalive(self) -> None: + """Keep an idle session open. Rarely needed: WebSocket pings count as activity.""" + await self.send(ASRKeepaliveEvent()) diff --git a/src/fishaudio/types/__init__.py b/src/fishaudio/types/__init__.py index 584bc38..9441d90 100644 --- a/src/fishaudio/types/__init__.py +++ b/src/fishaudio/types/__init__.py @@ -2,6 +2,38 @@ from .account import Credits, Package from .asr import ASRResponse, ASRSegment, SpeakerTurn +from .asr_realtime import ( + ASRAgentSpeakingEvent, + ASRCommittedEvent, + ASRConfiguredEvent, + ASRConfigureEvent, + ASRContext, + ASRContextAddEvent, + ASRContextItem, + ASRDraftEvent, + ASREagerEndOfTurnEvent, + ASREotProbEvent, + ASRErrorEvent, + ASRFinalizeEvent, + ASRKeepaliveEvent, + ASRProgressEvent, + ASRRealtimeConfig, + ASRRealtimeControl, + ASRRealtimeEvent, + ASRResults, + ASRSampleRate, + ASRSessionDoneEvent, + ASRSessionStartedEvent, + ASRSessionStats, + ASRSpeechStartEvent, + ASRTurnDetection, + ASRTurnResumedEvent, + ASRUserBackchannelEvent, + ASRUserTurnTakenEvent, + ASRVadEvent, + ASRWord, + TurnDetectionMode, +) from .shared import ( AudioFormat, LatencyMode, @@ -31,6 +63,37 @@ "ASRResponse", "ASRSegment", "SpeakerTurn", + # Realtime ASR types + "ASRAgentSpeakingEvent", + "ASRCommittedEvent", + "ASRConfiguredEvent", + "ASRConfigureEvent", + "ASRContext", + "ASRContextAddEvent", + "ASRContextItem", + "ASRDraftEvent", + "ASREagerEndOfTurnEvent", + "ASREotProbEvent", + "ASRErrorEvent", + "ASRFinalizeEvent", + "ASRKeepaliveEvent", + "ASRProgressEvent", + "ASRRealtimeConfig", + "ASRRealtimeControl", + "ASRRealtimeEvent", + "ASRResults", + "ASRSampleRate", + "ASRSessionDoneEvent", + "ASRSessionStartedEvent", + "ASRSessionStats", + "ASRSpeechStartEvent", + "ASRTurnDetection", + "ASRTurnResumedEvent", + "ASRUserBackchannelEvent", + "ASRUserTurnTakenEvent", + "ASRVadEvent", + "ASRWord", + "TurnDetectionMode", # Shared types "AudioFormat", "LatencyMode", diff --git a/src/fishaudio/types/asr_realtime.py b/src/fishaudio/types/asr_realtime.py new file mode 100644 index 0000000..00ddaf8 --- /dev/null +++ b/src/fishaudio/types/asr_realtime.py @@ -0,0 +1,518 @@ +"""Types for realtime speech-to-text (``/v1/asr/realtime``).""" + +from typing import Any, Literal, Optional, Union + +from pydantic import BaseModel, ConfigDict + +ASRSampleRate = Literal[8000, 12000, 16000, 22050, 24000, 32000, 44100, 48000] +TurnDetectionMode = Literal["auto", "vad", "manual"] + + +# Session configuration + + +class ASRTurnDetection(BaseModel): + """How the server decides that a turn has ended. + + Fields left as None are not sent: the server uses its default at session + start, and keeps the current value in a mid-session ``configure``. + + Attributes: + mode: "auto" (default): the server judges when the user has finished and tells + user turns from noise and other voices. "vad": a turn ends after + silence_timeout_ms of silence. "manual": a turn ends when you send finalize + eager: Send eager_end_of_turn events (auto mode only). Server default: False + silence_timeout_ms: Silence that ends a turn. auto: default 5000, allowed + 3000-60000. vad: default 700, allowed 300-60000. manual: default 60000, + allowed 300-60000 + """ + + mode: Optional[TurnDetectionMode] = None + eager: Optional[bool] = None + silence_timeout_ms: Optional[int] = None + + +class ASRResults(BaseModel): + """Which results the server sends, and what the transcript text contains. + + Fields left as None are not sent: the server uses its default at session + start, and keeps the current value in a mid-session ``configure``. + + Attributes: + drafts: Send live draft events. Server default: False + ignore_timestamps: False adds word timings to committed events. Server default: True + diarize: Speaker tags such as ``<|speaker:0|>`` in the text. Server default: True + tag_audio_events: Sound tags such as ``[laughter]`` in the text. Server default: True + vad_events: Send vad events (voice activity, up to 10 per second). Server default: False + eot_events: Send eot_prob events (end-of-turn likelihood). Server default: False + """ + + drafts: Optional[bool] = None + ignore_timestamps: Optional[bool] = None + diarize: Optional[bool] = None + tag_audio_events: Optional[bool] = None + vad_events: Optional[bool] = None + eot_events: Optional[bool] = None + + +class ASRContextItem(BaseModel): + """One line of conversation given to the server as context. + + Attributes: + role: Who said it: "user" or "assistant" + text: What was said (up to 2000 characters) + """ + + role: Literal["user", "assistant"] + text: str + + +class ASRContext(BaseModel): + """Conversation context that helps the server recognize names and follow-ups. + + Attributes: + history: Earlier conversation, oldest first (up to 32 items). Only accepted + at session start; add lines later with context_add + terms: Names, products and jargon to recognize (up to 100 terms of up to + 32 characters) + """ + + history: Optional[list[ASRContextItem]] = None + terms: Optional[list[str]] = None + + +class ASRRealtimeConfig(BaseModel): + """Configuration for a realtime speech-to-text session. + + Attributes: + sample_rate: Sample rate of the audio you send, in Hz. The server converts + other rates to 16000, so you never need to resample. Default: 16000 + turn_detection: Turn detection settings. Default: None (server defaults) + results: Result settings. Default: None (server defaults) + context: Conversation history and custom vocabulary. Default: None + client_reference_id: Your own ID for the session (up to 256 characters). + Recorded with the session; not sent back. Default: None + """ + + sample_rate: ASRSampleRate = 16000 + turn_detection: Optional[ASRTurnDetection] = None + results: Optional[ASRResults] = None + context: Optional[ASRContext] = None + client_reference_id: Optional[str] = None + + +# Control messages you can send during a session + + +class ASRFinalizeEvent(BaseModel): + """Commit the current turn now (push-to-talk: the button was released). + + Attributes: + type: Message type identifier, always "finalize" + """ + + type: Literal["finalize"] = "finalize" + + +class ASRAgentSpeakingEvent(BaseModel): + """Tell the server whether your voice agent is speaking (auto mode). + + While the agent speaks, a short acknowledgement from the user produces + user_backchannel instead of user_turn_taken. + + Attributes: + type: Message type identifier, always "agent_speaking" + speaking: True when you commit to playing a reply; False when its last + sample has played or you stop it + """ + + type: Literal["agent_speaking"] = "agent_speaking" + speaking: bool + + +class ASRContextAddEvent(BaseModel): + """Add conversation context, typically each line your agent speaks. + + Attributes: + type: Message type identifier, always "context_add" + items: Conversation items, oldest first (up to 32) + reset_history: First drop the items you added before. Default: False + """ + + type: Literal["context_add"] = "context_add" + items: list[ASRContextItem] + reset_history: bool = False + + +class ASRConfigureEvent(BaseModel): + """Change settings during the session. Answered by a configured event. + + Attributes: + type: Message type identifier, always "configure" + turn_detection: Turn detection changes; omitted fields keep their values + results: Result changes; omitted fields keep their values + context: Only ``terms`` is accepted here; it replaces the list of terms + """ + + type: Literal["configure"] = "configure" + turn_detection: Optional[ASRTurnDetection] = None + results: Optional[ASRResults] = None + context: Optional[ASRContext] = None + + +class ASRKeepaliveEvent(BaseModel): + """Keep an idle session open. + + Rarely needed: the SDK's WebSocket pings already count as client activity. + + Attributes: + type: Message type identifier, always "keepalive" + """ + + type: Literal["keepalive"] = "keepalive" + + +ASRRealtimeControl = Union[ + ASRFinalizeEvent, + ASRAgentSpeakingEvent, + ASRContextAddEvent, + ASRConfigureEvent, + ASRKeepaliveEvent, +] + + +# Events the server sends + + +class _ServerEvent(BaseModel): + # The protocol only ever adds fields, so keep the ones this SDK version does + # not know yet reachable as attributes instead of dropping them. + model_config = ConfigDict(extra="allow") + + seq: Optional[int] = None + + +class ASRWord(BaseModel): + """A word of a committed transcript with its position in the audio. + + Attributes: + text: The word + start_ms: Where the word starts, in milliseconds of session audio + end_ms: Where the word ends, in milliseconds of session audio + """ + + text: str + start_ms: int + end_ms: int + + +class ASRSessionStartedEvent(_ServerEvent): + """The session is ready; audio is sent after this event. + + Attributes: + type: Event type identifier, always "session_started" + seq: Sequence number, increasing by one per server message + session_id: The session's ID + request_id: Identifier of this request; quote it when reporting a problem + config: The configuration in effect, with defaults filled in + limits: Session limits (max_session_ms, max_turn_ms, max_frame_bytes) + """ + + type: Literal["session_started"] = "session_started" + session_id: str + request_id: Optional[str] = None + config: dict[str, Any] = {} + limits: dict[str, Any] = {} + + +class ASRSpeechStartEvent(_ServerEvent): + """A turn opened on voice activity. + + In auto mode noise and other voices open turns too: wait for + user_turn_taken before treating it as the user's turn. + + Attributes: + type: Event type identifier, always "speech_start" + seq: Sequence number + turn_index: The turn that opened, counting from 0 + audio_ms: Where the turn starts, slightly before the speech + """ + + type: Literal["speech_start"] = "speech_start" + turn_index: int + audio_ms: Optional[int] = None + + +class ASRUserTurnTakenEvent(_ServerEvent): + """Auto mode: the server judged that the user is taking their turn. + + For a voice agent that is speaking, this is the signal to stop (barge-in). + + Attributes: + type: Event type identifier, always "user_turn_taken" + seq: Sequence number + turn_index: The turn the user took + audio_ms: Where the server judged that the user took the turn + """ + + type: Literal["user_turn_taken"] = "user_turn_taken" + turn_index: int + audio_ms: Optional[int] = None + + +class ASRDraftEvent(_ServerEvent): + """Live draft of the open turn (with ``drafts=True``). Not final. + + Attributes: + type: Event type identifier, always "draft" + seq: Sequence number + turn_index: The open turn + text: The whole turn so far. Replaces the previous draft + settled_text: The beginning of text that the server is confident will not + change. Often empty + language: English name of the detected language. None if not identified + language_code: ISO 639-1 code of the detected language. None if not identified + audio_ms: The audio position the draft covers up to + audio_received_ms: Audio received so far + audio_processed_ms: Audio processed so far + audio_committed_ms: Audio covered by committed turns so far + """ + + type: Literal["draft"] = "draft" + turn_index: int + text: str + settled_text: str = "" + language: Optional[str] = None + language_code: Optional[str] = None + audio_ms: Optional[int] = None + audio_received_ms: Optional[int] = None + audio_processed_ms: Optional[int] = None + audio_committed_ms: Optional[int] = None + + +class ASREagerEndOfTurnEvent(_ServerEvent): + """The turn has probably ended (auto mode with ``eager=True``). + + Start preparing your response; a turn_resumed event cancels it. + + Attributes: + type: Event type identifier, always "eager_end_of_turn" + seq: Sequence number + turn_index: The turn that probably ended + text: Exactly what committed will say unless turn_resumed follows. Can be empty + language: English name of the detected language. None if not identified + language_code: ISO 639-1 code of the detected language. None if not identified + audio_ms: The audio position of the signal + """ + + type: Literal["eager_end_of_turn"] = "eager_end_of_turn" + turn_index: int + text: str + language: Optional[str] = None + language_code: Optional[str] = None + audio_ms: Optional[int] = None + + +class ASRTurnResumedEvent(_ServerEvent): + """The speaker went on after eager_end_of_turn: discard that text. + + Attributes: + type: Event type identifier, always "turn_resumed" + seq: Sequence number + turn_index: The turn that resumed + """ + + type: Literal["turn_resumed"] = "turn_resumed" + turn_index: int + + +class ASRUserBackchannelEvent(_ServerEvent): + """Auto mode, while your agent speaks: the user only acknowledged ("mm-hm"). + + Attributes: + type: Event type identifier, always "user_backchannel" + seq: Sequence number + turn_index: The open turn, or the index the next turn will get + audio_ms: Where the acknowledgement is in the audio + """ + + type: Literal["user_backchannel"] = "user_backchannel" + turn_index: int + audio_ms: Optional[int] = None + + +class ASRCommittedEvent(_ServerEvent): + """The final transcript of a turn. Every turn has exactly one. + + Attributes: + type: Event type identifier, always "committed" + seq: Sequence number + turn_index: The turn that ended + text: The final transcript. Can contain speaker tags such as ``<|speaker:0|>`` + and sound tags such as ``[laughter]``. Can be empty + words: Word timings. Only with ``ignore_timestamps=False``; None otherwise + language: English name of the detected language. None if not identified + language_code: ISO 639-1 code of the detected language. None if not identified + audio_start_ms: Where the turn starts in the session audio + audio_end_ms: Where the turn ends in the session audio + reason: Why the turn ended: "eot", "finalize", "silence_timeout", + "max_turn_duration" or "audio_done". Treat an unknown value like "eot" + degraded: True when the final pass failed and the text comes from the last draft + user_turn: True for the user's turn. Decide whether to answer by this field + turn_kind: "user", "backchannel" or "other" + audio_received_ms: Audio received so far + audio_processed_ms: Audio processed so far + audio_committed_ms: Audio covered by committed turns so far + """ + + type: Literal["committed"] = "committed" + turn_index: int + text: str + words: Optional[list[ASRWord]] = None + language: Optional[str] = None + language_code: Optional[str] = None + audio_start_ms: Optional[int] = None + audio_end_ms: Optional[int] = None + reason: str = "eot" + degraded: bool = False + user_turn: bool = True + turn_kind: Optional[str] = None + audio_received_ms: Optional[int] = None + audio_processed_ms: Optional[int] = None + audio_committed_ms: Optional[int] = None + + +class ASRVadEvent(_ServerEvent): + """Voice activity (with ``vad_events=True``), up to 10 per second. + + Attributes: + type: Event type identifier, always "vad" + seq: Sequence number + audio_ms: The audio position of the score + score: Voice activity, from 0 to 1 + """ + + type: Literal["vad"] = "vad" + audio_ms: Optional[int] = None + score: float + + +class ASREotProbEvent(_ServerEvent): + """End-of-turn likelihood for display (with ``eot_events=True``). + + Attributes: + type: Event type identifier, always "eot_prob" + seq: Sequence number + turn_index: The open turn + audio_ms: The audio position of the estimate + prob: End-of-turn likelihood, from 0 to 1 + """ + + type: Literal["eot_prob"] = "eot_prob" + turn_index: Optional[int] = None + audio_ms: Optional[int] = None + prob: float + + +class ASRConfiguredEvent(_ServerEvent): + """The reply to a configure message. + + Attributes: + type: Event type identifier, always "configured" + seq: Sequence number + ok: False means nothing changed + config: The configuration in effect + message: Why the change was refused, in English. None when ok is True + """ + + type: Literal["configured"] = "configured" + ok: bool + config: dict[str, Any] = {} + message: Optional[str] = None + + +class ASRProgressEvent(_ServerEvent): + """Audio watermarks, sent every 5 seconds while the client sends nothing. + + Attributes: + type: Event type identifier, always "progress" + seq: Sequence number + audio_received_ms: Audio received so far + audio_processed_ms: Audio processed so far + audio_committed_ms: Audio covered by committed turns so far + """ + + type: Literal["progress"] = "progress" + audio_received_ms: Optional[int] = None + audio_processed_ms: Optional[int] = None + audio_committed_ms: Optional[int] = None + + +class ASRErrorEvent(_ServerEvent): + """A recoverable error: the session continues. + + Errors that end the session are raised as ASRRealtimeError instead. + + Attributes: + type: Event type identifier, always "error" + seq: Sequence number + code: HTTP-style status + error_type: Machine-readable error type, e.g. "invalid_request". Match on this + message: A short English description, for humans + request_id: Identifier of this request; quote it when reporting a problem + recoverable: True when the session continues + """ + + type: Literal["error"] = "error" + code: Optional[int] = None + error_type: str + message: str = "" + request_id: Optional[str] = None + recoverable: bool = False + + +class ASRSessionStats(BaseModel): + """Totals for a finished session. + + Attributes: + audio_ms: Audio received in the session + turns: Every committed turn, user turn or not + request_id: Identifier of this request + """ + + model_config = ConfigDict(extra="allow") + + audio_ms: Optional[int] = None + turns: Optional[int] = None + request_id: Optional[str] = None + + +class ASRSessionDoneEvent(_ServerEvent): + """The session ended normally. Always the last event. + + Attributes: + type: Event type identifier, always "session_done" + seq: Sequence number + stats: Totals for the session + """ + + type: Literal["session_done"] = "session_done" + stats: ASRSessionStats = ASRSessionStats() + + +ASRRealtimeEvent = Union[ + ASRSessionStartedEvent, + ASRSpeechStartEvent, + ASRUserTurnTakenEvent, + ASRDraftEvent, + ASREagerEndOfTurnEvent, + ASRTurnResumedEvent, + ASRUserBackchannelEvent, + ASRCommittedEvent, + ASRVadEvent, + ASREotProbEvent, + ASRConfiguredEvent, + ASRProgressEvent, + ASRErrorEvent, + ASRSessionDoneEvent, +] diff --git a/tests/unit/realtime_server.py b/tests/unit/realtime_server.py new file mode 100644 index 0000000..f772a09 --- /dev/null +++ b/tests/unit/realtime_server.py @@ -0,0 +1,193 @@ +"""A scripted WebSocket server that speaks the server side of /v1/asr/realtime. + +It listens on a real TCP socket and frames messages with wsproto, so the tests +exercise the SDK's actual transport (httpx + httpx-ws) rather than mocks of it. +""" + +from __future__ import annotations + +import contextlib +import socket +import threading +from collections import deque +from typing import Any, Callable, Optional + +import ormsgpack +from wsproto import ConnectionType, WSConnection +from wsproto.events import ( + AcceptConnection, + BytesMessage, + CloseConnection, + Ping, + RejectConnection, + Request, +) + +SESSION_STARTED = { + "type": "session_started", + "seq": 0, + "session_id": "s_test", + "request_id": "req_test", + "config": {"model": "transcribe-stream-1"}, + "limits": {"max_session_ms": 3600000}, +} + + +class ClientGone(Exception): + """The client closed the connection.""" + + +class Connection: + """One client connection, as seen by a server script.""" + + def __init__(self, sock: socket.socket, reject_status: Optional[int]): + self._sock = sock + self._ws = WSConnection(ConnectionType.SERVER) + self._reject_status = reject_status + self._pending: deque[dict[str, Any]] = deque() + self._partial = b"" + self.headers: dict[str, str] = {} + self.path: Optional[str] = None + self.received: list[dict[str, Any]] = [] + self.close_code: Optional[int] = None + + def _write(self, event: Any) -> None: + self._sock.sendall(self._ws.send(event)) + + def _read(self) -> None: + try: + data = self._sock.recv(65536) + except socket.timeout: + raise + except OSError: + data = b"" + if not data: + raise ClientGone + self._ws.receive_data(data) + for event in self._ws.events(): + if isinstance(event, Request): + self.path = event.target + self.headers = {k.decode(): v.decode() for k, v in event.extra_headers} + if self._reject_status is not None: + self._write(RejectConnection(status_code=self._reject_status)) + raise ClientGone + self._write(AcceptConnection()) + elif isinstance(event, BytesMessage): + self._partial += bytes(event.data) + if event.message_finished: + self._pending.append(ormsgpack.unpackb(self._partial)) + self._partial = b"" + elif isinstance(event, Ping): + self._write(event.response()) + elif isinstance(event, CloseConnection): + self.close_code = event.code + with contextlib.suppress(Exception): + self._write(event.response()) + raise ClientGone + + def handshake(self) -> None: + while self.path is None: + self._read() + + def recv(self) -> dict[str, Any]: + """The next message from the client. Raises ClientGone when it has left.""" + while not self._pending: + self._read() + message = self._pending.popleft() + self.received.append(message) + return message + + def recv_until(self, message_type: str) -> list[dict[str, Any]]: + """Read up to and including the first message of the given type.""" + messages = [] + while not messages or messages[-1]["type"] != message_type: + messages.append(self.recv()) + return messages + + def quiet_for(self, seconds: float) -> bool: + """True if the client sends nothing for the given time.""" + self._sock.settimeout(seconds) + try: + self._read() + except socket.timeout: + return not self._pending + finally: + self._sock.settimeout(5) + return not self._pending + + def send(self, message: dict[str, Any]) -> None: + self._write(BytesMessage(data=ormsgpack.packb(message))) + + def send_raw(self, data: bytes) -> None: + self._write(BytesMessage(data=data)) + + def close(self, code: int = 1000, reason: str = "") -> None: + self._write(CloseConnection(code=code, reason=reason)) + + def drop(self) -> None: + """Cut the TCP connection without a close frame.""" + self._sock.close() + + def wait_gone(self) -> None: + """Block until the client has closed the connection.""" + with contextlib.suppress(ClientGone): + while True: + self.recv() + # Messages that arrived in the same read as the close frame. + self.received.extend(self._pending) + self._pending.clear() + + +class RealtimeServer: + """Runs ``script(connection)`` for the first client that connects.""" + + def __init__( + self, + script: Callable[[Connection], None], + *, + reject_status: Optional[int] = None, + ): + self._script = script + self._reject_status = reject_status + self._listener = socket.create_server(("127.0.0.1", 0)) + self._listener.settimeout(5) + self.url = f"http://127.0.0.1:{self._listener.getsockname()[1]}" + self.connection: Optional[Connection] = None + self.error: Optional[BaseException] = None + self.finished = threading.Event() + self._thread = threading.Thread(target=self._serve, daemon=True) + self._thread.start() + + def _serve(self) -> None: + try: + sock, _ = self._listener.accept() + except OSError: + self.finished.set() + return + sock.settimeout(5) + self.connection = Connection(sock, self._reject_status) + try: + self.connection.handshake() + self._script(self.connection) + self.connection.wait_gone() + except ClientGone: + pass + except BaseException as e: + self.error = e + finally: + with contextlib.suppress(OSError): + sock.close() + self.finished.set() + + def stop(self) -> Connection: + """Wait for the script to end, re-raise its failure, return the connection.""" + assert self.finished.wait(10), "server script did not finish" + self.close() + if self.error is not None: + raise self.error + assert self.connection is not None, "no client connected" + return self.connection + + def close(self) -> None: + """Stop listening. Called by stop(); safe to call again.""" + self._listener.close() diff --git a/tests/unit/test_asr_realtime.py b/tests/unit/test_asr_realtime.py new file mode 100644 index 0000000..a1f86d2 --- /dev/null +++ b/tests/unit/test_asr_realtime.py @@ -0,0 +1,1004 @@ +"""Tests for realtime speech-to-text (client.asr.stream_websocket). + +The session tests run the real client against a scripted WebSocket server on a +local TCP socket (see realtime_server.py), so they cover the wire format, the +ordering of messages and how the connection is closed. +""" + +import asyncio +import contextlib +import threading +import time + +import ormsgpack +import pytest + +from fishaudio import ( + APIError, + ASRRealtimeError, + AsyncFishAudio, + AuthenticationError, + FishAudio, + WebSocketError, +) +from fishaudio.resources import asr_realtime +from fishaudio.resources.asr import _realtime_config +from fishaudio.resources.asr_realtime import ( + decode_event, + encode_config, + encode_message, +) +from fishaudio.types import ( + ASRAgentSpeakingEvent, + ASRCommittedEvent, + ASRConfigureEvent, + ASRContext, + ASRContextAddEvent, + ASRContextItem, + ASRDraftEvent, + ASRErrorEvent, + ASRFinalizeEvent, + ASRRealtimeConfig, + ASRResults, + ASRSessionDoneEvent, + ASRSessionStartedEvent, + ASRTurnDetection, +) + +from .realtime_server import SESSION_STARTED, RealtimeServer + +CHUNK = b"\x01\x00" * 320 # 20 ms of 16 kHz audio + +SPEECH_START = {"type": "speech_start", "seq": 1, "turn_index": 0, "audio_ms": 300} +DRAFT = { + "type": "draft", + "seq": 2, + "turn_index": 0, + "text": "what's the weather", + "settled_text": "", + "language_code": "en", + "audio_ms": 1800, +} +COMMITTED = { + "type": "committed", + "seq": 3, + "turn_index": 0, + "text": "What's the weather like?", + "language": "English", + "language_code": "en", + "audio_start_ms": 300, + "audio_end_ms": 2880, + "reason": "audio_done", + "degraded": False, + "user_turn": True, + "turn_kind": "user", +} +SESSION_DONE = { + "type": "session_done", + "seq": 4, + "stats": {"audio_ms": 40, "turns": 1, "request_id": "req_test"}, +} + + +def error_message(error_type, *, recoverable, code=400): + return { + "type": "error", + "seq": 1, + "code": code, + "error_type": error_type, + "message": f"{error_type} happened", + "request_id": "req_test", + "recoverable": recoverable, + } + + +def transcribe_script(conn): + """A whole session: config, audio until audio_done, one committed turn.""" + conn.recv() + assert conn.quiet_for(0.2), "audio was sent before session_started" + conn.send(SESSION_STARTED) + conn.send(SPEECH_START) + conn.recv_until("audio_done") + conn.send(DRAFT) + conn.send(COMMITTED) + conn.send(SESSION_DONE) + conn.close(1000, "done") + + +def open_ended_script(conn): + """Start a session, commit one turn, then keep it open until the client leaves.""" + conn.recv() + conn.send(SESSION_STARTED) + conn.send(COMMITTED) + + +def endless_audio(): + while True: + yield CHUNK + time.sleep(0.01) + + +async def aendless_audio(): + while True: + yield CHUNK + await asyncio.sleep(0.01) + + +async def aiter_chunks(*items): + for item in items: + yield item + + +@contextlib.contextmanager +def serving(script, **server_options): + server = RealtimeServer(script, **server_options) + client = FishAudio(api_key="test-key", base_url=server.url) + try: + yield server, client + finally: + client.close() + server.close() + + +@contextlib.asynccontextmanager +async def aserving(script, **server_options): + server = RealtimeServer(script, **server_options) + client = AsyncFishAudio(api_key="test-key", base_url=server.url) + try: + yield server, client + finally: + await client.close() + server.close() + + +def sender_threads(): + return [ + t for t in threading.enumerate() if t.name == "fishaudio-asr-realtime-sender" + ] + + +def wait_for_no_sender_threads(timeout=2): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline and sender_threads(): + time.sleep(0.01) + return not sender_threads() + + +async def astop(server): + """Wait for the server script without blocking the event loop.""" + return await asyncio.get_running_loop().run_in_executor(None, server.stop) + + +class TestEncoding: + def test_config_defaults_send_only_the_audio_format(self): + assert ormsgpack.unpackb(encode_config(ASRRealtimeConfig())) == { + "type": "config", + "audio": {"format": "pcm_s16le", "sample_rate": 16000, "channels": 1}, + } + + def test_config_with_every_option(self): + config = ASRRealtimeConfig( + sample_rate=48000, + turn_detection=ASRTurnDetection( + mode="vad", eager=False, silence_timeout_ms=900 + ), + results=ASRResults(drafts=True, ignore_timestamps=False, diarize=False), + context=ASRContext( + history=[ASRContextItem(role="assistant", text="Hello.")], + terms=["Fish Audio"], + ), + client_reference_id="call-42", + ) + assert ormsgpack.unpackb(encode_config(config)) == { + "type": "config", + "audio": {"format": "pcm_s16le", "sample_rate": 48000, "channels": 1}, + "turn_detection": { + "mode": "vad", + "eager": False, + "silence_timeout_ms": 900, + }, + "results": {"drafts": True, "ignore_timestamps": False, "diarize": False}, + "context": { + "history": [{"role": "assistant", "text": "Hello."}], + "terms": ["Fish Audio"], + }, + "client_reference_id": "call-42", + } + + def test_config_rejects_unsupported_sample_rate(self): + with pytest.raises(ValueError): + ASRRealtimeConfig(sample_rate=11025) + + def test_direct_parameters_override_config_without_mutating_it(self): + base = ASRRealtimeConfig( + sample_rate=8000, + turn_detection=ASRTurnDetection(mode="vad", silence_timeout_ms=900), + context=ASRContext(terms=["old"]), + ) + merged = _realtime_config( + base, + sample_rate=24000, + turn_detection="auto", + eager=True, + drafts=True, + diarize=False, + terms=["Fish Audio"], + ) + assert merged.sample_rate == 24000 + assert merged.turn_detection == ASRTurnDetection( + mode="auto", eager=True, silence_timeout_ms=900 + ) + assert merged.results == ASRResults(drafts=True, diarize=False) + assert merged.context == ASRContext(terms=["Fish Audio"]) + assert base.sample_rate == 8000 + assert base.turn_detection.mode == "vad" + assert base.context.terms == ["old"] + + def test_omitted_parameters_keep_config(self): + base = ASRRealtimeConfig(results=ASRResults(drafts=True)) + merged = _realtime_config( + base, + sample_rate=None, + turn_detection=None, + eager=None, + drafts=None, + diarize=None, + terms=None, + ) + assert merged == base + + def test_diarize_keeps_other_result_settings(self): + base = ASRRealtimeConfig(results=ASRResults(drafts=True, diarize=True)) + merged = _realtime_config( + base, + sample_rate=None, + turn_detection=None, + eager=None, + drafts=None, + diarize=False, + terms=None, + ) + assert merged.results == ASRResults(drafts=True, diarize=False) + assert base.results.diarize is True + + def test_audio_is_packed_as_msgpack_bin(self): + packed = encode_message(b"\x01\x02\x03") + assert ormsgpack.unpackb(packed) == {"type": "audio", "data": b"\x01\x02\x03"} + # bin 8 marker + length: the server drops audio sent as str or array + assert b"\xc4\x03\x01\x02\x03" in packed + assert encode_message(bytearray(b"\x01\x02\x03")) == packed + assert encode_message(memoryview(b"\x01\x02\x03")) == packed + + @pytest.mark.parametrize( + ("message", "expected"), + [ + (ASRFinalizeEvent(), {"type": "finalize"}), + ( + ASRAgentSpeakingEvent(speaking=True), + {"type": "agent_speaking", "speaking": True}, + ), + ( + ASRContextAddEvent( + items=[ASRContextItem(role="assistant", text="Sure.")] + ), + { + "type": "context_add", + "items": [{"role": "assistant", "text": "Sure."}], + "reset_history": False, + }, + ), + ( + ASRConfigureEvent(context=ASRContext(terms=["Main Street"])), + {"type": "configure", "context": {"terms": ["Main Street"]}}, + ), + ], + ) + def test_control_messages(self, message, expected): + assert ormsgpack.unpackb(encode_message(message)) == expected + + +class TestDecoding: + def test_committed(self): + event = decode_event( + ormsgpack.packb( + { + **COMMITTED, + "words": [{"text": "What's", "start_ms": 300, "end_ms": 620}], + } + ) + ) + assert isinstance(event, ASRCommittedEvent) + assert event.text == "What's the weather like?" + assert event.reason == "audio_done" + assert event.user_turn is True + assert event.turn_kind == "user" + assert event.words[0].start_ms == 300 + assert (event.audio_start_ms, event.audio_end_ms) == (300, 2880) + + def test_committed_treats_missing_user_turn_as_true(self): + event = decode_event( + ormsgpack.packb({"type": "committed", "turn_index": 1, "text": ""}) + ) + assert event.user_turn is True + assert event.words is None + assert event.language_code is None + + def test_draft(self): + event = decode_event(ormsgpack.packb(DRAFT)) + assert isinstance(event, ASRDraftEvent) + assert (event.text, event.settled_text) == ("what's the weather", "") + assert event.language is None + + @pytest.mark.parametrize( + "message", + [ + SESSION_STARTED, + SPEECH_START, + {"type": "user_turn_taken", "seq": 3, "turn_index": 0, "audio_ms": 1280}, + DRAFT, + {"type": "eager_end_of_turn", "seq": 5, "turn_index": 0, "text": "Hi."}, + {"type": "turn_resumed", "seq": 6, "turn_index": 0}, + {"type": "user_backchannel", "seq": 8, "turn_index": 1, "audio_ms": 3840}, + COMMITTED, + {"type": "vad", "seq": 12, "audio_ms": 1100, "score": 0.93}, + { + "type": "eot_prob", + "seq": 13, + "turn_index": 0, + "audio_ms": 2200, + "prob": 0.42, + }, + {"type": "configured", "seq": 1, "ok": False, "config": {}, "message": "x"}, + {"type": "progress", "seq": 30, "audio_received_ms": 12000}, + error_message("invalid_request", recoverable=True), + SESSION_DONE, + ], + ids=lambda message: message["type"], + ) + def test_every_server_message_type_has_a_model(self, message): + event = decode_event(ormsgpack.packb(message)) + assert event.type == message["type"] + assert event.seq == message["seq"] + + def test_unknown_message_type_is_ignored(self): + assert decode_event(ormsgpack.packb({"type": "from_the_future"})) is None + + def test_unknown_fields_are_kept(self): + event = decode_event(ormsgpack.packb({**SPEECH_START, "confidence": 0.8})) + assert event.confidence == 0.8 + + +class TestSyncSession: + def test_streams_audio_and_yields_typed_events(self): + with serving(transcribe_script) as (server, client): + events = list( + client.asr.stream_websocket( + iter([CHUNK, b"", CHUNK]), sample_rate=16000, drafts=True + ) + ) + conn = server.stop() + + assert [event.type for event in events] == [ + "session_started", + "speech_start", + "draft", + "committed", + "session_done", + ] + assert isinstance(events[0], ASRSessionStartedEvent) + assert events[0].session_id == "s_test" + assert events[3].text == "What's the weather like?" + assert isinstance(events[4], ASRSessionDoneEvent) + assert events[4].stats.turns == 1 + + assert conn.path == "/v1/asr/realtime" + assert conn.headers["authorization"] == "Bearer test-key" + assert conn.headers["model"] == "transcribe-stream-1" + assert conn.received == [ + { + "type": "config", + "audio": {"format": "pcm_s16le", "sample_rate": 16000, "channels": 1}, + "results": {"drafts": True}, + }, + {"type": "audio", "data": CHUNK}, + {"type": "audio", "data": CHUNK}, + {"type": "audio_done"}, + ] + assert conn.close_code == 1000 + + def test_control_messages_in_the_audio_stream_keep_their_position(self): + with serving(transcribe_script) as (server, client): + list( + client.asr.stream_websocket( + iter([CHUNK, ASRFinalizeEvent(), CHUNK]), turn_detection="manual" + ) + ) + conn = server.stop() + assert conn.received[0]["turn_detection"] == {"mode": "manual"} + assert [m["type"] for m in conn.received[1:]] == [ + "audio", + "finalize", + "audio", + "audio_done", + ] + + def test_control_methods_send_during_the_session(self): + release = threading.Event() + + def audio(): + yield CHUNK + release.wait(5) + + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + conn.send(COMMITTED) + conn.recv_until("audio_done") + conn.send(SESSION_DONE) + conn.close(1000, "done") + + with serving(script) as (server, client): + stream = client.asr.stream_websocket(audio()) + with pytest.raises(WebSocketError, match="not open"): + stream.finalize() + for event in stream: + if event.type == "committed": + stream.agent_speaking(True) + stream.add_context([ASRContextItem(role="assistant", text="Hi.")]) + stream.configure( + turn_detection=ASRTurnDetection(mode="vad"), + terms=["Fish Audio"], + ) + stream.finalize() + stream.keepalive() + release.set() + with pytest.raises(WebSocketError, match="not open"): + stream.finalize() + conn = server.stop() + + control = [m for m in conn.received[1:] if m["type"] != "audio"] + assert control == [ + {"type": "agent_speaking", "speaking": True}, + { + "type": "context_add", + "items": [{"role": "assistant", "text": "Hi."}], + "reset_history": False, + }, + { + "type": "configure", + "turn_detection": {"mode": "vad"}, + "context": {"terms": ["Fish Audio"]}, + }, + {"type": "finalize"}, + {"type": "keepalive"}, + {"type": "audio_done"}, + ] + + def test_unknown_messages_are_skipped(self): + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + conn.send({"type": "from_the_future", "seq": 1}) + conn.recv_until("audio_done") + conn.send(SESSION_DONE) + conn.close(1000, "done") + + with serving(script) as (server, client): + events = list(client.asr.stream_websocket(iter([CHUNK]))) + server.stop() + assert [event.type for event in events] == ["session_started", "session_done"] + + def test_recoverable_error_is_an_event_and_the_session_continues(self): + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + conn.send(error_message("invalid_request", recoverable=True)) + conn.recv_until("audio_done") + conn.send(COMMITTED) + conn.send(SESSION_DONE) + conn.close(1000, "done") + + with serving(script) as (server, client): + events = list(client.asr.stream_websocket(iter([CHUNK]))) + server.stop() + assert [event.type for event in events] == [ + "session_started", + "error", + "committed", + "session_done", + ] + assert isinstance(events[1], ASRErrorEvent) + assert events[1].error_type == "invalid_request" + + def test_fatal_error_event_raises(self): + def script(conn): + conn.recv() + conn.send(error_message("unsupported_audio", recoverable=False)) + conn.close(4400, "unsupported_audio") + + with ( + serving(script) as (server, client), + pytest.raises(ASRRealtimeError) as exc_info, + ): + list(client.asr.stream_websocket(iter([CHUNK]))) + conn = server.stop() + + error = exc_info.value + assert isinstance(error, WebSocketError) + assert error.error_type == "unsupported_audio" + assert error.code == 400 + assert error.request_id == "req_test" + assert "unsupported_audio happened" in str(error) + assert [m["type"] for m in conn.received] == ["config"] # no audio was sent + assert conn.close_code is not None # the client closed its side + + def test_server_restarting_yields_the_error_then_raises_with_close_code(self): + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + conn.send(error_message("server_restarting", recoverable=True, code=503)) + conn.close(1012, "restarting") + + events = [] + with ( + serving(script) as (server, client), + pytest.raises(ASRRealtimeError) as exc_info, + ): + for event in client.asr.stream_websocket(endless_audio()): + events.append(event) + server.stop() + + assert [event.type for event in events] == ["session_started", "error"] + assert exc_info.value.close_code == 1012 + assert exc_info.value.error_type == "server_restarting" + + def test_abnormal_close_without_error_event_raises_with_close_code(self): + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + conn.close(1011, "boom") + + with ( + serving(script) as (server, client), + pytest.raises(ASRRealtimeError) as exc_info, + ): + list(client.asr.stream_websocket(endless_audio())) + server.stop() + assert exc_info.value.close_code == 1011 + assert exc_info.value.error_type is None + assert "boom" in str(exc_info.value) + + def test_dropped_connection_raises_websocket_error(self): + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + conn.drop() + + with serving(script) as (server, client), pytest.raises(WebSocketError): + list(client.asr.stream_websocket(endless_audio())) + server.stop() + + @pytest.mark.parametrize( + ("status", "error_class"), [(401, AuthenticationError), (402, APIError)] + ) + def test_refused_upgrade_raises_api_error(self, status, error_class): + with ( + serving(lambda conn: None, reject_status=status) as (server, client), + pytest.raises(error_class) as exc_info, + ): + list(client.asr.stream_websocket(iter([CHUNK]))) + assert exc_info.value.status == status + + def test_leaving_the_loop_early_closes_the_connection(self): + with serving(open_ended_script) as (server, client): + for event in client.asr.stream_websocket(endless_audio()): + if event.type == "committed": + break + conn = server.stop() # returns only once the client has gone + assert conn.close_code == 1000 + + def test_context_manager_closes_the_connection(self): + with serving(open_ended_script) as (server, client): + with client.asr.stream_websocket(endless_audio()) as stream: + assert next(stream).type == "session_started" + conn = server.stop() + stream.close() # safe to call again + assert list(stream) == [] + assert conn.close_code == 1000 + + def test_audio_stream_failure_is_raised_and_closes_the_connection(self): + def audio(): + yield CHUNK + raise RuntimeError("microphone unplugged") + + with serving(open_ended_script) as (server, client): + with pytest.raises(RuntimeError, match="microphone unplugged"): + list(client.asr.stream_websocket(audio())) + conn = server.stop() + assert conn.close_code == 1000 + assert [m["type"] for m in conn.received] == ["config", "audio"] + + def test_diarize_parameter_is_sent_in_config(self): + with serving(transcribe_script) as (server, client): + list(client.asr.stream_websocket(iter([CHUNK]), diarize=False)) + conn = server.stop() + assert conn.received[0]["results"] == {"diarize": False} + + def test_early_exit_stops_the_sender_and_closes_the_audio_generator(self): + closed = threading.Event() + + def audio(): + try: + while True: + yield CHUNK + time.sleep(0.01) + finally: + closed.set() + + with serving(open_ended_script) as (server, client): + with client.asr.stream_websocket(audio()) as stream: + next(stream) + server.stop() + assert closed.wait(2) + assert wait_for_no_sender_threads() + + def test_blocked_audio_stream_is_not_interrupted_but_stops_at_its_next_chunk( + self, + ): + waiting = threading.Event() + release = threading.Event() + closed = threading.Event() + + def audio(): + try: + yield CHUNK + waiting.set() + release.wait(10) # a microphone read that blocks + yield CHUNK + yield CHUNK + finally: + closed.set() + + with serving(open_ended_script) as (server, client): + stream = client.asr.stream_websocket(audio()) + for event in stream: + if event.type == "committed": + break + assert waiting.wait(2) + stream.close() # the generator is running in the sender thread + conn = server.stop() + + # The SDK cannot interrupt the blocked read: the thread is still there. + assert sender_threads() + assert not closed.is_set() + + release.set() + assert closed.wait(2) # closed by the sender thread at the next chunk + assert wait_for_no_sender_threads() + assert [m["type"] for m in conn.received] == ["config", "audio"] + + def test_audio_stream_that_is_not_a_generator_is_not_closed(self): + class Source: + closed = False + + def __iter__(self): + return iter([CHUNK]) + + def close(self): + self.closed = True + + source = Source() + with serving(transcribe_script) as (server, client): + list(client.asr.stream_websocket(source)) + server.stop() + assert wait_for_no_sender_threads() + assert source.closed is False + + def test_failing_generator_cleanup_does_not_reach_the_consumer(self): + def audio(): + try: + while True: + yield CHUNK + time.sleep(0.01) + finally: + raise RuntimeError("cleanup failed") + + with serving(open_ended_script) as (server, client): + with client.asr.stream_websocket(audio()) as stream: + next(stream) + server.stop() + assert wait_for_no_sender_threads() + + +class TestAsyncSession: + async def test_streams_audio_and_yields_typed_events(self): + async with aserving(transcribe_script) as (server, client): + events = [ + event + async for event in client.asr.stream_websocket( + aiter_chunks(CHUNK, b"", CHUNK), sample_rate=16000, drafts=True + ) + ] + conn = await astop(server) + + assert [event.type for event in events] == [ + "session_started", + "speech_start", + "draft", + "committed", + "session_done", + ] + assert events[3].text == "What's the weather like?" + assert conn.path == "/v1/asr/realtime" + assert conn.headers["authorization"] == "Bearer test-key" + assert conn.headers["model"] == "transcribe-stream-1" + assert conn.received == [ + { + "type": "config", + "audio": {"format": "pcm_s16le", "sample_rate": 16000, "channels": 1}, + "results": {"drafts": True}, + }, + {"type": "audio", "data": CHUNK}, + {"type": "audio", "data": CHUNK}, + {"type": "audio_done"}, + ] + assert conn.close_code == 1000 + + async def test_control_messages_in_the_audio_stream_keep_their_position(self): + async with aserving(transcribe_script) as (server, client): + async for _ in client.asr.stream_websocket( + aiter_chunks(CHUNK, ASRFinalizeEvent(), CHUNK) + ): + pass + conn = await astop(server) + assert [m["type"] for m in conn.received[1:]] == [ + "audio", + "finalize", + "audio", + "audio_done", + ] + + async def test_control_methods_send_during_the_session(self): + release = asyncio.Event() + + async def audio(): + yield CHUNK + await asyncio.wait_for(release.wait(), 5) + + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + conn.send(COMMITTED) + conn.recv_until("audio_done") + conn.send(SESSION_DONE) + conn.close(1000, "done") + + async with aserving(script) as (server, client): + stream = client.asr.stream_websocket(audio()) + with pytest.raises(WebSocketError, match="not open"): + await stream.finalize() + async for event in stream: + if event.type == "committed": + await stream.agent_speaking(True) + await stream.add_context( + [ASRContextItem(role="assistant", text="Hi.")] + ) + await stream.configure(results=ASRResults(drafts=True)) + await stream.finalize() + await stream.keepalive() + release.set() + with pytest.raises(WebSocketError, match="not open"): + await stream.finalize() + conn = await astop(server) + + control = [m for m in conn.received[1:] if m["type"] != "audio"] + assert control == [ + {"type": "agent_speaking", "speaking": True}, + { + "type": "context_add", + "items": [{"role": "assistant", "text": "Hi."}], + "reset_history": False, + }, + {"type": "configure", "results": {"drafts": True}}, + {"type": "finalize"}, + {"type": "keepalive"}, + {"type": "audio_done"}, + ] + + async def test_recoverable_error_is_an_event_and_the_session_continues(self): + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + conn.send(error_message("invalid_request", recoverable=True)) + conn.recv_until("audio_done") + conn.send(SESSION_DONE) + conn.close(1000, "done") + + async with aserving(script) as (server, client): + events = [ + event + async for event in client.asr.stream_websocket(aiter_chunks(CHUNK)) + ] + await astop(server) + assert [event.type for event in events] == [ + "session_started", + "error", + "session_done", + ] + + async def test_fatal_error_event_raises(self): + def script(conn): + conn.recv() + conn.send(error_message("invalid_config", recoverable=False)) + conn.close(4400, "invalid_config") + + async with aserving(script) as (server, client): + with pytest.raises(ASRRealtimeError) as exc_info: + async for _ in client.asr.stream_websocket(aiter_chunks(CHUNK)): + pass + conn = await astop(server) + assert exc_info.value.error_type == "invalid_config" + assert exc_info.value.code == 400 + assert [m["type"] for m in conn.received] == ["config"] + assert conn.close_code is not None + + async def test_server_restarting_yields_the_error_then_raises_with_close_code( + self, + ): + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + conn.send(error_message("server_restarting", recoverable=True, code=503)) + conn.close(1012, "restarting") + + events = [] + async with aserving(script) as (server, client): + with pytest.raises(ASRRealtimeError) as exc_info: + async for event in client.asr.stream_websocket(aendless_audio()): + events.append(event) + await astop(server) + assert [event.type for event in events] == ["session_started", "error"] + assert exc_info.value.close_code == 1012 + assert exc_info.value.error_type == "server_restarting" + + async def test_dropped_connection_raises_websocket_error(self): + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + conn.drop() + + async with aserving(script) as (server, client): + with pytest.raises(WebSocketError): + async for _ in client.asr.stream_websocket(aendless_audio()): + pass + await astop(server) + + @pytest.mark.parametrize( + ("status", "error_class"), [(401, AuthenticationError), (402, APIError)] + ) + async def test_refused_upgrade_raises_api_error(self, status, error_class): + async with aserving(lambda conn: None, reject_status=status) as (_, client): + with pytest.raises(error_class) as exc_info: + async for _ in client.asr.stream_websocket(aiter_chunks(CHUNK)): + pass + assert exc_info.value.status == status + + async def test_leaving_the_loop_early_closes_the_connection(self): + async with aserving(open_ended_script) as (server, client): + async for event in client.asr.stream_websocket(aendless_audio()): + if event.type == "committed": + break + conn = await astop(server) # returns only once the client has gone + assert conn.close_code == 1000 + + async def test_context_manager_closes_the_connection(self): + async with aserving(open_ended_script) as (server, client): + async with client.asr.stream_websocket(aendless_audio()) as stream: + assert (await stream.__anext__()).type == "session_started" + conn = await astop(server) + await stream.aclose() # safe to call again + assert [event async for event in stream] == [] + assert conn.close_code == 1000 + + async def test_audio_stream_failure_is_raised_and_closes_the_connection(self): + async def audio(): + yield CHUNK + raise RuntimeError("microphone unplugged") + + async with aserving(open_ended_script) as (server, client): + with pytest.raises(RuntimeError, match="microphone unplugged"): + async for _ in client.asr.stream_websocket(audio()): + pass + conn = await astop(server) + assert conn.close_code == 1000 + assert [m["type"] for m in conn.received] == ["config", "audio"] + + async def test_diarize_parameter_is_sent_in_config(self): + async with aserving(transcribe_script) as (server, client): + async for _ in client.asr.stream_websocket( + aiter_chunks(CHUNK), diarize=False + ): + pass + conn = await astop(server) + assert conn.received[0]["results"] == {"diarize": False} + + async def test_closing_closes_the_audio_generator(self): + closed = asyncio.Event() + + async def audio(): + try: + while True: + yield CHUNK + await asyncio.sleep(0.01) + finally: + closed.set() + + async with aserving(open_ended_script) as (server, client): + async with client.asr.stream_websocket(audio()) as stream: + await stream.__anext__() + assert closed.is_set() # already closed when aclose() returns + await astop(server) + + async def test_slow_consumer_gets_backpressure_instead_of_unbounded_buffering( + self, + ): + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + for seq in range(1, 601): + conn.send({**DRAFT, "seq": seq}) + + async with aserving(script) as (server, client): + stream = client.asr.stream_websocket(aendless_audio()) + assert (await stream.__anext__()).type == "session_started" + await asyncio.sleep(0.5) # the consumer stops reading + + assert stream._events.maxsize == asr_realtime._EVENT_QUEUE_SIZE + assert stream._events.qsize() == asr_realtime._EVENT_QUEUE_SIZE + + # The session task is waiting on the full queue: closing must still work. + await asyncio.wait_for(stream.aclose(), 2) + assert stream._task.done() + await astop(server) + + async def test_events_and_final_error_are_delivered_through_a_full_queue( + self, monkeypatch + ): + monkeypatch.setattr(asr_realtime, "_EVENT_QUEUE_SIZE", 2) + + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + for seq in range(1, 6): + conn.send({**DRAFT, "seq": seq}) + conn.close(1011, "boom") + + events = [] + async with aserving(script) as (server, client): + stream = client.asr.stream_websocket(aendless_audio()) + events.append(await stream.__anext__()) + await asyncio.sleep(0.3) # let the queue fill up + assert stream._events.qsize() == 2 + with pytest.raises(ASRRealtimeError) as exc_info: + async for event in stream: + events.append(event) + await astop(server) + assert [event.seq for event in events] == [0, 1, 2, 3, 4, 5] + assert exc_info.value.close_code == 1011 + + async def test_leaving_the_loop_with_a_full_queue_closes_the_connection( + self, monkeypatch + ): + monkeypatch.setattr(asr_realtime, "_EVENT_QUEUE_SIZE", 1) + + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + for seq in range(1, 6): + conn.send({**DRAFT, "seq": seq}) + + async with aserving(script) as (server, client): + async for _ in client.asr.stream_websocket(aendless_audio()): + await asyncio.sleep(0.2) # the session task blocks on the queue + break + await astop(server) # returns only once the client has gone From 74af21a1864841eff28b2b4e2baadc073c2cbd74 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:58:18 -0800 Subject: [PATCH 3/9] fix(asr): close three gaps in realtime session error handling - A network failure while sending the opening config frame surfaced as httpx-ws's own exception. It now raises WebSocketError like a failure on any later frame (sync and async). - aclose() from another task left a consumer waiting in __anext__ forever: a cancelled session task queues no end marker. The consumer now also watches the session task and stops when it is gone. - If the audio stream awaited something that was cancelled, the sender task ended as cancelled, which was treated as "no failure", so the session kept polling. It now ends with a WebSocketError. Co-Authored-By: Claude Fable 5.2 --- src/fishaudio/resources/asr_realtime.py | 50 ++++++++++++++-- tests/unit/test_asr_realtime.py | 77 +++++++++++++++++++++++++ 2 files changed, 122 insertions(+), 5 deletions(-) diff --git a/src/fishaudio/resources/asr_realtime.py b/src/fishaudio/resources/asr_realtime.py index 1292676..0a2e5e2 100644 --- a/src/fishaudio/resources/asr_realtime.py +++ b/src/fishaudio/resources/asr_realtime.py @@ -248,7 +248,10 @@ def _iter_session( try: with connect() as ws: try: - ws.send_bytes(config) + try: + ws.send_bytes(config) + except HTTPXWSException as e: + raise WebSocketError("WebSocket connection lost") from e while True: try: message = ws.receive_bytes( @@ -417,8 +420,13 @@ async def _asend_audio( def _failure(task: Optional[asyncio.Task[None]]) -> Optional[BaseException]: - if task is None or not task.done() or task.cancelled(): + """Why the audio sender stopped early, if it did.""" + if task is None or not task.done(): return None + if task.cancelled(): + # Not our doing (cleanup cancels it only after the receive loop has ended): + # the audio stream awaited something that was cancelled. + return WebSocketError("Audio stream was cancelled before the session ended") return task.exception() @@ -450,7 +458,10 @@ async def _run_session( try: async with connect() as ws: try: - await ws.send_bytes(config) + try: + await ws.send_bytes(config) + except HTTPXWSException as e: + raise WebSocketError("WebSocket connection lost") from e while True: failure = _failure(sender) try: @@ -485,7 +496,8 @@ async def _run_session( if sender is not None: sender.cancel() await asyncio.wait({sender}) - _failure(sender) # mark a late exception as retrieved + if not sender.cancelled(): + sender.exception() # mark a late exception as retrieved except WebSocketUpgradeError as e: error = _upgrade_error(e.response) error.__cause__ = e @@ -546,7 +558,10 @@ async def __anext__(self) -> ASRRealtimeEvent: self._audio_stream, ) ) - item = await self._events.get() + item = await self._next_item(self._events, self._task) + if item is None: # closed by aclose() while waiting + self._finished = True + raise StopAsyncIteration if isinstance(item, _End): self._finished = True if item.error is not None: @@ -554,6 +569,31 @@ async def __anext__(self) -> ASRRealtimeEvent: raise StopAsyncIteration return item + @staticmethod + async def _next_item( + events: asyncio.Queue[Union[ASRRealtimeEvent, _End]], + task: Optional[asyncio.Task[None]], + ) -> Union[ASRRealtimeEvent, _End, None]: + """The next queue item, or None once the session task is gone and the queue is empty. + + A session that ends by itself always queues an ``_End`` first. One that is + cancelled (``aclose()`` from another task) queues nothing, so waiting on + the queue alone would block this consumer forever. + """ + if not events.empty() or task is None: + return await events.get() + get = asyncio.ensure_future(events.get()) + try: + await asyncio.wait({get, task}, return_when=asyncio.FIRST_COMPLETED) + finally: + if not get.done(): + get.cancel() + if get.done() and not get.cancelled(): + return get.result() + with contextlib.suppress(asyncio.QueueEmpty): + return events.get_nowait() + return None + async def __aenter__(self) -> AsyncASRRealtimeStream: return self diff --git a/tests/unit/test_asr_realtime.py b/tests/unit/test_asr_realtime.py index a1f86d2..9aadb96 100644 --- a/tests/unit/test_asr_realtime.py +++ b/tests/unit/test_asr_realtime.py @@ -12,6 +12,7 @@ import ormsgpack import pytest +from httpx_ws import WebSocketNetworkError from fishaudio import ( APIError, @@ -24,6 +25,8 @@ from fishaudio.resources import asr_realtime from fishaudio.resources.asr import _realtime_config from fishaudio.resources.asr_realtime import ( + ASRRealtimeStream, + AsyncASRRealtimeStream, decode_event, encode_config, encode_message, @@ -578,6 +581,23 @@ def script(conn): list(client.asr.stream_websocket(endless_audio())) server.stop() + def test_connection_lost_while_sending_config_raises_websocket_error(self): + """A network failure on the first frame is a WebSocketError, not httpx-ws's own.""" + + class LostSession: + def send_bytes(self, data): + raise WebSocketNetworkError + + @contextlib.contextmanager + def connect(): + yield LostSession() + + stream = ASRRealtimeStream(connect, ASRRealtimeConfig(), endless_audio()) + with pytest.raises(WebSocketError) as exc_info: + list(stream) + assert not isinstance(exc_info.value, ASRRealtimeError) + assert isinstance(exc_info.value.__cause__, WebSocketNetworkError) + @pytest.mark.parametrize( ("status", "error_class"), [(401, AuthenticationError), (402, APIError)] ) @@ -873,6 +893,24 @@ def script(conn): pass await astop(server) + async def test_connection_lost_while_sending_config_raises_websocket_error(self): + """A network failure on the first frame is a WebSocketError, not httpx-ws's own.""" + + class LostSession: + async def send_bytes(self, data): + raise WebSocketNetworkError + + @contextlib.asynccontextmanager + async def connect(): + yield LostSession() + + stream = AsyncASRRealtimeStream(connect, ASRRealtimeConfig(), aendless_audio()) + with pytest.raises(WebSocketError) as exc_info: + async for _ in stream: + pass + assert not isinstance(exc_info.value, ASRRealtimeError) + assert isinstance(exc_info.value.__cause__, WebSocketNetworkError) + @pytest.mark.parametrize( ("status", "error_class"), [(401, AuthenticationError), (402, APIError)] ) @@ -939,6 +977,45 @@ async def audio(): assert closed.is_set() # already closed when aclose() returns await astop(server) + async def test_aclose_from_another_task_wakes_a_waiting_consumer(self): + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + conn.wait_gone() # no more events: the consumer blocks in __anext__ + + async with aserving(script) as (server, client): + stream = client.asr.stream_websocket(aendless_audio()) + + async def consume(): + return [event.type async for event in stream] + + consumer = asyncio.create_task(consume()) + await asyncio.sleep(0.3) # session_started received, now waiting + await asyncio.wait_for(stream.aclose(), 2) + + assert await asyncio.wait_for(consumer, 2) == ["session_started"] + await astop(server) + + async def test_cancelled_audio_stream_ends_the_session_with_an_error(self): + async def audio(): + yield CHUNK + cancelled = asyncio.get_running_loop().create_future() + cancelled.cancel() + await ( + cancelled + ) # e.g. the capture task this iterator waits on was cancelled + + async def consume(stream): + async for _ in stream: + pass + + async with aserving(open_ended_script) as (server, client): + stream = client.asr.stream_websocket(audio()) + with pytest.raises(WebSocketError, match="cancelled"): + await asyncio.wait_for(consume(stream), 3) + conn = await astop(server) + assert conn.close_code == 1000 + async def test_slow_consumer_gets_backpressure_instead_of_unbounded_buffering( self, ): From 723ff419bfcac450695a71eabd3bb68d27e69469 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:34:21 -0800 Subject: [PATCH 4/9] fix(asr): harden realtime session shutdown and failure reporting - close() could hang when many events were unread: httpx-ws's reader thread blocks putting into its full queue and its __exit__ joins that thread without a timeout. drain_reader() now discards the unread events until the reader exits (also covers tts.stream_websocket). - A failed audio stream is reported within one fixed drain window, even while events keep arriving, and also when the server then closes normally (it used to end the iteration silently). - The sync session closes the connection before handing out session_done, so a caller that stops there does not leave it open. - A header set by a method now replaces one of a different case from RequestOptions, so transcribe(model=...) cannot send two model headers. Document the precedence. - Document that a consumer stalled past the keepalive timeout while events keep arriving loses the connection. - Test server: quiet_for() waits the whole interval. Co-Authored-By: Claude Fable 5.2 --- src/fishaudio/core/_ws_utils.py | 18 +++- src/fishaudio/core/client_wrapper.py | 9 +- src/fishaudio/resources/asr.py | 12 ++- src/fishaudio/resources/asr_realtime.py | 57 ++++++++++-- tests/unit/realtime_server.py | 20 +++-- tests/unit/test_asr_realtime.py | 112 ++++++++++++++++++++++++ tests/unit/test_core.py | 24 +++++ tests/unit/test_ws_utils.py | 6 +- 8 files changed, 234 insertions(+), 24 deletions(-) diff --git a/src/fishaudio/core/_ws_utils.py b/src/fishaudio/core/_ws_utils.py index 9bc0574..edcdfbf 100644 --- a/src/fishaudio/core/_ws_utils.py +++ b/src/fishaudio/core/_ws_utils.py @@ -4,7 +4,9 @@ import contextlib import logging +import queue import socket +import time from typing import Any import wsproto.events @@ -59,8 +61,18 @@ def drain_reader(ws: Any) -> None: thread = getattr(ws, "_background_receive_task", None) if thread is not None: - # 5 s is the worst case only when the reader is stuck; httpx-ws's own - # untimed join in __exit__ would hang afterwards anyway. - thread.join(timeout=5) + # The reader can also be blocked putting an event into httpx-ws's + # bounded queue (the consumer stopped reading). Nothing will read + # those events any more, so discard them until the thread exits; + # httpx-ws's own untimed join in __exit__ would hang otherwise. + events = getattr(ws, "_events", None) + deadline = time.monotonic() + 5 + thread.join(timeout=0.02) + while thread.is_alive() is True and time.monotonic() < deadline: + if isinstance(events, queue.Queue): + with contextlib.suppress(queue.Empty): + while True: + events.get_nowait() + thread.join(timeout=0.02) except Exception: logger.debug("drain_reader failed; falling back to plain close", exc_info=True) diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index 790e714..534c81f 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -84,7 +84,14 @@ def _prepare_request_kwargs( headers = self.get_headers() if request_options and request_options.additional_headers: headers.update(request_options.additional_headers) - kwargs["headers"] = {**headers, **kwargs.get("headers", {})} + # Headers set by the calling method win, whatever the case of the name: + # {"Model": ...} from request options must not travel next to {"model": ...}. + explicit = kwargs.get("headers", {}) + explicit_names = {name.lower() for name in explicit} + kwargs["headers"] = { + **{k: v for k, v in headers.items() if k.lower() not in explicit_names}, + **explicit, + } # Apply timeout override if provided if request_options and request_options.timeout is not None: diff --git a/src/fishaudio/resources/asr.py b/src/fishaudio/resources/asr.py index d6d0c17..514c5ac 100644 --- a/src/fishaudio/resources/asr.py +++ b/src/fishaudio/resources/asr.py @@ -82,8 +82,10 @@ def transcribe( language: Language code (e.g., "en", "zh"). Auto-detected if not provided. include_timestamps: Whether to include timestamp information for segments (and speaker turns, on models that return them) - model: ASR model, e.g. "transcribe-1-pro" (recommended). If not provided, - the request runs on the API's default model, transcribe-1 + model: ASR model, e.g. "transcribe-1-pro" (recommended). Sent as the + ``model`` header and takes precedence over one in request_options. + If not provided and request_options sets no ``model`` header, the + request runs on the API's default model, transcribe-1 request_options: Request-level overrides Returns: @@ -267,8 +269,10 @@ async def transcribe( language: Language code (e.g., "en", "zh"). Auto-detected if not provided. include_timestamps: Whether to include timestamp information for segments (and speaker turns, on models that return them) - model: ASR model, e.g. "transcribe-1-pro" (recommended). If not provided, - the request runs on the API's default model, transcribe-1 + model: ASR model, e.g. "transcribe-1-pro" (recommended). Sent as the + ``model`` header and takes precedence over one in request_options. + If not provided and request_options sets no ``model`` header, the + request runs on the API's default model, transcribe-1 request_options: Request-level overrides Returns: diff --git a/src/fishaudio/resources/asr_realtime.py b/src/fishaudio/resources/asr_realtime.py index 0a2e5e2..ed630bf 100644 --- a/src/fishaudio/resources/asr_realtime.py +++ b/src/fishaudio/resources/asr_realtime.py @@ -8,6 +8,7 @@ import logging import queue import threading +import time from typing import ( TYPE_CHECKING, Any, @@ -245,6 +246,8 @@ def _iter_session( protocol = _Protocol() failure: list[BaseException] = [] sender: Optional[threading.Thread] = None + done: Optional[ASRSessionDoneEvent] = None + drain_until: Optional[float] = None try: with connect() as ws: try: @@ -252,17 +255,27 @@ def _iter_session( ws.send_bytes(config) except HTTPXWSException as e: raise WebSocketError("WebSocket connection lost") from e - while True: + while done is None: + if failure and drain_until is None: + # One deadline for the whole drain: events that keep + # arriving must not postpone the audio stream's error. + drain_until = time.monotonic() + _DRAIN_SECONDS + if drain_until is not None and time.monotonic() >= drain_until: + raise failure[0] try: message = ws.receive_bytes( - timeout=_DRAIN_SECONDS if failure else _POLL_SECONDS + timeout=_POLL_SECONDS + if drain_until is None + else max(drain_until - time.monotonic(), 0.001) ) except (queue.Empty, TimeoutError): # httpx-ws < 0.8 / >= 0.8 - if failure: - raise failure[0] from None continue except WebSocketDisconnect as e: protocol.on_close(e.code, e.reason) + if ( + failure + ): # a normal close does not hide a failed audio stream + raise failure[0] from None return except HTTPXWSException as e: raise WebSocketError("WebSocket connection lost") from e @@ -270,6 +283,9 @@ def _iter_session( event = protocol.on_message(message) if event is None: continue + if isinstance(event, ASRSessionDoneEvent): + done = event + continue if isinstance(event, ASRSessionStartedEvent) and sender is None: link.open(ws) sender = threading.Thread( @@ -280,13 +296,15 @@ def _iter_session( ) sender.start() yield event - if isinstance(event, ASRSessionDoneEvent): - return finally: link.close() # Stop httpx-ws's reader thread before the socket is closed so it # cannot read from a reused fd belonging to the next connection. drain_reader(ws) + # The connection is closed before the last event is handed out, so a + # caller that stops at session_done does not leave it open. + if done is not None: + yield done except WebSocketUpgradeError as e: raise _upgrade_error(e.response) from e @@ -462,18 +480,34 @@ async def _run_session( await ws.send_bytes(config) except HTTPXWSException as e: raise WebSocketError("WebSocket connection lost") from e + drain_until: Optional[float] = None while True: failure = _failure(sender) + if failure and drain_until is None: + # One deadline for the whole drain: events that keep + # arriving must not postpone the audio stream's error. + drain_until = time.monotonic() + _DRAIN_SECONDS + if ( + failure is not None + and drain_until is not None + and time.monotonic() >= drain_until + ): + raise failure try: message = await ws.receive_bytes( - timeout=_DRAIN_SECONDS if failure else _POLL_SECONDS + timeout=_POLL_SECONDS + if drain_until is None + else max(drain_until - time.monotonic(), 0.001) ) except TimeoutError: - if failure: - raise failure from None continue except WebSocketDisconnect as e: protocol.on_close(e.code, e.reason) + failure = _failure(sender) + if ( + failure + ): # a normal close does not hide a failed audio stream + raise failure from None break except HTTPXWSException as e: raise WebSocketError("WebSocket connection lost") from e @@ -523,6 +557,11 @@ class AsyncASRRealtimeStream: The control methods send a message at the current position in the audio stream; they can be awaited once ``session_started`` has been received. + + Keep reading: when you stop, the SDK buffers a few hundred events and then + stops reading from the connection, which also stops it answering keepalive + pings. A consumer that stays stalled past the keepalive timeout (20 s by + default, see ``ws_options``) while events keep arriving loses the connection. """ def __init__( diff --git a/tests/unit/realtime_server.py b/tests/unit/realtime_server.py index f772a09..550e573 100644 --- a/tests/unit/realtime_server.py +++ b/tests/unit/realtime_server.py @@ -9,6 +9,7 @@ import contextlib import socket import threading +import time from collections import deque from typing import Any, Callable, Optional @@ -105,12 +106,21 @@ def recv_until(self, message_type: str) -> list[dict[str, Any]]: return messages def quiet_for(self, seconds: float) -> bool: - """True if the client sends nothing for the given time.""" - self._sock.settimeout(seconds) + """True if the client sends no message for the whole of the given time. + + Pings and partial frames do not end the wait early. + """ + deadline = time.monotonic() + seconds try: - self._read() - except socket.timeout: - return not self._pending + while not self._pending: + remaining = deadline - time.monotonic() + if remaining <= 0: + break + self._sock.settimeout(remaining) + try: + self._read() + except socket.timeout: + break finally: self._sock.settimeout(5) return not self._pending diff --git a/tests/unit/test_asr_realtime.py b/tests/unit/test_asr_realtime.py index 9aadb96..2be2777 100644 --- a/tests/unit/test_asr_realtime.py +++ b/tests/unit/test_asr_realtime.py @@ -581,6 +581,79 @@ def script(conn): list(client.asr.stream_websocket(endless_audio())) server.stop() + def test_audio_failure_is_not_delayed_by_a_steady_stream_of_events(self): + def audio(): + yield CHUNK + raise RuntimeError("microphone unplugged") + + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + conn.recv() # the one audio chunk + with contextlib.suppress(OSError): # the client leaves before the end + for seq in range(200): # an event every 10 ms for 2 s + conn.send({**DRAFT, "seq": seq}) + time.sleep(0.01) + + with serving(script) as (server, client): + started = time.monotonic() + with pytest.raises(RuntimeError, match="microphone unplugged"): + list(client.asr.stream_websocket(audio())) + assert time.monotonic() - started < 1.0 + server.stop() + + def test_audio_failure_is_raised_when_the_server_closes_normally(self): + def audio(): + yield CHUNK + raise RuntimeError("microphone unplugged") + + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + conn.recv() # the one audio chunk + conn.close(1000, "bye") + + with ( + serving(script) as (server, client), + pytest.raises(RuntimeError, match="microphone unplugged"), + ): + list(client.asr.stream_websocket(audio())) + server.stop() + + def test_connection_is_closed_once_session_done_is_returned(self): + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + conn.recv_until("audio_done") + conn.send(SESSION_DONE) + + with serving(script) as (server, client): + stream = client.asr.stream_websocket(iter([CHUNK])) + assert next(stream).type == "session_started" + assert next(stream).type == "session_done" + # No further next() or close(): the client must already be gone. + conn = server.stop() + assert list(stream) == [] + assert conn.close_code == 1000 + + def test_close_does_not_hang_when_many_events_are_unread(self): + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + for seq in range(800): # more than httpx-ws's receive queue holds + conn.send({**DRAFT, "seq": seq}) + + with serving(script) as (server, client): + stream = client.asr.stream_websocket(endless_audio()) + assert next(stream).type == "session_started" + time.sleep(0.5) # the consumer stops reading; the transport queue fills + + closer = threading.Thread(target=stream.close, daemon=True) + closer.start() + closer.join(3) + assert not closer.is_alive(), "close() is stuck" + server.stop() + def test_connection_lost_while_sending_config_raises_websocket_error(self): """A network failure on the first frame is a WebSocketError, not httpx-ws's own.""" @@ -977,6 +1050,45 @@ async def audio(): assert closed.is_set() # already closed when aclose() returns await astop(server) + async def test_audio_failure_is_not_delayed_by_a_steady_stream_of_events(self): + async def audio(): + yield CHUNK + raise RuntimeError("microphone unplugged") + + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + conn.recv() + with contextlib.suppress(OSError): # the client leaves before the end + for seq in range(200): + conn.send({**DRAFT, "seq": seq}) + time.sleep(0.01) + + async with aserving(script) as (server, client): + started = time.monotonic() + with pytest.raises(RuntimeError, match="microphone unplugged"): + async for _ in client.asr.stream_websocket(audio()): + pass + assert time.monotonic() - started < 1.0 + await astop(server) + + async def test_audio_failure_is_raised_when_the_server_closes_normally(self): + async def audio(): + yield CHUNK + raise RuntimeError("microphone unplugged") + + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + conn.recv() + conn.close(1000, "bye") + + async with aserving(script) as (server, client): + with pytest.raises(RuntimeError, match="microphone unplugged"): + async for _ in client.asr.stream_websocket(audio()): + pass + await astop(server) + async def test_aclose_from_another_task_wakes_a_waiting_consumer(self): def script(conn): conn.recv() diff --git a/tests/unit/test_core.py b/tests/unit/test_core.py index e979689..ce38383 100644 --- a/tests/unit/test_core.py +++ b/tests/unit/test_core.py @@ -125,6 +125,30 @@ def test_get_headers_with_additional(self, mock_api_key): assert headers["Authorization"] == f"Bearer {mock_api_key}" +class TestRequestHeaders: + """Headers passed by a method win over RequestOptions, whatever their case.""" + + def test_explicit_header_replaces_additional_header_of_other_case( + self, mock_api_key + ): + wrapper = ClientWrapper(api_key=mock_api_key) + kwargs = {"headers": {"model": "transcribe-1-pro"}} + wrapper._prepare_request_kwargs( + RequestOptions(additional_headers={"Model": "transcribe-1"}), kwargs + ) + models = {k: v for k, v in kwargs["headers"].items() if k.lower() == "model"} + assert models == {"model": "transcribe-1-pro"} + + def test_additional_header_is_kept_without_an_explicit_one(self, mock_api_key): + wrapper = ClientWrapper(api_key=mock_api_key) + kwargs = {} + wrapper._prepare_request_kwargs( + RequestOptions(additional_headers={"Model": "transcribe-1-pro"}), kwargs + ) + assert kwargs["headers"]["Model"] == "transcribe-1-pro" + assert kwargs["headers"]["Authorization"] == f"Bearer {mock_api_key}" + + class TestAsyncClientWrapper: """Test async AsyncClientWrapper.""" diff --git a/tests/unit/test_ws_utils.py b/tests/unit/test_ws_utils.py index b72a3c0..ce7d045 100644 --- a/tests/unit/test_ws_utils.py +++ b/tests/unit/test_ws_utils.py @@ -25,6 +25,7 @@ class TestDrainReader: def test_sends_close_frame_then_shuts_down_socket_and_joins_reader(self): sock = Mock() thread = Mock() + thread.is_alive.return_value = False # the reader exits on the first join ws = _make_ws(sock, thread) parent = Mock() parent.attach_mock(ws.send, "send") @@ -38,7 +39,7 @@ def test_sends_close_frame_then_shuts_down_socket_and_joins_reader(self): assert isinstance(event, wsproto.events.CloseConnection) assert event.code == 1000 sock.shutdown.assert_called_once_with(socket.SHUT_RDWR) - thread.join.assert_called_once_with(timeout=5) + thread.join.assert_called_once_with(timeout=0.02) def test_falls_back_to_response_network_stream(self): sock = Mock() @@ -62,8 +63,9 @@ def test_joins_reader_when_socket_shutdown_fails(self): sock = Mock() sock.shutdown.side_effect = OSError("already closed") thread = Mock() + thread.is_alive.return_value = False drain_reader(_make_ws(sock, thread)) - thread.join.assert_called_once_with(timeout=5) + thread.join.assert_called_once_with(timeout=0.02) def test_tolerates_missing_socket_and_thread(self): ws = Mock() From 08949367b0d9142336de959aacf04350c2d460d7 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 23 Nov 2026 05:03:05 -0800 Subject: [PATCH 5/9] fix(asr): keep the event of a cancelled async read AsyncASRRealtimeStream.__anext__ waited on a temporary queue getter together with the session task. If the read was cancelled after the getter had taken an event but before __anext__ returned (for example by asyncio.wait_for timing out), the event was dropped with the getter. Keep the getter on the stream across calls: a cancelled read leaves it in place and the next read picks up its event. aclose() and __del__ cancel a getter that is still pending, so a consumer that stops reading after a cancelled read leaves no task behind. Co-Authored-By: Claude Fable 5.2 --- src/fishaudio/resources/asr_realtime.py | 51 +++++++++++------ tests/unit/test_asr_realtime.py | 76 +++++++++++++++++++++++++ 2 files changed, 110 insertions(+), 17 deletions(-) diff --git a/src/fishaudio/resources/asr_realtime.py b/src/fishaudio/resources/asr_realtime.py index ed630bf..52eaca0 100644 --- a/src/fishaudio/resources/asr_realtime.py +++ b/src/fishaudio/resources/asr_realtime.py @@ -576,6 +576,9 @@ def __init__( self._audio_stream = audio_stream self._events: Optional[asyncio.Queue[Union[ASRRealtimeEvent, _End]]] = None self._task: Optional[asyncio.Task[None]] = None + # The pending read of the queue. It outlives a cancelled __anext__, so an + # event it has already taken is handed to the next read instead of lost. + self._getter: Optional[asyncio.Future[Union[ASRRealtimeEvent, _End]]] = None self._finished = False def __aiter__(self) -> AsyncASRRealtimeStream: @@ -597,7 +600,7 @@ async def __anext__(self) -> ASRRealtimeEvent: self._audio_stream, ) ) - item = await self._next_item(self._events, self._task) + item = await self._next_item() if item is None: # closed by aclose() while waiting self._finished = True raise StopAsyncIteration @@ -608,31 +611,42 @@ async def __anext__(self) -> ASRRealtimeEvent: raise StopAsyncIteration return item - @staticmethod - async def _next_item( - events: asyncio.Queue[Union[ASRRealtimeEvent, _End]], - task: Optional[asyncio.Task[None]], - ) -> Union[ASRRealtimeEvent, _End, None]: + async def _next_item(self) -> Union[ASRRealtimeEvent, _End, None]: """The next queue item, or None once the session task is gone and the queue is empty. A session that ends by itself always queues an ``_End`` first. One that is cancelled (``aclose()`` from another task) queues nothing, so waiting on - the queue alone would block this consumer forever. + the queue alone would block this consumer forever: wait for the queue and + the session task together. """ - if not events.empty() or task is None: - return await events.get() - get = asyncio.ensure_future(events.get()) - try: - await asyncio.wait({get, task}, return_when=asyncio.FIRST_COMPLETED) - finally: - if not get.done(): - get.cancel() - if get.done() and not get.cancelled(): - return get.result() + events, task = self._events, self._task + assert events is not None and task is not None + if self._getter is None: + with contextlib.suppress(asyncio.QueueEmpty): + return events.get_nowait() + self._getter = asyncio.ensure_future(events.get()) + getter = self._getter + if not getter.done(): + # Cancelling this wait (asyncio.wait_for around __anext__, for example) + # leaves the getter in place for the next call. + await asyncio.wait({getter, task}, return_when=asyncio.FIRST_COMPLETED) + self._getter = None + if getter.done() and not getter.cancelled(): + return getter.result() + # The session task ended first, or aclose() dropped the getter. Either way + # the getter has taken nothing: what the session queued last is still there. + getter.cancel() with contextlib.suppress(asyncio.QueueEmpty): return events.get_nowait() return None + def _drop_getter(self) -> None: + getter, self._getter = self._getter, None + if getter is not None and not getter.done(): + # RuntimeError: the event loop is already closed + with contextlib.suppress(RuntimeError): + getter.cancel() + async def __aenter__(self) -> AsyncASRRealtimeStream: return self @@ -642,11 +656,14 @@ async def __aexit__(self, *exc_info: Any) -> None: async def aclose(self) -> None: """Close the connection. Safe to call more than once.""" self._finished = True + self._drop_getter() if self._task is not None: self._task.cancel() await asyncio.wait({self._task}) def __del__(self) -> None: + if getattr(self, "_getter", None) is not None: + self._drop_getter() task = getattr(self, "_task", None) if task is not None and not task.done(): # RuntimeError: the event loop is already closed diff --git a/tests/unit/test_asr_realtime.py b/tests/unit/test_asr_realtime.py index 2be2777..5e10736 100644 --- a/tests/unit/test_asr_realtime.py +++ b/tests/unit/test_asr_realtime.py @@ -1191,3 +1191,79 @@ def script(conn): await asyncio.sleep(0.2) # the session task blocks on the queue break await astop(server) # returns only once the client has gone + + async def test_cancelled_read_does_not_lose_the_event_it_had_taken(self): + """A read cancelled after it took an event from the queue (for example by + asyncio.wait_for) must hand that event to the next read.""" + + async def read_cancelled_after(steps, marker): + read = asyncio.ensure_future(stream.__anext__()) + await asyncio.sleep(0) # the read is now waiting for an event + stream._events.put_nowait(marker) + for _ in range(steps): # let the read get this far before cancelling + await asyncio.sleep(0) + read.cancel() + with contextlib.suppress(asyncio.CancelledError): + return await read + return await asyncio.wait_for(stream.__anext__(), 1) + + async with aserving(open_ended_script) as (server, client): + async with client.asr.stream_websocket(aendless_audio()) as stream: + assert (await stream.__anext__()).type == "session_started" + assert (await stream.__anext__()).type == "committed" + + # Cancel at every point between "event queued" and "read returned". + received = [] + for steps in range(8): + marker = ASRDraftEvent(turn_index=0, text="marker", seq=steps) + received.append(await read_cancelled_after(steps, marker)) + await astop(server) + assert [event.seq for event in received] == list(range(8)) + + async def test_reading_with_timeouts_delivers_every_event_in_order(self): + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + conn.recv_until("audio_done") + for seq in range(1, 61): + conn.send({**DRAFT, "seq": seq}) + time.sleep(0.003) + conn.send({**SESSION_DONE, "seq": 61}) + conn.close(1000, "done") + + seqs = [] + timeouts = 0 + async with aserving(script) as (server, client): + stream = client.asr.stream_websocket(aiter_chunks(CHUNK)) + while True: + try: + event = await asyncio.wait_for(stream.__anext__(), 0.002) + except asyncio.TimeoutError: + timeouts += 1 + continue + except StopAsyncIteration: + break + seqs.append(event.seq) + await astop(server) + assert seqs == list(range(62)) + assert timeouts > 0 # the reads really were interrupted + + async def test_closing_after_a_cancelled_read_leaves_no_pending_task(self): + async with aserving(open_ended_script) as (server, client): + stream = client.asr.stream_websocket(aendless_audio()) + assert (await stream.__anext__()).type == "session_started" + assert (await stream.__anext__()).type == "committed" + with pytest.raises(asyncio.TimeoutError): # nothing more is coming + await asyncio.wait_for(stream.__anext__(), 0.05) + + await stream.aclose() + await stream.aclose() # safe to call again + await asyncio.sleep(0) # let cancelled tasks finish + pending = [ + task + for task in asyncio.all_tasks() + if task is not asyncio.current_task() and not task.done() + ] + assert pending == [] + assert [event async for event in stream] == [] + await astop(server) From a8458c1b857abdf2d927f53178ce31da28e0a447 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:48:32 -0800 Subject: [PATCH 6/9] fix(websocket): release a keepalive thread blocked on a full event queue After a ping timeout httpx-ws's keepalive thread closes the transport and puts an error into the event queue. If the queue is full and the reader thread has already exited, drain_reader() skipped the drain, the put never returned, and httpx-ws's untimed join of the keepalive thread hung close(). Reachable when a consumer stalls past the keepalive timeout, reads one more event and then closes. Discard the unread events once more after the reader is gone. Co-Authored-By: Claude Fable 5.2 --- src/fishaudio/core/_ws_utils.py | 20 +++++++++++++++----- tests/unit/test_ws_utils.py | 27 +++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/src/fishaudio/core/_ws_utils.py b/src/fishaudio/core/_ws_utils.py index edcdfbf..cf71210 100644 --- a/src/fishaudio/core/_ws_utils.py +++ b/src/fishaudio/core/_ws_utils.py @@ -59,20 +59,30 @@ def drain_reader(ws: Any) -> None: with contextlib.suppress(OSError): sock.shutdown(socket.SHUT_RDWR) + events = getattr(ws, "_events", None) + + def discard_unread_events() -> None: + if isinstance(events, queue.Queue): + with contextlib.suppress(queue.Empty): + while True: + events.get_nowait() + thread = getattr(ws, "_background_receive_task", None) if thread is not None: # The reader can also be blocked putting an event into httpx-ws's # bounded queue (the consumer stopped reading). Nothing will read # those events any more, so discard them until the thread exits; # httpx-ws's own untimed join in __exit__ would hang otherwise. - events = getattr(ws, "_events", None) deadline = time.monotonic() + 5 thread.join(timeout=0.02) while thread.is_alive() is True and time.monotonic() < deadline: - if isinstance(events, queue.Queue): - with contextlib.suppress(queue.Empty): - while True: - events.get_nowait() + discard_unread_events() thread.join(timeout=0.02) + + # The keepalive thread writes to the same queue: after a ping timeout it + # closes the transport and puts an error. With the queue still full and + # the reader gone it would block there, and httpx-ws joins it without a + # timeout too. Make room once more now that the reader adds nothing. + discard_unread_events() except Exception: logger.debug("drain_reader failed; falling back to plain close", exc_info=True) diff --git a/tests/unit/test_ws_utils.py b/tests/unit/test_ws_utils.py index ce7d045..8d74a85 100644 --- a/tests/unit/test_ws_utils.py +++ b/tests/unit/test_ws_utils.py @@ -1,5 +1,6 @@ """Tests for the sync WebSocket reader-draining helper.""" +import queue import socket import threading from unittest.mock import Mock, patch @@ -67,6 +68,32 @@ def test_joins_reader_when_socket_shutdown_fails(self): drain_reader(_make_ws(sock, thread)) thread.join.assert_called_once_with(timeout=0.02) + def test_releases_keepalive_thread_blocked_on_full_queue_after_reader_exited( + self, + ): + # httpx-ws's keepalive thread closes the transport on a ping timeout and + # then puts an error into the event queue. With the queue full and the + # reader already gone, nothing else would ever make room for it, and + # httpx-ws joins that thread without a timeout. + events = queue.Queue(2) + events.put("unread 1") + events.put("unread 2") + reader = threading.Thread(target=lambda: None) + reader.start() + reader.join() + keepalive = threading.Thread( + target=events.put, args=(httpx_ws.WebSocketNetworkError(),), daemon=True + ) + keepalive.start() + ws = _make_ws(Mock(), reader) + ws._events = events + ws._background_keepalive_ping_task = keepalive + + drain_reader(ws) + + keepalive.join(timeout=1) + assert not keepalive.is_alive() + def test_tolerates_missing_socket_and_thread(self): ws = Mock() ws.stream = None From 1ff5382b6af2e0f9830152cdf6181fe83329236a Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:48:32 -0800 Subject: [PATCH 7/9] fix(asr): bound the wait for the cancelled audio sender When an async session ended before its audio stream, the session task cancelled the sender and waited for it without a timeout, inside the open connection. An audio generator whose cleanup never finishes kept the connection open and the consumer waiting for an end that was never queued. Wait at most one second, then close the connection and report the session's result; a late exception from the sender is still retrieved. Tests: the two "audio failure is raised when the server closes normally" tests closed the connection as soon as the first chunk arrived, which does not prove the SDK had recorded the failure yet. The server now waits until the sender has ended, and the failure is delayed so the tests would fail without that wait. Co-Authored-By: Claude Fable 5.2 --- src/fishaudio/resources/asr_realtime.py | 15 ++++-- tests/unit/test_asr_realtime.py | 72 +++++++++++++++++++++++-- 2 files changed, 81 insertions(+), 6 deletions(-) diff --git a/src/fishaudio/resources/asr_realtime.py b/src/fishaudio/resources/asr_realtime.py index 52eaca0..bb46da3 100644 --- a/src/fishaudio/resources/asr_realtime.py +++ b/src/fishaudio/resources/asr_realtime.py @@ -72,6 +72,9 @@ _POLL_SECONDS = 0.25 # Once the sender has failed, only messages that already arrived are read. _DRAIN_SECONDS = 0.05 +# How long the async session waits for the cancelled audio sender, and with it +# the audio stream's own cleanup, before it closes the connection anyway. +_SENDER_CLEANUP_SECONDS = 1.0 _EVENT_TYPES: dict[str, type[ASRRealtimeEvent]] = { "session_started": ASRSessionStartedEvent, @@ -437,6 +440,11 @@ async def _asend_audio( logger.debug("Closing the audio stream failed", exc_info=True) +def _retrieve_exception(task: asyncio.Task[None]) -> None: + if not task.cancelled(): + task.exception() # mark it as retrieved: nobody else will look + + def _failure(task: Optional[asyncio.Task[None]]) -> Optional[BaseException]: """Why the audio sender stopped early, if it did.""" if task is None or not task.done(): @@ -529,9 +537,10 @@ async def _run_session( link.close() if sender is not None: sender.cancel() - await asyncio.wait({sender}) - if not sender.cancelled(): - sender.exception() # mark a late exception as retrieved + # Bounded: an audio stream whose cleanup never finishes must + # not keep the connection open and the consumer waiting. + await asyncio.wait({sender}, timeout=_SENDER_CLEANUP_SECONDS) + sender.add_done_callback(_retrieve_exception) except WebSocketUpgradeError as e: error = _upgrade_error(e.response) error.__cause__ = e diff --git a/tests/unit/test_asr_realtime.py b/tests/unit/test_asr_realtime.py index 5e10736..0444a10 100644 --- a/tests/unit/test_asr_realtime.py +++ b/tests/unit/test_asr_realtime.py @@ -602,15 +602,30 @@ def script(conn): assert time.monotonic() - started < 1.0 server.stop() - def test_audio_failure_is_raised_when_the_server_closes_normally(self): + def test_audio_failure_is_raised_when_the_server_closes_normally(self, monkeypatch): + # The server must close only after the SDK has recorded the failure: + # receiving the chunk does not prove that, so wait for the sender to end. + sender_ended = threading.Event() + send_audio = asr_realtime._send_audio + + def send_audio_then_signal(*args): + try: + send_audio(*args) + finally: + sender_ended.set() + + monkeypatch.setattr(asr_realtime, "_send_audio", send_audio_then_signal) + def audio(): yield CHUNK + time.sleep(0.05) # the failure comes well after the chunk was sent raise RuntimeError("microphone unplugged") def script(conn): conn.recv() conn.send(SESSION_STARTED) conn.recv() # the one audio chunk + assert sender_ended.wait(5) conn.close(1000, "bye") with ( @@ -1072,15 +1087,32 @@ def script(conn): assert time.monotonic() - started < 1.0 await astop(server) - async def test_audio_failure_is_raised_when_the_server_closes_normally(self): + async def test_audio_failure_is_raised_when_the_server_closes_normally( + self, monkeypatch + ): + # As in the sync test: close only once the sender task has failed. The + # task is done in the same event-loop step that sets the flag. + sender_ended = threading.Event() + asend_audio = asr_realtime._asend_audio + + async def asend_audio_then_signal(*args): + try: + await asend_audio(*args) + finally: + sender_ended.set() + + monkeypatch.setattr(asr_realtime, "_asend_audio", asend_audio_then_signal) + async def audio(): yield CHUNK + await asyncio.sleep(0.05) # the failure comes well after the chunk raise RuntimeError("microphone unplugged") def script(conn): conn.recv() conn.send(SESSION_STARTED) - conn.recv() + conn.recv() # the one audio chunk + assert sender_ended.wait(5) conn.close(1000, "bye") async with aserving(script) as (server, client): @@ -1089,6 +1121,40 @@ def script(conn): pass await astop(server) + async def test_audio_stream_cleanup_that_never_finishes_does_not_hang_the_session( + self, monkeypatch + ): + monkeypatch.setattr(asr_realtime, "_SENDER_CLEANUP_SECONDS", 0.05) + release = asyncio.Event() + + async def audio(): + try: + while True: + yield CHUNK + await asyncio.sleep(0.01) + finally: + await release.wait() # cleanup that does not finish + + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + conn.recv() # the first audio chunk + conn.close(1011, "boom") + + async def read_all(stream): + async for _ in stream: + pass + + async with aserving(script) as (server, client): + stream = client.asr.stream_websocket(audio()) + with pytest.raises(ASRRealtimeError) as exc_info: + await asyncio.wait_for(read_all(stream), 2) + assert exc_info.value.close_code == 1011 + await astop(server) # the connection was closed, not left open + + release.set() # let the abandoned cleanup finish + await asyncio.sleep(0.05) + async def test_aclose_from_another_task_wakes_a_waiting_consumer(self): def script(conn): conn.recv() From 200769b5838bd2b709671596ec128c06c847ff3a Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:39:57 -0800 Subject: [PATCH 8/9] fix(asr): interrupt blocked writes on close and refuse concurrent reads Closing a realtime session waited for a socket write that could not finish when the server had stopped reading: - sync: the link lock is held across the write, so close() waited on it, and the close frame waited on httpx-ws's write lock after that. close() now waits half a second, then shuts the socket down so the write fails. - async: the cancelled sender let go, but the close frame was then written into the same full buffer with no cancellation left to stop it. The close frame is now bounded; the transport is closed either way. Two async reads waiting on an empty queue shared one getter and both returned its event. A read started while another is waiting now raises RuntimeError, as a running generator does; the sync stream already refuses a second thread that way. A cancelled read still keeps its event. Co-Authored-By: Claude Fable 5.2 --- src/fishaudio/core/_ws_utils.py | 30 +++++- src/fishaudio/resources/asr_realtime.py | 53 +++++++++- tests/unit/test_asr_realtime.py | 123 ++++++++++++++++++++++++ 3 files changed, 196 insertions(+), 10 deletions(-) diff --git a/src/fishaudio/core/_ws_utils.py b/src/fishaudio/core/_ws_utils.py index cf71210..6900aaa 100644 --- a/src/fishaudio/core/_ws_utils.py +++ b/src/fishaudio/core/_ws_utils.py @@ -14,6 +14,30 @@ logger = logging.getLogger(__name__) +def _socket(ws: Any) -> Any: + stream = getattr(ws, "stream", None) + if stream is None: + response = getattr(ws, "response", None) + stream = response.extensions.get("network_stream") if response else None + return stream.get_extra_info("socket") if stream is not None else None + + +def interrupt_writes(ws: Any) -> None: + """Make a socket write that is blocked in another thread fail now. + + A write blocks for as long as the peer does not read, and httpx-ws holds its + write lock meanwhile, so nothing else can be sent either, not even the close + frame. Shutting the socket down is the only way to end that from outside. + """ + try: + sock = _socket(ws) + if sock is not None: + with contextlib.suppress(OSError): + sock.shutdown(socket.SHUT_RDWR) + except Exception: + logger.debug("interrupt_writes failed", exc_info=True) + + def drain_reader(ws: Any) -> None: """Send the close frame, shut the socket down, and wait for httpx-ws's reader thread to exit before the session's own ``close()`` frees the fd. @@ -45,11 +69,7 @@ def drain_reader(ws: Any) -> None: read can still race. That can only be fixed inside httpx-ws's ``close()``. """ try: - stream = getattr(ws, "stream", None) - if stream is None: - response = getattr(ws, "response", None) - stream = response.extensions.get("network_stream") if response else None - sock = stream.get_extra_info("socket") if stream is not None else None + sock = _socket(ws) # Moves the wsproto state to LOCAL_CLOSING; later close() calls skip the frame. with contextlib.suppress(Exception): diff --git a/src/fishaudio/resources/asr_realtime.py b/src/fishaudio/resources/asr_realtime.py index bb46da3..a36413c 100644 --- a/src/fishaudio/resources/asr_realtime.py +++ b/src/fishaudio/resources/asr_realtime.py @@ -21,7 +21,7 @@ import ormsgpack from httpx_ws import HTTPXWSException, WebSocketDisconnect, WebSocketUpgradeError -from fishaudio.core._ws_utils import drain_reader +from fishaudio.core._ws_utils import drain_reader, interrupt_writes from fishaudio.core.client_wrapper import _api_error from fishaudio.exceptions import ASRRealtimeError, WebSocketError from fishaudio.types.asr_realtime import ( @@ -75,6 +75,9 @@ # How long the async session waits for the cancelled audio sender, and with it # the audio stream's own cleanup, before it closes the connection anyway. _SENDER_CLEANUP_SECONDS = 1.0 +# How long closing waits for a write to the socket. A write does not finish while +# the server is not reading; after this the connection is cut instead. +_CLOSE_WRITE_SECONDS = 0.5 _EVENT_TYPES: dict[str, type[ASRRealtimeEvent]] = { "session_started": ASRSessionStartedEvent, @@ -201,9 +204,19 @@ def open(self, ws: WebSocketSession) -> None: self._ws = ws def close(self) -> None: - with self._lock: - self._ws = None - self.closed = True + """End the link. Does not wait for a write that is blocked.""" + self.closed = True # the sender stops at its next chunk + ws = self._ws + if not self._lock.acquire(timeout=_CLOSE_WRITE_SECONDS): + # A send holds the lock across a socket write that is not finishing. + # Cut the connection so that it fails; nothing else can be sent + # before it does, the close frame included. + interrupt_writes(ws) + if not self._lock.acquire(timeout=_CLOSE_WRITE_SECONDS): + self._ws = None + return + self._ws = None + self._lock.release() def send(self, data: bytes) -> None: with self._lock: @@ -327,6 +340,12 @@ class ASRRealtimeStream: microphone read with no timeout): make your audio source end, or yield regularly, so the thread can exit. + Closing does not wait for a server that has stopped reading: a write that + is still pending after half a second is interrupted by cutting the + connection, without a close frame. + + Read the events from one thread at a time. + The control methods send a message at the current position in the audio stream; they can be called from any thread once ``session_started`` has been received. @@ -541,6 +560,14 @@ async def _run_session( # not keep the connection open and the consumer waiting. await asyncio.wait({sender}, timeout=_SENDER_CLEANUP_SECONDS) sender.add_done_callback(_retrieve_exception) + # The close frame is a write like any other: it does not finish + # while the server is not reading, or while a control message + # sent from another task is stuck in the same way. Bound it here; + # leaving the block then closes the transport without the frame. + try: + await asyncio.wait_for(ws.close(), _CLOSE_WRITE_SECONDS) + except Exception: # includes the timeout + logger.debug("Close frame was not sent", exc_info=True) except WebSocketUpgradeError as e: error = _upgrade_error(e.response) error.__cause__ = e @@ -564,6 +591,10 @@ class AsyncASRRealtimeStream: that reads slowly; beyond that the session stops reading from the server until the consumer catches up. + Read the events from one task at a time: a read started while another is + waiting raises ``RuntimeError``. A read that was cancelled (for example by + ``asyncio.wait_for``) loses nothing; just read again. + The control methods send a message at the current position in the audio stream; they can be awaited once ``session_started`` has been received. @@ -588,6 +619,7 @@ def __init__( # The pending read of the queue. It outlives a cancelled __anext__, so an # event it has already taken is handed to the next read instead of lost. self._getter: Optional[asyncio.Future[Union[ASRRealtimeEvent, _End]]] = None + self._reading = False self._finished = False def __aiter__(self) -> AsyncASRRealtimeStream: @@ -609,7 +641,18 @@ async def __anext__(self) -> ASRRealtimeEvent: self._audio_stream, ) ) - item = await self._next_item() + if self._reading: + # Events have one order and one reader. Two reads waiting together + # would be handed the same event, so refuse the second, as Python + # does for a generator that is already running. + raise RuntimeError( + "Another read of this stream is already waiting for an event" + ) + self._reading = True + try: + item = await self._next_item() + finally: + self._reading = False if item is None: # closed by aclose() while waiting self._finished = True raise StopAsyncIteration diff --git a/tests/unit/test_asr_realtime.py b/tests/unit/test_asr_realtime.py index 0444a10..20941bb 100644 --- a/tests/unit/test_asr_realtime.py +++ b/tests/unit/test_asr_realtime.py @@ -785,6 +785,74 @@ def audio(): assert wait_for_no_sender_threads() assert [m["type"] for m in conn.received] == ["config", "audio"] + def test_close_interrupts_a_blocked_write(self): + """The server stops reading, so the sender blocks in a socket write while + it holds the link. Closing must not wait for that write.""" + release = threading.Event() + sent = [] + + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + release.wait(10) # read nothing: the client's socket buffer fills up + + def audio(): + while True: + sent.append(time.monotonic()) + yield b"\x00" * (1 << 20) + + def sender_is_blocked(): + return bool(sent) and time.monotonic() - sent[-1] > 0.3 + + with serving(script) as (server, client): + stream = client.asr.stream_websocket(audio()) + try: + assert next(stream).type == "session_started" + deadline = time.monotonic() + 5 + while not sender_is_blocked() and time.monotonic() < deadline: + time.sleep(0.05) + assert sender_is_blocked() + + closing = threading.Thread(target=stream.close, daemon=True) + started = time.monotonic() + closing.start() + closing.join(3) + assert not closing.is_alive(), "close() is stuck behind the write" + assert time.monotonic() - started < 2 + assert wait_for_no_sender_threads() + with pytest.raises(WebSocketError): + stream.finalize() + finally: + release.set() + server.stop() + + def test_a_second_thread_cannot_read_while_one_is_reading(self): + """Two threads never get the same event: Python refuses the second read.""" + finish = threading.Event() + + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + finish.wait(10) + conn.send(SESSION_DONE) + conn.close(1000, "done") + + with serving(script) as (server, client): + stream = client.asr.stream_websocket(iter(())) + assert next(stream).type == "session_started" + first = [] + reader = threading.Thread(target=lambda: first.append(next(stream))) + reader.start() + try: + time.sleep(0.1) # the reader is now waiting for an event + with pytest.raises(ValueError, match="already executing"): + next(stream) + finally: + finish.set() + reader.join(5) + assert [event.type for event in first] == ["session_done"] + server.stop() + def test_audio_stream_that_is_not_a_generator_is_not_closed(self): class Source: closed = False @@ -1333,3 +1401,58 @@ async def test_closing_after_a_cancelled_read_leaves_no_pending_task(self): assert pending == [] assert [event async for event in stream] == [] await astop(server) + + async def test_concurrent_reads_do_not_deliver_an_event_twice(self): + async with aserving(open_ended_script) as (server, client): + async with client.asr.stream_websocket(aendless_audio()) as stream: + assert (await stream.__anext__()).type == "session_started" + assert (await stream.__anext__()).type == "committed" + + first = asyncio.ensure_future(stream.__anext__()) + await asyncio.sleep(0) # the first read is now waiting + second = asyncio.ensure_future(stream.__anext__()) + await asyncio.sleep(0) + stream._events.put_nowait(ASRDraftEvent(turn_index=0, text="once")) + done, pending = await asyncio.wait({first, second}, timeout=0.5) + for read in pending: + read.cancel() + + delivered = [r.result() for r in done if r.exception() is None] + assert [event.text for event in delivered] == ["once"] + assert first in done and first.exception() is None + with pytest.raises(RuntimeError, match="already waiting"): + await second + # The refused read took nothing and broke nothing. + stream._events.put_nowait(ASRDraftEvent(turn_index=0, text="next")) + assert (await asyncio.wait_for(stream.__anext__(), 1)).text == "next" + await astop(server) + + async def test_aclose_interrupts_a_blocked_write(self): + release = threading.Event() + sent = [] + + def script(conn): + conn.recv() + conn.send(SESSION_STARTED) + release.wait(10) # read nothing: the client's socket buffer fills up + + async def audio(): + while True: + sent.append(time.monotonic()) + yield b"\x00" * (1 << 20) + + def sender_is_blocked(): + return bool(sent) and time.monotonic() - sent[-1] > 0.3 + + async with aserving(script) as (server, client): + stream = client.asr.stream_websocket(audio()) + try: + assert (await stream.__anext__()).type == "session_started" + deadline = time.monotonic() + 5 + while not sender_is_blocked() and time.monotonic() < deadline: + await asyncio.sleep(0.05) + assert sender_is_blocked() + await asyncio.wait_for(stream.aclose(), 2) + finally: + release.set() + await astop(server) From 41c31df60e5403acd2652e1e1dde85f996aa18f2 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:17:33 -0800 Subject: [PATCH 9/9] fix(websocket): bound the close frame when the peer has stopped reading drain_reader() sent the close frame before shutting the socket down, and httpx-ws writes it without a timeout. With the send buffer full and no write pending (the last audio write just fitted, the source is waiting for its next chunk) nothing interrupted that write, so a sync close() could still block for as long as the server did not read. The frame is now sent from a helper thread with a half-second deadline. When it finishes in time the peer still gets a clean 1000 close; when it does not, the socket is shut down, which makes the blocked write fail. Co-Authored-By: Claude Fable 5.2 --- src/fishaudio/core/_ws_utils.py | 28 +++++++++++++++++++++++++--- tests/unit/test_ws_utils.py | 31 +++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/src/fishaudio/core/_ws_utils.py b/src/fishaudio/core/_ws_utils.py index 6900aaa..12c4114 100644 --- a/src/fishaudio/core/_ws_utils.py +++ b/src/fishaudio/core/_ws_utils.py @@ -6,6 +6,7 @@ import logging import queue import socket +import threading import time from typing import Any @@ -13,6 +14,15 @@ logger = logging.getLogger(__name__) +# How long a close frame may take to be written before the socket is shut down +# without it. +_CLOSE_FRAME_SECONDS = 0.5 + + +def _send_close_frame(ws: Any) -> None: + with contextlib.suppress(Exception): + ws.send(wsproto.events.CloseConnection(1000)) + def _socket(ws: Any) -> Any: stream = getattr(ws, "stream", None) @@ -58,7 +68,8 @@ def drain_reader(ws: Any) -> None: reader with ``EBADF`` on ``close()``, so it is unaffected. The fix is to end the in-flight read *before* the fd is freed: send the close - frame (so the server still sees a clean 1000 close rather than 1006), then + frame (so the server still sees a clean 1000 close rather than 1006; a peer + that has stopped reading does not get one, see below), then ``shutdown(SHUT_RDWR)`` the socket, which wakes the blocked reader with EOF, and join the reader thread. The later ``close()`` sees ``LOCAL_CLOSING`` and skips sending a second frame. @@ -72,12 +83,23 @@ def drain_reader(ws: Any) -> None: sock = _socket(ws) # Moves the wsproto state to LOCAL_CLOSING; later close() calls skip the frame. - with contextlib.suppress(Exception): - ws.send(wsproto.events.CloseConnection(1000)) + # The frame is a socket write, and httpx-ws writes without a timeout: it + # does not finish while the peer is not reading and the send buffer is + # full. So it is sent from a helper thread and given a deadline. The + # shutdown below makes a write that is still blocked fail. + closer = threading.Thread( + target=_send_close_frame, + args=(ws,), + name="fishaudio-ws-close-frame", + daemon=True, + ) + closer.start() + closer.join(timeout=_CLOSE_FRAME_SECONDS) if sock is not None: with contextlib.suppress(OSError): sock.shutdown(socket.SHUT_RDWR) + closer.join(timeout=_CLOSE_FRAME_SECONDS) events = getattr(ws, "_events", None) diff --git a/tests/unit/test_ws_utils.py b/tests/unit/test_ws_utils.py index 8d74a85..1c3621c 100644 --- a/tests/unit/test_ws_utils.py +++ b/tests/unit/test_ws_utils.py @@ -148,6 +148,37 @@ def test_real_httpx_ws_session_over_socketpair(self): server_sock.close() client_sock.close() + def test_does_not_wait_for_a_close_frame_the_peer_is_not_reading(self): + # No write is pending, but the send buffer is full: the last write just + # fitted and the peer has stopped reading. The close frame is a write + # too, and httpx-ws sends it without a timeout. + client_sock, server_sock = socket.socketpair() + try: + # Filled before the session starts: its reader thread sets the + # socket back to blocking every time it begins a read. + client_sock.setblocking(False) + with pytest.raises(BlockingIOError): + while True: + client_sock.send(b"\x00" * 65536) + client_sock.setblocking(True) + ws = httpx_ws.WebSocketSession( + SyncStream(client_sock), keepalive_ping_interval_seconds=None + ) + with ws: + draining = threading.Thread(target=drain_reader, args=(ws,)) + draining.daemon = True + draining.start() + draining.join(3) + stuck = draining.is_alive() + if stuck: # let the write through so the test can end + server_sock.close() + draining.join(3) + assert not stuck, "drain_reader is stuck behind the close frame" + assert not ws._background_receive_task.is_alive() + finally: + server_sock.close() + client_sock.close() + class TestDrainReaderIsCalledFromSyncPaths: @patch("fishaudio.resources.tts.drain_reader")