From 588e6b011373a7fe78258d7e64908e283591137c Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:45:11 -0800 Subject: [PATCH 01/29] fix(tts): raise on a WebSocket error event instead of waiting forever When the API rejects the start event of /v1/tts/live (for example an invalid language tag), it sends {"event": "error", "error": "..."} and then nothing more. stream_websocket ignored that event as unknown and kept waiting for audio or a finish event, so the call never returned. It now raises WebSocketError with the server's message. Co-Authored-By: Claude Opus 5.5 --- src/fishaudio/resources/realtime.py | 8 +++++++- tests/unit/test_realtime.py | 6 ++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/fishaudio/resources/realtime.py b/src/fishaudio/resources/realtime.py index 1049859..2bec49f 100644 --- a/src/fishaudio/resources/realtime.py +++ b/src/fishaudio/resources/realtime.py @@ -33,10 +33,16 @@ def _process_audio_event(data: dict[str, Any]) -> Optional[bytes]: Audio bytes if audio event, None for unknown events Raises: - WebSocketError: If finish event has error reason + WebSocketError: If the server reports an error, either as an error + event or as a finish event with reason "error" """ if data.get("event") == "audio": return data.get("audio") + if data.get("event") == "error": + # The server sends this when it rejects the start event (for example an + # invalid language tag) and then sends nothing more, so waiting for a + # finish event would block forever. + raise WebSocketError(f"WebSocket stream failed: {data.get('error')}") if data.get("event") == "finish" and data.get("reason") == "error": raise WebSocketError("WebSocket stream ended with error") return None # Ignore unknown events diff --git a/tests/unit/test_realtime.py b/tests/unit/test_realtime.py index 446ae3c..54e662c 100644 --- a/tests/unit/test_realtime.py +++ b/tests/unit/test_realtime.py @@ -60,6 +60,12 @@ def test_finish_event_with_error_raises_exception(self): with pytest.raises(WebSocketError, match="WebSocket stream ended with error"): _process_audio_event(data) + def test_error_event_raises_with_server_message(self): + """An error event (sent when the server rejects the start event) raises.""" + data = {"event": "error", "error": 'Invalid language "en us".'} + with pytest.raises(WebSocketError, match='Invalid language "en us"'): + _process_audio_event(data) + def test_finish_event_with_stop_returns_none(self): """Test that finish event with stop reason returns None.""" data = {"event": "finish", "reason": "stop"} From 62343d39d430ddd37435d55b301083cf62f1520d Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:45:11 -0800 Subject: [PATCH 02/29] feat(tts): add language option for text normalization (FISH-1400) TTSConfig.language and a language parameter on convert, stream, convert_with_timestamps, stream_with_timestamps and stream_websocket (sync and async) set the BCP-47 tag the API uses to spell out numbers, dates, units and symbols. The parameter overrides the config value. The tag is sent as given; the API checks it. When language is unset nothing is sent: TTSRequest drops the field from every dump, including the WebSocket start event, which is serialized without exclude_none. Other unset start-event fields keep their current behaviour. Co-Authored-By: Claude Opus 5.5 --- README.md | 12 + src/fishaudio/resources/tts.py | 42 ++++ src/fishaudio/types/tts.py | 27 +- tests/integration/test_tts_integration.py | 19 ++ .../test_tts_websocket_integration.py | 16 ++ tests/unit/test_tts_language.py | 231 ++++++++++++++++++ 6 files changed, 346 insertions(+), 1 deletion(-) create mode 100644 tests/unit/test_tts_language.py diff --git a/README.md b/README.md index f1ca832..1687292 100644 --- a/README.md +++ b/README.md @@ -129,6 +129,18 @@ audio = client.tts.convert( ) ``` +**Language of the text:** + +```python +# "$300" is read as "trescientos pesos" with es-MX, "trescientos dólares" with es +audio = client.tts.convert( + text="La entrada cuesta $300.", + language="es-MX", +) +``` + +`language` is a BCP-47 tag such as `en`, `es-MX` or `zh-CN`. It only changes how numbers, dates, units and symbols are spelled out before synthesis (and word-timestamp alignment); it does not change the voice or accent. Without it, the API detects the language of each chunk, which is also the right choice for text that mixes languages. It is accepted by every text-to-speech method and by `TTSConfig`; on `stream_websocket` it applies to the whole session. See [supported normalization languages](https://docs.fish.audio/features/text-to-speech#supported-normalization-languages). + **Reusable configuration:** ```python diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 73d83f2..600866c 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -58,6 +58,7 @@ def _config_to_tts_request(config: TTSConfig, text: str) -> TTSRequest: references=config.references, reference_id=config.reference_id, normalize=config.normalize, + language=config.language, latency=config.latency, prosody=config.prosody, top_p=config.top_p, @@ -95,6 +96,7 @@ def _build_tts_payload( format: Optional[AudioFormat], latency: Optional[LatencyMode], speed: Optional[float], + language: Optional[str], ) -> bytes: """Build the MessagePack request body; direct parameters override config.""" request = _config_to_tts_request(config, text) @@ -108,6 +110,8 @@ def _build_tts_payload( request.latency = latency if speed is not None: request.prosody = Prosody.from_speed_override(speed, base=config.prosody) + if language is not None: + request.language = language return ormsgpack.packb(request.model_dump(exclude_none=True)) @@ -144,6 +148,7 @@ def stream( format: Optional[AudioFormat] = None, latency: Optional[LatencyMode] = None, speed: Optional[float] = None, + language: Optional[str] = None, config: TTSConfig = TTSConfig(), model: Union[Model, str] = "s2.1-pro", request_options: Optional[RequestOptions] = None, @@ -158,6 +163,7 @@ def stream( format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided) latency: Latency mode - "normal" or "balanced" (overrides config.latency if provided) speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided) + language: BCP-47 tag of the text, e.g. "es-MX", for text normalization (overrides config.language if provided) config: TTS configuration (audio settings, voice, model parameters) model: TTS model to use request_options: Request-level overrides @@ -200,6 +206,9 @@ def stream( if speed is not None: request.prosody = Prosody.from_speed_override(speed, base=config.prosody) + if language is not None: + request.language = language + payload = request.model_dump(exclude_none=True) # Send the request and return once headers arrive; the body is read @@ -233,6 +242,7 @@ def convert( format: Optional[AudioFormat] = None, latency: Optional[LatencyMode] = None, speed: Optional[float] = None, + language: Optional[str] = None, config: TTSConfig = TTSConfig(), model: Union[Model, str] = "s2.1-pro", request_options: Optional[RequestOptions] = None, @@ -250,6 +260,7 @@ def convert( format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided) latency: Latency mode - "normal" or "balanced" (overrides config.latency if provided) speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided) + language: BCP-47 tag of the text, e.g. "es-MX", for text normalization (overrides config.language if provided) config: TTS configuration (audio settings, voice, model parameters) model: TTS model to use request_options: Request-level overrides @@ -281,6 +292,7 @@ def convert( format=format, latency=latency, speed=speed, + language=language, config=config, model=model, request_options=request_options, @@ -295,6 +307,7 @@ def stream_with_timestamps( format: Optional[AudioFormat] = None, latency: Optional[LatencyMode] = None, speed: Optional[float] = None, + language: Optional[str] = None, config: TTSConfig = TTSConfig(), model: Union[Model, str] = "s2.1-pro", request_options: Optional[RequestOptions] = None, @@ -314,6 +327,7 @@ def stream_with_timestamps( are uncompressed, which keeps sample positions exact. latency: Latency mode - "normal" or "balanced" (overrides config.latency if provided) speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided) + language: BCP-47 tag of the text, e.g. "es-MX", for text normalization (overrides config.language if provided) config: TTS configuration (audio settings, voice, model parameters) model: TTS model to use request_options: Request-level overrides @@ -346,6 +360,7 @@ def stream_with_timestamps( format=format, latency=latency, speed=speed, + language=language, ) # Return once headers arrive; events are read lazily as they are produced. @@ -380,6 +395,7 @@ def convert_with_timestamps( format: Optional[AudioFormat] = None, latency: Optional[LatencyMode] = None, speed: Optional[float] = None, + language: Optional[str] = None, config: TTSConfig = TTSConfig(), model: Union[Model, str] = "s2.1-pro", request_options: Optional[RequestOptions] = None, @@ -399,6 +415,7 @@ def convert_with_timestamps( are uncompressed, which keeps sample positions exact. latency: Latency mode - "normal" or "balanced" (overrides config.latency if provided) speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided) + language: BCP-47 tag of the text, e.g. "es-MX", for text normalization (overrides config.language if provided) config: TTS configuration (audio settings, voice, model parameters) model: TTS model to use request_options: Request-level overrides @@ -430,6 +447,7 @@ def convert_with_timestamps( format=format, latency=latency, speed=speed, + language=language, config=config, model=model, request_options=request_options, @@ -444,6 +462,7 @@ def stream_websocket( format: Optional[AudioFormat] = None, latency: Optional[LatencyMode] = None, speed: Optional[float] = None, + language: Optional[str] = None, config: TTSConfig = TTSConfig(), model: Union[Model, str] = "s2.1-pro", max_workers: int = 10, @@ -461,6 +480,7 @@ def stream_websocket( format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided) latency: Latency mode - "normal" or "balanced" (overrides config.latency if provided) speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided) + language: BCP-47 tag of the text, e.g. "es-MX", for text normalization (overrides config.language if provided) config: TTS configuration (audio settings, voice, model parameters) model: TTS model to use max_workers: ThreadPoolExecutor workers for concurrent sender @@ -553,6 +573,9 @@ def text_generator(): speed, base=config.prosody ) + if language is not None: + tts_request.language = language + # Prepare WebSocket connection kwargs ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} @@ -607,6 +630,7 @@ async def stream( format: Optional[AudioFormat] = None, latency: Optional[LatencyMode] = None, speed: Optional[float] = None, + language: Optional[str] = None, config: TTSConfig = TTSConfig(), model: Union[Model, str] = "s2.1-pro", request_options: Optional[RequestOptions] = None, @@ -621,6 +645,7 @@ async def stream( format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided) latency: Latency mode - "normal" or "balanced" (overrides config.latency if provided) speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided) + language: BCP-47 tag of the text, e.g. "es-MX", for text normalization (overrides config.language if provided) config: TTS configuration (audio settings, voice, model parameters) model: TTS model to use request_options: Request-level overrides @@ -664,6 +689,9 @@ async def stream( if speed is not None: request.prosody = Prosody.from_speed_override(speed, base=config.prosody) + if language is not None: + request.language = language + payload = request.model_dump(exclude_none=True) # Send the request and return once headers arrive; the body is read @@ -697,6 +725,7 @@ async def convert( format: Optional[AudioFormat] = None, latency: Optional[LatencyMode] = None, speed: Optional[float] = None, + language: Optional[str] = None, config: TTSConfig = TTSConfig(), model: Union[Model, str] = "s2.1-pro", request_options: Optional[RequestOptions] = None, @@ -714,6 +743,7 @@ async def convert( format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided) latency: Latency mode - "normal" or "balanced" (overrides config.latency if provided) speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided) + language: BCP-47 tag of the text, e.g. "es-MX", for text normalization (overrides config.language if provided) config: TTS configuration (audio settings, voice, model parameters) model: TTS model to use request_options: Request-level overrides @@ -745,6 +775,7 @@ async def convert( format=format, latency=latency, speed=speed, + language=language, config=config, model=model, request_options=request_options, @@ -760,6 +791,7 @@ async def stream_with_timestamps( format: Optional[AudioFormat] = None, latency: Optional[LatencyMode] = None, speed: Optional[float] = None, + language: Optional[str] = None, config: TTSConfig = TTSConfig(), model: Union[Model, str] = "s2.1-pro", request_options: Optional[RequestOptions] = None, @@ -779,6 +811,7 @@ async def stream_with_timestamps( are uncompressed, which keeps sample positions exact. latency: Latency mode - "normal" or "balanced" (overrides config.latency if provided) speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided) + language: BCP-47 tag of the text, e.g. "es-MX", for text normalization (overrides config.language if provided) config: TTS configuration (audio settings, voice, model parameters) model: TTS model to use request_options: Request-level overrides @@ -812,6 +845,7 @@ async def stream_with_timestamps( format=format, latency=latency, speed=speed, + language=language, ) # Return once headers arrive; events are read lazily as they are produced. @@ -846,6 +880,7 @@ async def convert_with_timestamps( format: Optional[AudioFormat] = None, latency: Optional[LatencyMode] = None, speed: Optional[float] = None, + language: Optional[str] = None, config: TTSConfig = TTSConfig(), model: Union[Model, str] = "s2.1-pro", request_options: Optional[RequestOptions] = None, @@ -865,6 +900,7 @@ async def convert_with_timestamps( are uncompressed, which keeps sample positions exact. latency: Latency mode - "normal" or "balanced" (overrides config.latency if provided) speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided) + language: BCP-47 tag of the text, e.g. "es-MX", for text normalization (overrides config.language if provided) config: TTS configuration (audio settings, voice, model parameters) model: TTS model to use request_options: Request-level overrides @@ -896,6 +932,7 @@ async def convert_with_timestamps( format=format, latency=latency, speed=speed, + language=language, config=config, model=model, request_options=request_options, @@ -911,6 +948,7 @@ async def stream_websocket( format: Optional[AudioFormat] = None, latency: Optional[LatencyMode] = None, speed: Optional[float] = None, + language: Optional[str] = None, config: TTSConfig = TTSConfig(), model: Union[Model, str] = "s2.1-pro", ws_options: Optional[WebSocketOptions] = None, @@ -927,6 +965,7 @@ async def stream_websocket( format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided) latency: Latency mode - "normal" or "balanced" (overrides config.latency if provided) speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided) + language: BCP-47 tag of the text, e.g. "es-MX", for text normalization (overrides config.language if provided) config: TTS configuration (audio settings, voice, model parameters) model: TTS model to use ws_options: WebSocket connection options for configuring timeouts, message size limits, etc. @@ -1018,6 +1057,9 @@ async def text_generator(): speed, base=config.prosody ) + if language is not None: + tts_request.language = language + # Prepare WebSocket connection kwargs ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} diff --git a/src/fishaudio/types/tts.py b/src/fishaudio/types/tts.py index b3f1737..c6c370c 100644 --- a/src/fishaudio/types/tts.py +++ b/src/fishaudio/types/tts.py @@ -2,7 +2,14 @@ from typing import Annotated, Literal, Optional -from pydantic import BaseModel, ConfigDict, Field, field_serializer +from pydantic import ( + BaseModel, + ConfigDict, + Field, + SerializerFunctionWrapHandler, + field_serializer, + model_serializer, +) from .shared import AudioFormat, LatencyMode @@ -65,6 +72,11 @@ class TTSConfig(BaseModel): mp3_bitrate: MP3 bitrate in kbps. Options: 64, 128, 192. Default: 128 opus_bitrate: Opus bitrate in kbps. Options: -1000, 24, 32, 48, 64. Default: 32 normalize: Whether to normalize/clean the input text. Default: True + language: BCP-47 tag of the text's language, such as "en", "es-MX" or "zh-CN". + Only changes how text normalization spells out numbers, dates, units + and symbols (and word-timestamp alignment); it does not change the + voice or accent. Sent as given; the API checks it. Default: None + (not sent, the API detects the language of each chunk) chunk_length: Characters per generation chunk. Range: 100-300. Default: 200. Lower values = faster initial response, higher values = better quality latency: Generation mode. Options: "normal" (higher quality), "balanced" (faster). Default: "balanced" @@ -88,6 +100,7 @@ class TTSConfig(BaseModel): mp3_bitrate: Literal[64, 128, 192] = 128 opus_bitrate: Literal[-1000, 24, 32, 48, 64] = 32 normalize: bool = True + language: Optional[str] = None # Generation settings chunk_length: Annotated[int, Field(ge=100, le=300, strict=True)] = 200 @@ -127,6 +140,8 @@ class TTSRequest(BaseModel): references: List of reference audio samples for voice cloning. Default: [] reference_id: Voice model ID for using a specific voice. Default: None normalize: Whether to normalize/clean the input text. Default: True + language: BCP-47 tag of the text's language for text normalization. + Default: None, which leaves the field out of the request latency: Generation mode. Options: "normal", "balanced". Default: "balanced" prosody: Speech speed and volume settings. Default: None top_p: Nucleus sampling for token selection. Range: 0.0-1.0. Default: 0.7 @@ -147,6 +162,7 @@ class TTSRequest(BaseModel): references: list[ReferenceAudio] = [] reference_id: Optional[str] = None normalize: bool = True + language: Optional[str] = None latency: LatencyMode = "balanced" prosody: Optional[Prosody] = None top_p: Annotated[float, Field(ge=0.0, le=1.0)] = 0.7 @@ -162,6 +178,15 @@ def _opus_bitrate_bps(self, value: int) -> int: # The API takes opus_bitrate in bps (24000, 32000, ...); -1000 means auto. return value * 1000 if value > 0 else value + @model_serializer(mode="wrap") + def _omit_unset_language(self, handler: SerializerFunctionWrapHandler) -> dict: + # An unset language must not reach the API as null, including in the + # WebSocket start event, which is serialized without exclude_none. + data = handler(self) + if self.language is None: + data.pop("language", None) + return data + # WebSocket event types for streaming TTS class StartEvent(BaseModel): diff --git a/tests/integration/test_tts_integration.py b/tests/integration/test_tts_integration.py index 5d4e91e..a493cc2 100644 --- a/tests/integration/test_tts_integration.py +++ b/tests/integration/test_tts_integration.py @@ -4,6 +4,7 @@ import pytest +from fishaudio.exceptions import APIError from fishaudio.types import Prosody, TTSConfig from fishaudio.types.shared import AudioFormat, Model @@ -45,6 +46,24 @@ def test_tts_with_prosody(self, client, save_audio): # Write to output directory save_audio(audio, "test_prosody.mp3") + def test_tts_with_language(self, client, save_audio): + """Test TTS with a language tag for text normalization.""" + audio = client.tts.convert(text="La entrada cuesta $300.", language="es-MX") + assert len(audio) > 1000 + save_audio(audio, "test_language_es_mx.mp3") + + config = TTSConfig(language="es") + result = client.tts.convert_with_timestamps( + text="La entrada cuesta $300.", config=config + ) + assert len(result.audio) > 1000 + + def test_tts_with_invalid_language_is_rejected_by_api(self, client): + """The SDK sends the tag as given; the API rejects an invalid one.""" + with pytest.raises(APIError) as exc_info: + client.tts.convert(text="Hello", language="en US") + assert exc_info.value.status == 400 + @pytest.mark.filterwarnings("ignore::DeprecationWarning") def test_tts_with_different_models(self, client, save_audio): """Test TTS with different models.""" diff --git a/tests/integration/test_tts_websocket_integration.py b/tests/integration/test_tts_websocket_integration.py index ee9aa15..d4cf121 100644 --- a/tests/integration/test_tts_websocket_integration.py +++ b/tests/integration/test_tts_websocket_integration.py @@ -5,6 +5,7 @@ import pytest from fishaudio import WebSocketOptions +from fishaudio.exceptions import WebSocketError from fishaudio.types import FlushEvent, Prosody, TextEvent, TTSConfig from fishaudio.types.shared import DEPRECATED_MODELS, Model @@ -35,6 +36,21 @@ def text_stream(): # Save the audio save_audio(audio_chunks, "test_websocket_streaming.mp3") + def test_websocket_streaming_with_language(self, client, save_audio): + """Test WebSocket streaming with a language tag for the session.""" + audio_chunks = list( + client.tts.stream_websocket( + iter(["La entrada cuesta $300."]), language="es-MX" + ) + ) + assert len(b"".join(audio_chunks)) > 1000 + save_audio(audio_chunks, "test_websocket_language_es_mx.mp3") + + def test_websocket_invalid_language_raises(self, client): + """The API answers an invalid tag with an error event; the SDK raises it.""" + with pytest.raises(WebSocketError, match="Invalid language"): + list(client.tts.stream_websocket(iter(["Hello"]), language="en US")) + @pytest.mark.filterwarnings("ignore::DeprecationWarning") @pytest.mark.parametrize( "model", diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py new file mode 100644 index 0000000..c88fb55 --- /dev/null +++ b/tests/unit/test_tts_language.py @@ -0,0 +1,231 @@ +"""Tests for the text-to-speech `language` option on every entry point. + +HTTP requests go through real httpx transports and WebSocket sessions through a +local server (see realtime_server.py), so the assertions read the bytes the SDK +actually sends. An unset language must not appear on the wire at all, not even +as nil. +""" + +import contextlib + +import httpx +import ormsgpack +import pytest + +from fishaudio import AsyncFishAudio, FishAudio, TTSConfig +from fishaudio.core import AsyncClientWrapper, ClientWrapper +from fishaudio.exceptions import WebSocketError +from fishaudio.resources.tts import AsyncTTSClient, TTSClient +from fishaudio.types import StartEvent, TTSRequest + +from .realtime_server import RealtimeServer + +BASE_URL = "https://api.test.fish.audio" + +SSE_BODY = ( + b'event: message\ndata: {"audio_base64": "", "content": "", "alignment": null}\n\n' +) + +# (call kwargs, expected "language" in the body; None means absent) +CASES = [ + pytest.param({}, None, id="unset"), + pytest.param({"config": TTSConfig()}, None, id="default-config"), + pytest.param({"language": "es-MX"}, "es-MX", id="parameter"), + pytest.param({"config": TTSConfig(language="zh-CN")}, "zh-CN", id="config"), + pytest.param( + {"language": "es-MX", "config": TTSConfig(language="en")}, + "es-MX", + id="parameter-overrides-config", + ), + pytest.param({"language": "ES_mx"}, "ES_mx", id="sent-as-given"), + pytest.param({"language": ""}, "", id="empty-string-sent-as-given"), +] + + +def _check(body, expected): + if expected is None: + assert "language" not in body + else: + assert body["language"] == expected + + +def _capture(seen, response_body): + def handler(request): + seen.append(request) + return httpx.Response(200, content=response_body) + + return handler + + +def _sync_tts(seen, response_body=b"audio"): + transport = httpx.MockTransport(_capture(seen, response_body)) + http = httpx.Client(base_url=BASE_URL, transport=transport) + return TTSClient(ClientWrapper(api_key="test", httpx_client=http)) + + +def _async_tts(seen, response_body=b"audio"): + transport = httpx.MockTransport(_capture(seen, response_body)) + http = httpx.AsyncClient(base_url=BASE_URL, transport=transport) + return AsyncTTSClient(AsyncClientWrapper(api_key="test", httpx_client=http)) + + +class TestTypes: + def test_config_defaults_to_unset(self): + assert TTSConfig().language is None + + def test_request_omits_unset_language_in_every_dump(self): + request = TTSRequest(text="hi") + assert "language" not in request.model_dump() + assert "language" not in request.model_dump(exclude_none=True) + assert "language" not in StartEvent(request=request).model_dump()["request"] + + def test_request_keeps_a_set_language(self): + request = TTSRequest(text="hi", language="es-MX") + assert request.model_dump()["language"] == "es-MX" + assert StartEvent(request=request).model_dump()["request"]["language"] == ( + "es-MX" + ) + + def test_other_none_fields_are_unchanged(self): + # Only language is dropped when unset; the start event keeps sending the + # other optional fields as nil, as it did before. + dumped = StartEvent(request=TTSRequest(text="")).model_dump()["request"] + assert dumped["reference_id"] is None + assert dumped["sample_rate"] is None + assert dumped["prosody"] is None + + +class TestHTTP: + @pytest.mark.parametrize("kwargs, expected", CASES) + def test_convert(self, kwargs, expected): + seen = [] + _sync_tts(seen).convert(text="La entrada cuesta $300.", **kwargs) + assert seen[0].url.path == "/v1/tts" + _check(ormsgpack.unpackb(seen[0].content), expected) + + @pytest.mark.parametrize("kwargs, expected", CASES) + def test_stream(self, kwargs, expected): + seen = [] + _sync_tts(seen).stream(text="Hi", **kwargs).collect() + _check(ormsgpack.unpackb(seen[0].content), expected) + + @pytest.mark.parametrize("kwargs, expected", CASES) + def test_convert_with_timestamps(self, kwargs, expected): + seen = [] + _sync_tts(seen, SSE_BODY).convert_with_timestamps(text="Hi", **kwargs) + assert seen[0].url.path == "/v1/tts/stream/with-timestamp" + _check(ormsgpack.unpackb(seen[0].content), expected) + + @pytest.mark.parametrize("kwargs, expected", CASES) + def test_stream_with_timestamps(self, kwargs, expected): + seen = [] + _sync_tts(seen, SSE_BODY).stream_with_timestamps(text="Hi", **kwargs).close() + _check(ormsgpack.unpackb(seen[0].content), expected) + + @pytest.mark.parametrize("kwargs, expected", CASES) + async def test_async_convert(self, kwargs, expected): + seen = [] + await _async_tts(seen).convert(text="Hi", **kwargs) + _check(ormsgpack.unpackb(seen[0].content), expected) + + @pytest.mark.parametrize("kwargs, expected", CASES) + async def test_async_stream(self, kwargs, expected): + seen = [] + stream = await _async_tts(seen).stream(text="Hi", **kwargs) + await stream.collect() + _check(ormsgpack.unpackb(seen[0].content), expected) + + @pytest.mark.parametrize("kwargs, expected", CASES) + async def test_async_convert_with_timestamps(self, kwargs, expected): + seen = [] + await _async_tts(seen, SSE_BODY).convert_with_timestamps(text="Hi", **kwargs) + _check(ormsgpack.unpackb(seen[0].content), expected) + + @pytest.mark.parametrize("kwargs, expected", CASES) + async def test_async_stream_with_timestamps(self, kwargs, expected): + seen = [] + stream = await _async_tts(seen, SSE_BODY).stream_with_timestamps( + text="Hi", **kwargs + ) + await stream.aclose() + _check(ormsgpack.unpackb(seen[0].content), expected) + + +def tts_script(conn): + """Read the start event and the text, then answer with audio and finish.""" + while conn.recv().get("event") != "stop": + pass + conn.send({"event": "audio", "audio": b"audio"}) + conn.send({"event": "finish", "reason": "stop"}) + + +def rejecting_script(conn): + """What the API does with an invalid start event: an error event, then silence.""" + conn.recv() + conn.send({"event": "error", "error": 'Invalid language "en us".'}) + + +@contextlib.contextmanager +def serving(script): + server = RealtimeServer(script) + 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 = RealtimeServer(script) + client = AsyncFishAudio(api_key="test-key", base_url=server.url) + try: + yield server, client + finally: + await client.close() + server.close() + + +async def _aiter(*items): + for item in items: + yield item + + +class TestWebSocket: + @pytest.mark.parametrize("kwargs, expected", CASES) + def test_start_event(self, kwargs, expected): + with serving(tts_script) as (server, client): + audio = b"".join(client.tts.stream_websocket(iter(["Hola"]), **kwargs)) + conn = server.stop() + assert audio == b"audio" + assert conn.path == "/v1/tts/live" + start = conn.received[0] + assert start["event"] == "start" + _check(start["request"], expected) + + @pytest.mark.parametrize("kwargs, expected", CASES) + async def test_async_start_event(self, kwargs, expected): + async with aserving(tts_script) as (server, client): + chunks = [ + chunk + async for chunk in client.tts.stream_websocket(_aiter("Hola"), **kwargs) + ] + conn = server.stop() + assert b"".join(chunks) == b"audio" + _check(conn.received[0]["request"], expected) + + def test_rejected_start_event_raises_instead_of_hanging(self): + with serving(rejecting_script) as (server, client): + with pytest.raises(WebSocketError, match='Invalid language "en us"'): + list(client.tts.stream_websocket(iter(["Hola"]), language="en us")) + server.stop() + + async def test_async_rejected_start_event_raises_instead_of_hanging(self): + async with aserving(rejecting_script) as (server, client): + with pytest.raises(WebSocketError, match='Invalid language "en us"'): + async for _ in client.tts.stream_websocket( + _aiter("Hola"), language="en us" + ): + pass + server.stop() From 0b1fb05fbb89419b1616dc48e55e925d3aa3c8ad Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:04:45 -0800 Subject: [PATCH 03/29] fix(tts): stop the WebSocket sender when the stream ends early When the audio stream ended before the sender finished (the server's error event, a disconnect, or the caller stopping), stream_websocket left the sender running: the async task stayed pending and could write to the closed socket with nobody retrieving its exception, and the sync thread kept reading text_stream and writing to the closed socket. The async client now cancels the sender task and waits for it, bounded like the realtime speech-to-text session. The sync client signals the sender thread, which stops at its next text chunk without sending it; a thread cannot be interrupted while text_stream itself blocks. Co-Authored-By: Claude Opus 5.5 --- src/fishaudio/resources/tts.py | 34 ++++++++++++++++--- tests/unit/test_tts_language.py | 59 +++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+), 5 deletions(-) diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 600866c..2f1f519 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -4,6 +4,7 @@ import base64 import binascii import json +import threading from collections.abc import AsyncIterable, Iterable, Iterator from concurrent.futures import ThreadPoolExecutor from typing import Optional, Union @@ -43,6 +44,7 @@ ) from fishaudio.types.shared import warn_if_deprecated_model +from .asr_realtime import _SENDER_CLEANUP_SECONDS, _retrieve_exception from .realtime import aiter_websocket_audio, iter_websocket_audio @@ -589,6 +591,7 @@ def text_generator(): headers=self._client.get_headers({"model": model}), **ws_kwargs, ) as ws: + stopped = threading.Event() def sender(): ws.send_bytes( @@ -596,9 +599,12 @@ def sender(): ) # Normalize strings to TextEvent for item in text_stream: + if stopped.is_set(): + return event = _normalize_to_event(item) ws.send_bytes(ormsgpack.packb(event.model_dump())) - ws.send_bytes(ormsgpack.packb(CloseEvent().model_dump())) + if not stopped.is_set(): + ws.send_bytes(ormsgpack.packb(CloseEvent().model_dump())) sender_future = executor.submit(sender) @@ -608,6 +614,13 @@ def sender(): sender_future.result() finally: + # If the stream ended early (an error event, a disconnect, or + # the caller stopped reading), stop the sender at its next + # text chunk instead of letting it keep reading text_stream + # and writing to a closed socket. A thread cannot be + # interrupted while text_stream itself blocks. + stopped.set() + sender_future.cancel() # 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) @@ -1083,8 +1096,19 @@ async def sender(): sender_task = asyncio.create_task(sender()) - # Process incoming audio messages - async for audio_chunk in aiter_websocket_audio(ws): - yield audio_chunk + try: + # Process incoming audio messages + async for audio_chunk in aiter_websocket_audio(ws): + yield audio_chunk - await sender_task + await sender_task + finally: + # If the stream ended early (an error event, a disconnect, or the + # caller stopped reading), cancel the sender so it does not keep + # reading text_stream or write to the closed socket. Bounded, like + # the realtime speech-to-text session, so a text_stream whose + # cleanup never finishes cannot hold the connection open. + if not sender_task.done(): + sender_task.cancel() + await asyncio.wait({sender_task}, timeout=_SENDER_CLEANUP_SECONDS) + sender_task.add_done_callback(_retrieve_exception) diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index c88fb55..97eb4eb 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -6,11 +6,15 @@ as nil. """ +import asyncio import contextlib +import threading +import time import httpx import ormsgpack import pytest +from httpx_ws import WebSocketSession from fishaudio import AsyncFishAudio, FishAudio, TTSConfig from fishaudio.core import AsyncClientWrapper, ClientWrapper @@ -229,3 +233,58 @@ async def test_async_rejected_start_event_raises_instead_of_hanging(self): ): pass server.stop() + + def test_rejected_start_event_stops_the_sender(self, monkeypatch): + """After the error the sender must not read on from text_stream or send more.""" + attempted = [] + real_send = WebSocketSession.send_bytes + + def recording_send(self, data): + attempted.append(ormsgpack.unpackb(data)) + return real_send(self, data) + + monkeypatch.setattr(WebSocketSession, "send_bytes", recording_send) + gate = threading.Event() + pulled_second = threading.Event() + resumed = [] + + def text_stream(): + yield "Hola" + gate.wait(5) + pulled_second.set() + yield "late" + resumed.append(True) + yield "later" + + with serving(rejecting_script) as (server, client): + with pytest.raises(WebSocketError): + list(client.tts.stream_websocket(text_stream(), language="en us")) + gate.set() + assert pulled_second.wait(5) + time.sleep(0.2) + conn = server.stop() + assert resumed == [] + assert [m.get("text") for m in attempted if m["event"] == "text"] == ["Hola"] + assert all(m.get("text") not in ("late", "later") for m in conn.received) + + async def test_async_rejected_start_event_cancels_the_sender(self): + """After the error the sender task is cancelled, not left pending.""" + never = asyncio.Event() + cancelled = asyncio.Event() + + async def text_stream(): + try: + yield "Hola" + await never.wait() + yield "late" + finally: + cancelled.set() + + async with aserving(rejecting_script) as (server, client): + with pytest.raises(WebSocketError): + async for _ in client.tts.stream_websocket( + text_stream(), language="en us" + ): + pass + assert cancelled.is_set() + server.stop() From 3c3ba7b2a7d35a09d7bef2ca932510ca0400cff2 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:57:40 -0800 Subject: [PATCH 04/29] test(tts): reject only after the first text in the sender-shutdown tests The sender-shutdown tests need the sender to be past its first text and blocked in text_stream when the error arrives. rejecting_script answers right after the start event, so the error could win that race: the sync sender then stopped before "Hola" and the test timed out waiting for the second item, and the async sender could be cancelled before the generator started. They now use rejecting_after_text_script, which rejects once the first text has arrived. The shutdown code is unchanged. Co-Authored-By: Claude Opus 5.5 --- tests/unit/test_tts_language.py | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index 97eb4eb..25c5b69 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -169,6 +169,18 @@ def rejecting_script(conn): conn.send({"event": "error", "error": 'Invalid language "en us".'}) +def rejecting_after_text_script(conn): + """Like rejecting_script, but rejects only once the first text has arrived. + + The sender-shutdown tests need the sender to be past its first text and + blocked in text_stream when the error comes; rejecting right after the + start event lets the error win that race and the tests time out. + """ + while conn.recv().get("event") != "text": + pass + conn.send({"event": "error", "error": 'Invalid language "en us".'}) + + @contextlib.contextmanager def serving(script): server = RealtimeServer(script) @@ -256,7 +268,7 @@ def text_stream(): resumed.append(True) yield "later" - with serving(rejecting_script) as (server, client): + with serving(rejecting_after_text_script) as (server, client): with pytest.raises(WebSocketError): list(client.tts.stream_websocket(text_stream(), language="en us")) gate.set() @@ -280,7 +292,7 @@ async def text_stream(): finally: cancelled.set() - async with aserving(rejecting_script) as (server, client): + async with aserving(rejecting_after_text_script) as (server, client): with pytest.raises(WebSocketError): async for _ in client.tts.stream_websocket( text_stream(), language="en us" From d15c864e25b53a000734fedcae7d9897360fbf71 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:28:23 -0800 Subject: [PATCH 05/29] fix(tts): keep TTSRequest's serialization schema The model serializer that drops an unset language was annotated '-> dict', which Pydantic publishes as the serialization schema, so TTSRequest.model_json_schema(mode="serialization") listed no fields. Without the annotation the schema is main's plus language. --- src/fishaudio/types/tts.py | 4 +++- tests/unit/test_tts_language.py | 13 +++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/fishaudio/types/tts.py b/src/fishaudio/types/tts.py index c6c370c..dde64f1 100644 --- a/src/fishaudio/types/tts.py +++ b/src/fishaudio/types/tts.py @@ -179,9 +179,11 @@ def _opus_bitrate_bps(self, value: int) -> int: return value * 1000 if value > 0 else value @model_serializer(mode="wrap") - def _omit_unset_language(self, handler: SerializerFunctionWrapHandler) -> dict: + def _omit_unset_language(self, handler: SerializerFunctionWrapHandler): # An unset language must not reach the API as null, including in the # WebSocket start event, which is serialized without exclude_none. + # No return annotation: Pydantic would publish it as the + # serialization schema in place of the model's fields. data = handler(self) if self.language is None: data.pop("language", None) diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index 25c5b69..2dd6f59 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -90,6 +90,19 @@ def test_request_keeps_a_set_language(self): "es-MX" ) + def test_serialization_schema_keeps_every_field(self): + # Dropping an unset language must not change the published schema: + # every field stays described and text stays required. + schema = TTSRequest.model_json_schema(mode="serialization") + assert set(schema["properties"]) == set(TTSRequest.model_fields) + assert schema["required"] == ["text"] + assert schema["properties"]["language"]["anyOf"] == [ + {"type": "string"}, + {"type": "null"}, + ] + nested = StartEvent.model_json_schema(mode="serialization")["$defs"] + assert set(nested["TTSRequest"]["properties"]) == set(TTSRequest.model_fields) + def test_other_none_fields_are_unchanged(self): # Only language is dropped when unset; the start event keeps sending the # other optional fields as nil, as it did before. From 60d8d2a8e247b9ebc3507e81b1d449dba819a799 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:11:45 -0800 Subject: [PATCH 06/29] fix(tts): do not read text_stream again once the stream is over The sync sender checked the stop flag only after reading the next item, so it could start one more read of text_stream after the stream had raised or been closed. It now checks before each read as well. This changes nothing while the stream runs. The comments and docstrings now say when the sender stops: when the stream finishes, raises, or is closed (close(), contextlib.closing, aclose()). A plain break does not close it. Two tests were renamed: their server rejects after the first text, not the start event. New tests cover closing and aclose(). --- src/fishaudio/resources/tts.py | 44 +++++++++----- tests/unit/test_tts_language.py | 103 +++++++++++++++++++++++++------- 2 files changed, 110 insertions(+), 37 deletions(-) diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 2f1f519..80fe935 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -491,7 +491,9 @@ def stream_websocket( See WebSocketOptions class for available parameters. Returns: - Iterator of audio bytes + Iterator of audio bytes. To stop reading early, close it (for + example with `contextlib.closing`): a plain `break` leaves the + connection open and the text sender running until it is closed. Example: ```python @@ -597,14 +599,20 @@ def sender(): ws.send_bytes( ormsgpack.packb(StartEvent(request=tts_request).model_dump()) ) - # Normalize strings to TextEvent - for item in text_stream: + # Check before each read as well as after it: once the + # stream is over, text_stream is not read again. + items = iter(text_stream) + while not stopped.is_set(): + try: + item = next(items) + except StopIteration: + ws.send_bytes(ormsgpack.packb(CloseEvent().model_dump())) + return if stopped.is_set(): return + # Normalize strings to TextEvent event = _normalize_to_event(item) ws.send_bytes(ormsgpack.packb(event.model_dump())) - if not stopped.is_set(): - ws.send_bytes(ormsgpack.packb(CloseEvent().model_dump())) sender_future = executor.submit(sender) @@ -614,11 +622,11 @@ def sender(): sender_future.result() finally: - # If the stream ended early (an error event, a disconnect, or - # the caller stopped reading), stop the sender at its next - # text chunk instead of letting it keep reading text_stream - # and writing to a closed socket. A thread cannot be - # interrupted while text_stream itself blocks. + # Runs when the stream ends: it finished, it raised (an error + # event, a disconnect), or the caller closed it. A plain + # `break` does not close it. The sender then stops before its + # next read or send. A thread cannot be interrupted while + # text_stream itself blocks. stopped.set() sender_future.cancel() # Stop httpx-ws's reader thread before the socket is closed so it @@ -986,7 +994,10 @@ async def stream_websocket( See WebSocketOptions class for available parameters. Returns: - Async iterator of audio bytes + Async iterator of audio bytes. To stop reading early, close it with + `await stream.aclose()` (or `contextlib.aclosing` on Python 3.10+): + a plain `break` leaves the connection open and the text sender + running until it is closed. Example: ```python @@ -1103,11 +1114,12 @@ async def sender(): await sender_task finally: - # If the stream ended early (an error event, a disconnect, or the - # caller stopped reading), cancel the sender so it does not keep - # reading text_stream or write to the closed socket. Bounded, like - # the realtime speech-to-text session, so a text_stream whose - # cleanup never finishes cannot hold the connection open. + # Runs when the stream ends: it finished, it raised (an error + # event, a disconnect), or the caller closed it with aclose(). + # A plain `break` does not close it. The sender is cancelled; + # the wait is bounded, like the realtime speech-to-text session, + # so a text_stream whose cleanup never finishes cannot hold the + # connection open. if not sender_task.done(): sender_task.cancel() await asyncio.wait({sender_task}, timeout=_SENDER_CLEANUP_SECONDS) diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index 2dd6f59..21b6ba1 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -14,7 +14,7 @@ import httpx import ormsgpack import pytest -from httpx_ws import WebSocketSession +from httpx_ws import AsyncWebSocketSession, WebSocketSession from fishaudio import AsyncFishAudio, FishAudio, TTSConfig from fishaudio.core import AsyncClientWrapper, ClientWrapper @@ -259,40 +259,39 @@ async def test_async_rejected_start_event_raises_instead_of_hanging(self): pass server.stop() - def test_rejected_start_event_stops_the_sender(self, monkeypatch): - """After the error the sender must not read on from text_stream or send more.""" + def test_error_after_text_stops_the_sender_before_its_next_read(self, monkeypatch): + """Once the stream has raised, the sender neither reads text_stream again nor sends.""" + release = threading.Event() attempted = [] real_send = WebSocketSession.send_bytes - def recording_send(self, data): - attempted.append(ormsgpack.unpackb(data)) - return real_send(self, data) + def held_send(self, data): + message = ormsgpack.unpackb(data) + attempted.append(message) + result = real_send(self, data) + if message.get("text") == "Hola": + release.wait(5) # hold the sender here until the stream has ended + return result - monkeypatch.setattr(WebSocketSession, "send_bytes", recording_send) - gate = threading.Event() - pulled_second = threading.Event() - resumed = [] + monkeypatch.setattr(WebSocketSession, "send_bytes", held_send) + reads = [] def text_stream(): + reads.append("Hola") yield "Hola" - gate.wait(5) - pulled_second.set() + reads.append("late") yield "late" - resumed.append(True) - yield "later" with serving(rejecting_after_text_script) as (server, client): with pytest.raises(WebSocketError): list(client.tts.stream_websocket(text_stream(), language="en us")) - gate.set() - assert pulled_second.wait(5) - time.sleep(0.2) - conn = server.stop() - assert resumed == [] + release.set() + time.sleep(0.3) + server.stop() + assert reads == ["Hola"] assert [m.get("text") for m in attempted if m["event"] == "text"] == ["Hola"] - assert all(m.get("text") not in ("late", "later") for m in conn.received) - async def test_async_rejected_start_event_cancels_the_sender(self): + async def test_async_error_after_text_cancels_the_sender(self): """After the error the sender task is cancelled, not left pending.""" never = asyncio.Event() cancelled = asyncio.Event() @@ -313,3 +312,65 @@ async def text_stream(): pass assert cancelled.is_set() server.stop() + + +def endless_listener_script(conn): + """Answers the first text with audio, then reads until the client leaves.""" + while conn.recv().get("event") != "text": + pass + conn.send({"event": "audio", "audio": b"audio"}) + + +class TestClosingTheStream: + def test_closing_stops_the_sender(self, monkeypatch): + sent = [] + real_send = WebSocketSession.send_bytes + + def recording_send(self, data): + sent.append(ormsgpack.unpackb(data)) + return real_send(self, data) + + monkeypatch.setattr(WebSocketSession, "send_bytes", recording_send) + + def text_stream(): + for i in range(200): + time.sleep(0.01) + yield f"chunk {i}" + + with serving(endless_listener_script) as (server, client): + with contextlib.closing( + client.tts.stream_websocket(text_stream()) + ) as stream: + for _ in stream: + break + sent_at_close = len(sent) + time.sleep(0.3) + server.stop() + assert len(sent) == sent_at_close + + async def test_aclose_cancels_the_sender(self, monkeypatch): + sent = [] + real_send = AsyncWebSocketSession.send_bytes + + async def recording_send(self, data): + sent.append(ormsgpack.unpackb(data)) + return await real_send(self, data) + + monkeypatch.setattr(AsyncWebSocketSession, "send_bytes", recording_send) + + async def text_stream(): + for i in range(200): + await asyncio.sleep(0.01) + yield f"chunk {i}" + + async with aserving(endless_listener_script) as (server, client): + stream = client.tts.stream_websocket(text_stream()) + try: + async for _ in stream: + break + finally: + await stream.aclose() + sent_at_close = len(sent) + await asyncio.sleep(0.3) + server.stop() + assert len(sent) == sent_at_close From 41e74a4b4269cbf094a75ab9b2c8e1c92377ad05 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:02:24 -0800 Subject: [PATCH 07/29] fix(tts): send no stop once the stream is over 60d8d2a moved the CloseEvent into the read loop and dropped the stop check before it, so a text_stream that ended after the stream had raised or been closed made the sync sender write stop to a closed socket. The check is back, with a test. --- src/fishaudio/resources/tts.py | 6 ++++- tests/unit/test_tts_language.py | 45 +++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 3d48409..92c876a 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -639,7 +639,11 @@ def sender(): try: item = next(items) except StopIteration: - ws.send_bytes(ormsgpack.packb(CloseEvent().model_dump())) + # text_stream can end after the stream has. + if not stopped.is_set(): + ws.send_bytes( + ormsgpack.packb(CloseEvent().model_dump()) + ) return if stopped.is_set(): return diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index 21b6ba1..e1de5d2 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -374,3 +374,48 @@ async def text_stream(): await asyncio.sleep(0.3) server.stop() assert len(sent) == sent_at_close + + +def _record_sends(monkeypatch, session_class, is_async=False): + """Record every message the SDK tries to send, before it is sent.""" + attempted = [] + real_send = session_class.send_bytes + + if is_async: + + async def recording_send(self, data): + attempted.append(ormsgpack.unpackb(data)) + return await real_send(self, data) + + else: + + def recording_send(self, data): + attempted.append(ormsgpack.unpackb(data)) + return real_send(self, data) + + monkeypatch.setattr(session_class, "send_bytes", recording_send) + return attempted + + +class TestTextStreamOutlivesTheStream: + def test_text_stream_ending_after_an_error_sends_no_stop(self, monkeypatch): + """text_stream ends only after the stream raised: no stop on a closed socket.""" + attempted = _record_sends(monkeypatch, WebSocketSession) + gate = threading.Event() + ended = threading.Event() + + def text_stream(): + try: + yield "Hola" + gate.wait(5) # still waiting for input when the error comes + finally: + ended.set() + + with serving(rejecting_after_text_script) as (server, client): + with pytest.raises(WebSocketError): + list(client.tts.stream_websocket(text_stream(), language="en us")) + gate.set() + assert ended.wait(5) + time.sleep(0.2) # let the sender return after text_stream ended + server.stop() + assert [m["event"] for m in attempted] == ["start", "text"] From 97e913e733754b0f55306fdee5ac31c01aff66c0 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:02:26 -0800 Subject: [PATCH 08/29] fix(tts): end the WebSocket stream when the server finishes first When the server sent finish while text_stream was still waiting for input, the sync and async iterators waited for the sender, so they did not end, and text given later was still sent. They now end at finish: the sync sender is told to stop and the async one is cancelled; a sender that has already ended still reports its error. Four mock tests ended the fake server before the start event was sent, which a real server cannot do; their fake now answers once the start event is out. --- src/fishaudio/resources/tts.py | 16 +++++++-- tests/unit/test_tts_language.py | 63 +++++++++++++++++++++++++++++++++ tests/unit/test_tts_realtime.py | 13 +++++++ 3 files changed, 89 insertions(+), 3 deletions(-) diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 92c876a..974ffb7 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -657,13 +657,19 @@ def sender(): # Process incoming audio messages yield from iter_websocket_audio(ws) - sender_future.result() + # The server can finish while text_stream is still waiting + # for input. Do not wait for it then; a sender that has + # already ended reports its error here. + stopped.set() + if sender_future.done(): + sender_future.result() finally: # Runs when the stream ends: it finished, it raised (an error # event, a disconnect), or the caller closed it. A plain # `break` does not close it. The sender then stops before its # next read or send. A thread cannot be interrupted while - # text_stream itself blocks. + # text_stream itself blocks: it returns once text_stream + # yields or ends, without sending anything more. stopped.set() sender_future.cancel() # Stop httpx-ws's reader thread before the socket is closed so it @@ -1162,7 +1168,11 @@ async def sender(): async for audio_chunk in aiter_websocket_audio(ws): yield audio_chunk - await sender_task + # The server can finish while text_stream is still waiting for + # input. Do not wait for it then (it is cancelled below); a + # sender that has already ended reports its error here. + if sender_task.done(): + await sender_task finally: # Runs when the stream ends: it finished, it raised (an error # event, a disconnect), or the caller closed it with aclose(). diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index e1de5d2..ede4945 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -397,6 +397,14 @@ def recording_send(self, data): return attempted +def early_finish_script(conn): + """Finishes after the first text, without waiting for the client's stop.""" + while conn.recv().get("event") != "text": + pass + conn.send({"event": "audio", "audio": b"audio"}) + conn.send({"event": "finish", "reason": "stop"}) + + class TestTextStreamOutlivesTheStream: def test_text_stream_ending_after_an_error_sends_no_stop(self, monkeypatch): """text_stream ends only after the stream raised: no stop on a closed socket.""" @@ -419,3 +427,58 @@ def text_stream(): time.sleep(0.2) # let the sender return after text_stream ended server.stop() assert [m["event"] for m in attempted] == ["start", "text"] + + def test_finish_while_text_stream_waits_ends_the_stream(self, monkeypatch): + attempted = _record_sends(monkeypatch, WebSocketSession) + gate = threading.Event() + late_read = threading.Event() + + def text_stream(): + yield "first" + gate.wait(5) + late_read.set() + yield "late" + + result = {} + + def consume(client): + result["audio"] = b"".join(client.tts.stream_websocket(text_stream())) + + with serving(early_finish_script) as (server, client): + consumer = threading.Thread(target=consume, args=(client,), daemon=True) + consumer.start() + consumer.join(2) + ended_before_text_stream = not consumer.is_alive() + gate.set() + consumer.join(5) + assert late_read.wait(5) + time.sleep(0.2) # the sender's chance to send "late" + server.stop() + assert ended_before_text_stream + assert result["audio"] == b"audio" + assert [m.get("text") for m in attempted if m["event"] == "text"] == ["first"] + + async def test_async_finish_while_text_stream_waits_ends_the_stream( + self, monkeypatch + ): + attempted = _record_sends(monkeypatch, AsyncWebSocketSession, is_async=True) + never = asyncio.Event() + closed = asyncio.Event() + + async def text_stream(): + try: + yield "first" + await never.wait() + yield "late" + finally: + closed.set() + + async def consume(client): + return [chunk async for chunk in client.tts.stream_websocket(text_stream())] + + async with aserving(early_finish_script) as (server, client): + chunks = await asyncio.wait_for(consume(client), 2) + await asyncio.wait_for(closed.wait(), 2) + server.stop() + assert b"".join(chunks) == b"audio" + assert [m.get("text") for m in attempted if m["event"] == "text"] == ["first"] diff --git a/tests/unit/test_tts_realtime.py b/tests/unit/test_tts_realtime.py index 99e2f13..a22fbd7 100644 --- a/tests/unit/test_tts_realtime.py +++ b/tests/unit/test_tts_realtime.py @@ -1,5 +1,6 @@ """Tests for TTS realtime streaming.""" +import asyncio from unittest.mock import AsyncMock, MagicMock, Mock, patch import ormsgpack @@ -551,6 +552,9 @@ async def test_stream_websocket_with_reference_id_parameter( mock_aconnect_ws.return_value = mock_ws async def mock_audio_receiver(ws): + # A server answers only once it has the start event. + while not mock_ws.send_bytes.called: + await asyncio.sleep(0) yield b"audio" with patch( @@ -588,6 +592,9 @@ async def test_stream_websocket_parameter_reference_id_overrides_config( mock_aconnect_ws.return_value = mock_ws async def mock_audio_receiver(ws): + # A server answers only once it has the start event. + while not mock_ws.send_bytes.called: + await asyncio.sleep(0) yield b"audio" with patch( @@ -624,6 +631,9 @@ async def test_stream_websocket_with_references_parameter( mock_aconnect_ws.return_value = mock_ws async def mock_audio_receiver(ws): + # A server answers only once it has the start event. + while not mock_ws.send_bytes.called: + await asyncio.sleep(0) yield b"audio" with patch( @@ -665,6 +675,9 @@ async def test_stream_websocket_parameter_references_overrides_config( mock_aconnect_ws.return_value = mock_ws async def mock_audio_receiver(ws): + # A server answers only once it has the start event. + while not mock_ws.send_bytes.called: + await asyncio.sleep(0) yield b"audio" with patch( From 3e999bee782ec943abefc7381c7dd1e33833e2c2 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:10:34 -0800 Subject: [PATCH 09/29] fix(tts): send nothing more once the async stream has ended Cancelling the async sender is not enough: a text_stream that catches the cancellation and yields again had its text and a stop sent after the server's finish. The async sender now checks a stop flag after each read and before stop, as the sync sender does. --- src/fishaudio/resources/tts.py | 11 +++++++++-- tests/unit/test_tts_language.py | 27 +++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 974ffb7..97678a6 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -1150,16 +1150,22 @@ async def text_generator(): headers=self._client.get_headers({"model": model}), **ws_kwargs, ) as ws: + # Set when the stream ends. Cancelling the sender is not enough on + # its own: a text_stream may catch the cancellation and yield again. + stopped = asyncio.Event() async def sender(): await ws.send_bytes( ormsgpack.packb(StartEvent(request=tts_request).model_dump()) ) - # Normalize strings to TextEvent async for item in text_stream: + if stopped.is_set(): + return + # Normalize strings to TextEvent event = _normalize_to_event(item) await ws.send_bytes(ormsgpack.packb(event.model_dump())) - await ws.send_bytes(ormsgpack.packb(CloseEvent().model_dump())) + if not stopped.is_set(): + await ws.send_bytes(ormsgpack.packb(CloseEvent().model_dump())) sender_task = asyncio.create_task(sender()) @@ -1180,6 +1186,7 @@ async def sender(): # the wait is bounded, like the realtime speech-to-text session, # so a text_stream whose cleanup never finishes cannot hold the # connection open. + stopped.set() if not sender_task.done(): sender_task.cancel() await asyncio.wait({sender_task}, timeout=_SENDER_CLEANUP_SECONDS) diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index ede4945..0a5515d 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -482,3 +482,30 @@ async def consume(client): server.stop() assert b"".join(chunks) == b"audio" assert [m.get("text") for m in attempted if m["event"] == "text"] == ["first"] + + async def test_async_text_stream_that_ignores_cancellation_sends_nothing_more( + self, monkeypatch + ): + """A text_stream may catch the cancellation and yield again: not sent.""" + attempted = _record_sends(monkeypatch, AsyncWebSocketSession, is_async=True) + never = asyncio.Event() + late_yielded = asyncio.Event() + + async def text_stream(): + yield "first" + try: + await never.wait() + except asyncio.CancelledError: + late_yielded.set() + yield "late" + + async def consume(client): + return [chunk async for chunk in client.tts.stream_websocket(text_stream())] + + async with aserving(early_finish_script) as (server, client): + chunks = await asyncio.wait_for(consume(client), 2) + await asyncio.wait_for(late_yielded.wait(), 2) + await asyncio.sleep(0.2) # the sender's chance to send "late" + server.stop() + assert b"".join(chunks) == b"audio" + assert [m["event"] for m in attempted] == ["start", "text"] From 57268de362e5a76461513f4599389f0975f4c811 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:33:43 -0800 Subject: [PATCH 10/29] docs(tts): say what happens to text_stream when the stream ends first The SDK stops reading text_stream but does not close it; an async generator can stay suspended. The caller owns it and closes it if it holds resources. --- src/fishaudio/resources/tts.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 97678a6..3b3ad97 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -509,7 +509,11 @@ def stream_websocket( Perfect for conversational AI, live captioning, and streaming applications. Args: - text_stream: Iterator of text chunks to stream + text_stream: Iterator of text chunks to stream. If the stream + ends first (the server finishes, an error, or you close it), + the SDK stops reading it: a read already waiting completes in + the worker thread and its text is not sent. The SDK does not + close text_stream; close it yourself if it holds resources. reference_id: Voice reference ID (overrides config.reference_id if provided) references: Reference audio samples (overrides config.references if provided) format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided) @@ -1036,7 +1040,12 @@ async def stream_websocket( Perfect for conversational AI, live captioning, and streaming applications. Args: - text_stream: Async iterator of text chunks to stream + text_stream: Async iterator of text chunks to stream. If the + stream ends first (the server finishes, an error, or you close + it), the SDK stops reading it and cancels the task sending it; + nothing more is sent. The SDK does not close text_stream: an + async generator can stay suspended, so close it yourself + (`aclose()` or `contextlib.aclosing`) if it holds resources. reference_id: Voice reference ID (overrides config.reference_id if provided) references: Reference audio samples (overrides config.references if provided) format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided) From c1644cc74245d53679f85760158253e13a08695a Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 1 Dec 2026 04:37:02 -0800 Subject: [PATCH 11/29] fix(tts): raise a text_stream error at once and close text_stream on exit When text_stream raised mid-stream, the sender died and the receive loop kept waiting for audio that would not come (async and sync). Now the caller gets the original exception at once: - async: the receive runs in one long-lived task that hands chunks over a queue; a failed text_stream cancels that task, and the stream raises the error. No task per chunk, and a cancellation of the caller's own task is never caught. - sync: the sender records the error and the receive loop, which now waits at most _POLL_SECONDS per receive, raises it. On every exit path the SDK now closes a generator text_stream (aclose for async generators, close for generators), inside the bounded _SENDER_CLEANUP_SECONDS wait for async; sync never waits for the sender thread. Other iterables are left alone. A text_stream that is not iterable, or an item that is not text, ends the stream with that error. --- src/fishaudio/resources/realtime.py | 25 +- src/fishaudio/resources/tts.py | 340 +++++++++++++++++++++------- tests/unit/test_tts_language.py | 313 +++++++++++++++++++++++++ 3 files changed, 593 insertions(+), 85 deletions(-) diff --git a/src/fishaudio/resources/realtime.py b/src/fishaudio/resources/realtime.py index 2bec49f..8b1d797 100644 --- a/src/fishaudio/resources/realtime.py +++ b/src/fishaudio/resources/realtime.py @@ -1,7 +1,8 @@ """Real-time WebSocket streaming helpers.""" +import queue from collections.abc import AsyncIterator, Iterator -from typing import Any, Optional +from typing import Any, Callable, Optional import ormsgpack from httpx_ws import WebSocketDisconnect @@ -48,7 +49,11 @@ def _process_audio_event(data: dict[str, Any]) -> Optional[bytes]: return None # Ignore unknown events -def iter_websocket_audio(ws) -> Iterator[bytes]: +def iter_websocket_audio( + ws, + failure: Optional[Callable[[], Optional[BaseException]]] = None, + poll_seconds: float = 0.25, +) -> Iterator[bytes]: """ Process WebSocket audio messages (sync). @@ -57,6 +62,11 @@ def iter_websocket_audio(ws) -> Iterator[bytes]: Args: ws: WebSocket connection from httpx_ws.connect_ws + failure: Returns why the text sender failed, or None. When given, a + receive waits at most ``poll_seconds`` before checking it again, + and a failure is raised as it is, instead of waiting for audio + that will not come. + poll_seconds: How often a waiting receive checks ``failure``. Yields: Audio bytes @@ -65,8 +75,17 @@ def iter_websocket_audio(ws) -> Iterator[bytes]: WebSocketError: On disconnect or error finish event """ while True: + error = failure() if failure is not None else None + if error is not None: + raise error try: - message = ws.receive_bytes() + if failure is None: + message = ws.receive_bytes() + else: + try: + message = ws.receive_bytes(timeout=poll_seconds) + except (queue.Empty, TimeoutError): # httpx-ws < 0.8 / >= 0.8 + continue data = ormsgpack.unpackb(message) if _should_stop(data): diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 3b3ad97..3db6791 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -6,9 +6,10 @@ import functools import inspect import json +import logging import threading from collections.abc import AsyncIterable, Iterable, Iterator -from concurrent.futures import ThreadPoolExecutor +from concurrent.futures import Future, ThreadPoolExecutor from typing import Any, Callable, Optional, TypeVar, Union, cast import ormsgpack @@ -28,7 +29,7 @@ AudioStream, TTSTimestampStream, ) -from fishaudio.exceptions import FishAudioError +from fishaudio.exceptions import FishAudioError, WebSocketError from fishaudio.types import ( AudioFormat, CloseEvent, @@ -46,7 +47,7 @@ ) from fishaudio.types.shared import warn_if_deprecated_model -from .asr_realtime import _SENDER_CLEANUP_SECONDS, _retrieve_exception +from .asr_realtime import _POLL_SECONDS, _SENDER_CLEANUP_SECONDS, _retrieve_exception from .realtime import aiter_websocket_audio, iter_websocket_audio _F = TypeVar("_F", bound=Callable[..., Any]) @@ -95,6 +96,37 @@ def _config_to_tts_request(config: TTSConfig, text: str) -> TTSRequest: ) +logger = logging.getLogger(__name__) + +# The end of the audio, handed from the WebSocket receiver to the caller. +_END = object() + + +class _Raise: + """An error from the WebSocket receiver, to be raised to the caller.""" + + def __init__(self, error: BaseException) -> None: + self.error = error + + +def _close_text_stream(text_stream: object) -> None: + """Close a generator text_stream. Other iterables are left alone.""" + if inspect.isgenerator(text_stream): + try: + text_stream.close() + except Exception: + logger.debug("Closing text_stream failed", exc_info=True) + + +async def _aclose_text_stream(text_stream: object) -> None: + """Close an async-generator text_stream. Other iterables are left alone.""" + if inspect.isasyncgen(text_stream): + try: + await text_stream.aclose() + except Exception: + logger.debug("Closing text_stream failed", exc_info=True) + + def _normalize_to_event( item: Union[str, TextEvent, FlushEvent], ) -> Union[TextEvent, FlushEvent]: @@ -509,11 +541,15 @@ def stream_websocket( Perfect for conversational AI, live captioning, and streaming applications. Args: - text_stream: Iterator of text chunks to stream. If the stream + text_stream: Iterator of text chunks to stream. If it raises, + the stream ends and raises that same exception. If the stream ends first (the server finishes, an error, or you close it), the SDK stops reading it: a read already waiting completes in - the worker thread and its text is not sent. The SDK does not - close text_stream; close it yourself if it holds resources. + the worker thread and its text is not sent. When the stream + ends, however it ends, the SDK closes a generator text_stream + (`close()`) from the worker thread, so its `finally` blocks + run; the stream does not wait for that. Other iterables are + not closed. reference_id: Voice reference ID (overrides config.reference_id if provided) references: Reference audio samples (overrides config.references if provided) format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided) @@ -621,6 +657,7 @@ def text_generator(): ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} executor = ThreadPoolExecutor(max_workers=max_workers) + sender_future: Optional[Future[None]] = None try: ws: WebSocketSession @@ -631,55 +668,87 @@ def text_generator(): **ws_kwargs, ) as ws: stopped = threading.Event() + # Why text_stream failed, set by the sender; the receive loop + # raises it instead of waiting for audio that will not come. + failure: list[BaseException] = [] def sender(): - ws.send_bytes( - ormsgpack.packb(StartEvent(request=tts_request).model_dump()) - ) - # Check before each read as well as after it: once the - # stream is over, text_stream is not read again. - items = iter(text_stream) - while not stopped.is_set(): + try: + ws.send_bytes( + ormsgpack.packb( + StartEvent(request=tts_request).model_dump() + ) + ) + # Check before each read as well as after it: once the + # stream is over, text_stream is not read again. try: - item = next(items) - except StopIteration: - # text_stream can end after the stream has. - if not stopped.is_set(): - ws.send_bytes( - ormsgpack.packb(CloseEvent().model_dump()) - ) - return - if stopped.is_set(): + items = iter(text_stream) + except Exception as e: + failure.append(e) return - # Normalize strings to TextEvent - event = _normalize_to_event(item) - ws.send_bytes(ormsgpack.packb(event.model_dump())) + while not stopped.is_set(): + try: + item = next(items) + except StopIteration: + # text_stream can end after the stream has. + if not stopped.is_set(): + ws.send_bytes( + ormsgpack.packb(CloseEvent().model_dump()) + ) + return + except Exception as e: + if not stopped.is_set(): + failure.append(e) + return + if stopped.is_set(): + return + # Normalize strings to TextEvent + try: + event = _normalize_to_event(item) + except Exception as e: + failure.append(e) + return + ws.send_bytes(ormsgpack.packb(event.model_dump())) + finally: + # By this thread: a generator cannot be closed from + # another thread while it is running. + _close_text_stream(text_stream) sender_future = executor.submit(sender) try: # Process incoming audio messages - yield from iter_websocket_audio(ws) + yield from iter_websocket_audio( + ws, + failure=lambda: failure[0] if failure else None, + poll_seconds=_POLL_SECONDS, + ) # The server can finish while text_stream is still waiting # for input. Do not wait for it then; a sender that has # already ended reports its error here. stopped.set() + if failure: + raise failure[0] if sender_future.done(): sender_future.result() finally: # Runs when the stream ends: it finished, it raised (an error - # event, a disconnect), or the caller closed it. A plain - # `break` does not close it. The sender then stops before its - # next read or send. A thread cannot be interrupted while + # event, a disconnect, a failed text_stream), or the caller + # closed it. A plain `break` does not close it. The sender + # then stops before its next read or send, and closes + # text_stream. A thread cannot be interrupted while # text_stream itself blocks: it returns once text_stream - # yields or ends, without sending anything more. + # yields or ends, without sending anything more. The stream + # does not wait for that. stopped.set() - sender_future.cancel() # 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) finally: + # A sender that never ran cannot close text_stream itself. + if sender_future is None or sender_future.cancel(): + _close_text_stream(text_stream) executor.shutdown(wait=False) @@ -1040,12 +1109,14 @@ async def stream_websocket( Perfect for conversational AI, live captioning, and streaming applications. Args: - text_stream: Async iterator of text chunks to stream. If the + text_stream: Async iterator of text chunks to stream. If it + raises, the stream ends and raises that same exception. If the stream ends first (the server finishes, an error, or you close it), the SDK stops reading it and cancels the task sending it; - nothing more is sent. The SDK does not close text_stream: an - async generator can stay suspended, so close it yourself - (`aclose()` or `contextlib.aclosing`) if it holds resources. + nothing more is sent. When the stream ends, however it ends, + the SDK closes an async-generator text_stream (`aclose()`), so + its `finally` blocks run; it waits for that at most one second. + Other async iterables are not closed. reference_id: Voice reference ID (overrides config.reference_id if provided) references: Reference audio samples (overrides config.references if provided) format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided) @@ -1152,51 +1223,156 @@ async def text_generator(): # Prepare WebSocket connection kwargs ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} - ws: AsyncWebSocketSession - async with aconnect_ws( - "/v1/tts/live", - client=self._client.client, - headers=self._client.get_headers({"model": model}), - **ws_kwargs, - ) as ws: - # Set when the stream ends. Cancelling the sender is not enough on - # its own: a text_stream may catch the cancellation and yield again. - stopped = asyncio.Event() - - async def sender(): - await ws.send_bytes( - ormsgpack.packb(StartEvent(request=tts_request).model_dump()) - ) - async for item in text_stream: - if stopped.is_set(): - return - # Normalize strings to TextEvent - event = _normalize_to_event(item) - await ws.send_bytes(ormsgpack.packb(event.model_dump())) - if not stopped.is_set(): - await ws.send_bytes(ormsgpack.packb(CloseEvent().model_dump())) - - sender_task = asyncio.create_task(sender()) + sender_started = False + try: + ws: AsyncWebSocketSession + async with aconnect_ws( + "/v1/tts/live", + client=self._client.client, + headers=self._client.get_headers({"model": model}), + **ws_kwargs, + ) as ws: + # Set when the stream ends. Cancelling the sender is not enough + # on its own: a text_stream may catch the cancellation and + # yield again. + stopped = asyncio.Event() + # Why text_stream failed; raised to the caller in place of + # audio that will not come. + failure: list[BaseException] = [] + # Audio chunks, then _END (or the server's error), handed from + # the receiver task to this generator one at a time. + chunks: asyncio.Queue[Any] = asyncio.Queue() + + async def receiver() -> None: + try: + async for audio_chunk in aiter_websocket_audio(ws): + chunks.put_nowait(audio_chunk) + await chunks.join() # until it has been taken + chunks.put_nowait(_END) + except asyncio.CancelledError: + # This task is ours alone: it is cancelled when + # text_stream failed or the stream is being cleaned up. + # Any other cancellation must not end the audio early + # as if it were complete. + if failure or stopped.is_set(): + chunks.put_nowait(_END) + else: + chunks.put_nowait( + _Raise( + WebSocketError( + "Receiving audio was cancelled before " + "the stream ended" + ) + ) + ) + except BaseException as e: + chunks.put_nowait(_Raise(e)) + + receiver_task = asyncio.create_task(receiver()) + + def text_stream_failed(error: BaseException) -> None: + if not stopped.is_set() and not failure: + failure.append(error) + receiver_task.cancel() + + async def sender() -> None: + nonlocal sender_started + sender_started = True + try: + await ws.send_bytes( + ormsgpack.packb( + StartEvent(request=tts_request).model_dump() + ) + ) + try: + items = text_stream.__aiter__() + except AttributeError: + text_stream_failed( + TypeError( + "text_stream must be an async iterable, got " + f"{type(text_stream).__name__}" + ) + ) + return + while True: + try: + item = await items.__anext__() + if stopped.is_set(): + return + # Normalize strings to TextEvent + event = _normalize_to_event(item) + except StopAsyncIteration: + break + except Exception as e: + text_stream_failed(e) + return + await ws.send_bytes(ormsgpack.packb(event.model_dump())) + if not stopped.is_set(): + await ws.send_bytes( + ormsgpack.packb(CloseEvent().model_dump()) + ) + finally: + # Inside the bounded wait below when the stream ends + # first, so a cleanup that does not finish cannot hold + # the connection open. + await _aclose_text_stream(text_stream) + + def sender_done(task: asyncio.Task[None]) -> None: + # Only the cleanup below cancels the sender, after setting + # stopped: a cancellation before that came from text_stream. + if task.cancelled(): + text_stream_failed( + WebSocketError( + "text_stream was cancelled before the stream ended" + ) + ) + + sender_task = asyncio.create_task(sender()) + sender_task.add_done_callback(sender_done) - try: - # Process incoming audio messages - async for audio_chunk in aiter_websocket_audio(ws): - yield audio_chunk - - # The server can finish while text_stream is still waiting for - # input. Do not wait for it then (it is cancelled below); a - # sender that has already ended reports its error here. - if sender_task.done(): - await sender_task - finally: - # Runs when the stream ends: it finished, it raised (an error - # event, a disconnect), or the caller closed it with aclose(). - # A plain `break` does not close it. The sender is cancelled; - # the wait is bounded, like the realtime speech-to-text session, - # so a text_stream whose cleanup never finishes cannot hold the - # connection open. - stopped.set() - if not sender_task.done(): - sender_task.cancel() - await asyncio.wait({sender_task}, timeout=_SENDER_CLEANUP_SECONDS) - sender_task.add_done_callback(_retrieve_exception) + try: + while True: + item = await chunks.get() + chunks.task_done() + if item is _END: + break + if isinstance(item, _Raise): + raise item.error + yield item + + if failure: + raise failure[0] + # The server can finish while text_stream is still waiting + # for input. Do not wait for it then (it is cancelled + # below); a sender that has already ended reports its + # error here. + if sender_task.done(): + await sender_task + finally: + # Runs when the stream ends: it finished, it raised (an + # error event, a disconnect, a failed text_stream), or the + # caller closed it with aclose(). A plain `break` does not + # close it. The sender is cancelled and closes text_stream; + # the wait is bounded, like the realtime speech-to-text + # session, so a text_stream whose cleanup never finishes + # cannot hold the connection open. asyncio.wait does not + # raise the tasks' errors, and a cancellation of the + # caller's own task still reaches the caller. + stopped.set() + pending = { + task for task in (sender_task, receiver_task) if not task.done() + } + for task in pending: + task.cancel() + for task in (sender_task, receiver_task): + task.add_done_callback(_retrieve_exception) + if pending: + await asyncio.wait(pending, timeout=_SENDER_CLEANUP_SECONDS) + finally: + # A sender that never ran cannot close text_stream itself. Bounded + # too: a text_stream the caller had already started has cleanup + # that runs here. + if not sender_started: + closer = asyncio.ensure_future(_aclose_text_stream(text_stream)) + closer.add_done_callback(_retrieve_exception) + await asyncio.wait({closer}, timeout=_SENDER_CLEANUP_SECONDS) diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index 0a5515d..c96630e 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -509,3 +509,316 @@ async def consume(client): server.stop() assert b"".join(chunks) == b"audio" assert [m["event"] for m in attempted] == ["start", "text"] + + +def waiting_script(conn): + """Answers every text with audio and waits for the client's stop.""" + conn.recv() # start + while conn.recv().get("event") != "stop": + conn.send({"event": "audio", "audio": b"audio"}) + conn.send({"event": "finish", "reason": "stop"}) + + +def audio_then_wait_script(conn): + """Sends audio right after the start event, then waits until the client leaves.""" + conn.recv() # start + conn.send({"event": "audio", "audio": b"audio"}) + conn.wait_gone() + + +def audio_then_finish_script(conn): + """Sends audio and finishes right after the start event.""" + conn.recv() # start + conn.send({"event": "audio", "audio": b"audio"}) + conn.send({"event": "finish", "reason": "stop"}) + + +def _consume_in_thread(client, text_stream, mode="all"): + """Read the stream in a thread; return (thread, result dict).""" + result = {} + + def run(): + try: + it = client.tts.stream_websocket(text_stream) + if mode == "close_after_first": + result["audio"] = next(it) + it.close() + else: + result["audio"] = b"".join(it) + except BaseException as e: # noqa: BLE001 - reported to the test + result["error"] = e + + thread = threading.Thread(target=run, daemon=True) + thread.start() + return thread, result + + +def _block_text_sends(monkeypatch): + """Make the async SDK's sends of text events block, as on a server that stopped reading.""" + real_send = AsyncWebSocketSession.send_bytes + never = asyncio.Event() + + async def send(self, data): + if ormsgpack.unpackb(data).get("event") == "text": + await never.wait() + return await real_send(self, data) + + monkeypatch.setattr(AsyncWebSocketSession, "send_bytes", send) + + +class TestTextStreamErrorsReachTheCaller: + """An error in text_stream ends the stream with that error, not a hang.""" + + def test_sync_text_stream_error_is_raised(self): + error = ValueError("text stream failed") + + def text_stream(): + yield "hello" + raise error + + with serving(waiting_script) as (server, client): + thread, result = _consume_in_thread(client, text_stream()) + thread.join(3) + hung = thread.is_alive() + if not hung: + server.stop() + assert not hung, "still waiting for audio after text_stream raised" + assert result["error"] is error + + def test_sync_item_that_is_not_text_is_raised(self): + with serving(waiting_script) as (server, client): + thread, result = _consume_in_thread(client, iter(["hello", None])) + thread.join(3) + hung = thread.is_alive() + if not hung: + server.stop() + assert not hung + assert "text" in str(result["error"]) + + async def test_async_text_stream_error_is_raised(self): + error = ValueError("text stream failed") + + async def text_stream(): + yield "hello" + await asyncio.sleep(0.02) + raise error + + async def consume(client): + return [c async for c in client.tts.stream_websocket(text_stream())] + + async with aserving(waiting_script) as (server, client): + with pytest.raises(ValueError) as raised: + await asyncio.wait_for(consume(client), 3) + server.stop() + assert raised.value is error + + async def test_async_item_that_is_not_text_is_raised(self): + async def consume(client): + return [c async for c in client.tts.stream_websocket(_aiter("hello", None))] + + async with aserving(waiting_script) as (server, client): + with pytest.raises(Exception, match="text"): + await asyncio.wait_for(consume(client), 3) + server.stop() + + async def test_async_caller_cancellation_is_not_swallowed(self): + """Cancelling the caller's own task while it waits for audio cancels it.""" + never = asyncio.Event() + + async def text_stream(): + yield "hello" + await never.wait() + + async def consume(client): + return [c async for c in client.tts.stream_websocket(text_stream())] + + async with aserving(waiting_script) as (server, client): + task = asyncio.ensure_future(consume(client)) + await asyncio.sleep(0.3) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(task, 3) + server.stop() + + +class TestTextStreamIsClosed: + """The SDK closes a generator text_stream when the stream ends, however it ends.""" + + @staticmethod + def _sync_generator(gate, closed): + def text_stream(): + try: + yield "first" + gate.wait(5) # the stream ends while this read waits + yield "late" # the sender takes it and stops: suspended here + yield "never" + finally: + closed.set() + + return text_stream() + + @pytest.mark.parametrize( + ("script", "mode", "expect_error"), + [ + (rejecting_after_text_script, "all", WebSocketError), + (None, "close_after_first", None), + (early_finish_script, "all", None), + ], + ids=["server_error", "early_close", "normal_end"], + ) + def test_sync_generator_is_closed(self, script, mode, expect_error): + if script is None: + + def script(conn): + while conn.recv().get("event") != "text": + pass + conn.send({"event": "audio", "audio": b"audio"}) + conn.wait_gone() + + gate, closed = threading.Event(), threading.Event() + gen = self._sync_generator(gate, closed) # held: not closed by GC + with serving(script) as (server, client): + thread, result = _consume_in_thread(client, gen, mode) + thread.join(3) + assert not thread.is_alive() + gate.set() + assert closed.wait(3), "text_stream was left open" + server.stop() + if expect_error: + assert isinstance(result.get("error"), expect_error) + else: + assert result["audio"] == b"audio" + + def test_sync_generator_cleanup_that_hangs_does_not_hold_the_stream(self): + gate, entered, hang = threading.Event(), threading.Event(), threading.Event() + + def text_stream(): + try: + yield "first" + gate.wait(5) + yield "late" + finally: + entered.set() + hang.wait(5) # cleanup that does not finish + + gen = text_stream() + with serving(early_finish_script) as (server, client): + thread, result = _consume_in_thread(client, gen) + thread.join(3) + assert not thread.is_alive() + gate.set() + assert entered.wait(3), "text_stream was not closed" + server.stop() + hang.set() + assert result["audio"] == b"audio" + + def test_iterable_that_is_not_a_generator_is_left_alone(self): + """Guard: only generators are closed; this passes before the change too.""" + + class Texts: + closed = False + + def __iter__(self): + return iter(["hello"]) + + def close(self): + Texts.closed = True + + with serving(tts_script) as (server, client): + audio = b"".join(client.tts.stream_websocket(Texts())) + server.stop() + assert audio == b"audio" + assert Texts.closed is False + + @pytest.mark.parametrize( + ("script", "mode", "expect_error"), + [ + (rejecting_script, "all", WebSocketError), + (audio_then_wait_script, "close_after_first", None), + (audio_then_finish_script, "all", None), + ], + ids=["server_error", "early_close", "normal_end"], + ) + async def test_async_generator_is_closed( + self, monkeypatch, script, mode, expect_error + ): + _block_text_sends(monkeypatch) # the generator stays suspended at its yield + closed = asyncio.Event() + + async def text_stream(): + try: + yield "first" + yield "never" + finally: + closed.set() + + gen = text_stream() # held: not closed by GC + + async def consume(client): + stream = client.tts.stream_websocket(gen) + if mode == "close_after_first": + try: + return await stream.__anext__() + finally: + await stream.aclose() + return b"".join([c async for c in stream]) + + async with aserving(script) as (server, client): + if expect_error: + with pytest.raises(expect_error): + await asyncio.wait_for(consume(client), 3) + else: + assert await asyncio.wait_for(consume(client), 3) == b"audio" + assert closed.is_set(), "text_stream was left open" + server.stop() + + async def test_async_generator_cleanup_that_hangs_is_bounded(self, monkeypatch): + _block_text_sends(monkeypatch) + entered = asyncio.Event() + never = asyncio.Event() + + async def text_stream(): + try: + yield "first" + finally: + entered.set() + await never.wait() # cleanup that does not finish + + gen = text_stream() + + async def consume(client): + return b"".join([c async for c in client.tts.stream_websocket(gen)]) + + try: + async with aserving(audio_then_finish_script) as (server, client): + loop = asyncio.get_running_loop() + started = loop.time() + assert await asyncio.wait_for(consume(client), 3) == b"audio" + elapsed = loop.time() - started + assert entered.is_set(), "text_stream was not closed" + server.stop() + finally: + never.set() # let the cleanup end before the event loop closes + await asyncio.sleep(0.05) + assert elapsed < 2.5 + + +class TestTextStreamThatIsNotIterable: + def test_sync(self): + with serving(waiting_script) as (server, client): + thread, result = _consume_in_thread(client, 42) + thread.join(3) + hung = thread.is_alive() + if not hung: + server.stop() + assert not hung + assert isinstance(result["error"], TypeError) + + async def test_async(self): + async def consume(client): + return [c async for c in client.tts.stream_websocket(["hello"])] + + async with aserving(waiting_script) as (server, client): + with pytest.raises(TypeError, match="async iterable"): + await asyncio.wait_for(consume(client), 3) + server.stop() From c941f9dbac536e73106983fa185c6d8ca088eeee Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 1 Dec 2026 04:51:23 -0800 Subject: [PATCH 12/29] fix(tts): keep text_stream cleanup off the caller's path and uncut - sync: when the connection fails before the sender runs, a generator the caller had already started is closed on a thread of its own, so its cleanup cannot delay the connection error. - async: the stream's cleanup no longer cancels a sender that is already closing text_stream, which cut the generator's own cleanup short; the bounded wait still applies. - async: an error raised by text_stream.__aiter__() ends the stream with that error instead of hanging; only an object without __aiter__ gets the "must be an async iterable" TypeError. - tests: the finish-while-text_stream-waits tests now let the server finish only once text_stream has entered its blocked read, so the sender's next read is not raced by the finish. --- src/fishaudio/resources/tts.py | 40 ++++++++++++--- tests/unit/test_tts_language.py | 91 ++++++++++++++++++++++++++++++++- 2 files changed, 122 insertions(+), 9 deletions(-) diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 3db6791..afb459d 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -746,9 +746,23 @@ def sender(): # cannot read from a reused fd belonging to the next connection. drain_reader(ws) finally: - # A sender that never ran cannot close text_stream itself. + # A sender that never ran cannot close text_stream itself. A + # generator the caller had already started runs cleanup code when + # closed, so that is done on a thread of its own: the stream (for + # example a failed connection's error) does not wait for it. if sender_future is None or sender_future.cancel(): - _close_text_stream(text_stream) + if ( + inspect.isgenerator(text_stream) + and inspect.getgeneratorstate(text_stream) == inspect.GEN_SUSPENDED + ): + threading.Thread( + target=_close_text_stream, + args=(text_stream,), + name="fishaudio-tts-text-stream-close", + daemon=True, + ).start() + else: + _close_text_stream(text_stream) executor.shutdown(wait=False) @@ -1270,6 +1284,9 @@ async def receiver() -> None: receiver_task = asyncio.create_task(receiver()) + # Set once the sender is closing text_stream. + sender_closing = asyncio.Event() + def text_stream_failed(error: BaseException) -> None: if not stopped.is_set() and not failure: failure.append(error) @@ -1284,9 +1301,7 @@ async def sender() -> None: StartEvent(request=tts_request).model_dump() ) ) - try: - items = text_stream.__aiter__() - except AttributeError: + if not hasattr(type(text_stream), "__aiter__"): text_stream_failed( TypeError( "text_stream must be an async iterable, got " @@ -1294,6 +1309,11 @@ async def sender() -> None: ) ) return + try: + items = text_stream.__aiter__() + except Exception as e: + text_stream_failed(e) + return while True: try: item = await items.__anext__() @@ -1314,12 +1334,16 @@ async def sender() -> None: finally: # Inside the bounded wait below when the stream ends # first, so a cleanup that does not finish cannot hold - # the connection open. + # the connection open. The cleanup below does not + # cancel a sender that has got here: that would cut + # text_stream's own cleanup short. + sender_closing.set() await _aclose_text_stream(text_stream) def sender_done(task: asyncio.Task[None]) -> None: # Only the cleanup below cancels the sender, after setting - # stopped: a cancellation before that came from text_stream. + # stopped: a cancellation before that is not ours (for + # example text_stream awaited something that was cancelled). if task.cancelled(): text_stream_failed( WebSocketError( @@ -1363,6 +1387,8 @@ def sender_done(task: asyncio.Task[None]) -> None: task for task in (sender_task, receiver_task) if not task.done() } for task in pending: + if task is sender_task and sender_closing.is_set(): + continue # closing text_stream: waited for, not cut task.cancel() for task in (sender_task, receiver_task): task.add_done_callback(_retrieve_exception) diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index c96630e..3544f41 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -405,6 +405,22 @@ def early_finish_script(conn): conn.send({"event": "finish", "reason": "stop"}) +def finish_when(waiting): + """Like early_finish_script, but finishes only once text_stream has entered + the read it blocks in (``waiting`` is set right before it): otherwise the + finish can arrive before the sender reads again, and that read never comes. + """ + + def script(conn): + while conn.recv().get("event") != "text": + pass + assert waiting.wait(5) + conn.send({"event": "audio", "audio": b"audio"}) + conn.send({"event": "finish", "reason": "stop"}) + + return script + + class TestTextStreamOutlivesTheStream: def test_text_stream_ending_after_an_error_sends_no_stop(self, monkeypatch): """text_stream ends only after the stream raised: no stop on a closed socket.""" @@ -431,10 +447,12 @@ def text_stream(): def test_finish_while_text_stream_waits_ends_the_stream(self, monkeypatch): attempted = _record_sends(monkeypatch, WebSocketSession) gate = threading.Event() + waiting = threading.Event() late_read = threading.Event() def text_stream(): yield "first" + waiting.set() gate.wait(5) late_read.set() yield "late" @@ -444,7 +462,7 @@ def text_stream(): def consume(client): result["audio"] = b"".join(client.tts.stream_websocket(text_stream())) - with serving(early_finish_script) as (server, client): + with serving(finish_when(waiting)) as (server, client): consumer = threading.Thread(target=consume, args=(client,), daemon=True) consumer.start() consumer.join(2) @@ -489,11 +507,13 @@ async def test_async_text_stream_that_ignores_cancellation_sends_nothing_more( """A text_stream may catch the cancellation and yield again: not sent.""" attempted = _record_sends(monkeypatch, AsyncWebSocketSession, is_async=True) never = asyncio.Event() + waiting = threading.Event() # read by the server's thread late_yielded = asyncio.Event() async def text_stream(): yield "first" try: + waiting.set() await never.wait() except asyncio.CancelledError: late_yielded.set() @@ -502,7 +522,7 @@ async def text_stream(): async def consume(client): return [chunk async for chunk in client.tts.stream_websocket(text_stream())] - async with aserving(early_finish_script) as (server, client): + async with aserving(finish_when(waiting)) as (server, client): chunks = await asyncio.wait_for(consume(client), 2) await asyncio.wait_for(late_yielded.wait(), 2) await asyncio.sleep(0.2) # the sender's chance to send "late" @@ -822,3 +842,70 @@ async def consume(client): with pytest.raises(TypeError, match="async iterable"): await asyncio.wait_for(consume(client), 3) server.stop() + + +class TestClosingTextStreamEdgeCases: + def test_sync_failed_connection_does_not_wait_for_started_generator(self): + """A generator the caller already started is closed off the caller's thread.""" + hang, entered = threading.Event(), threading.Event() + + def text_stream(): + try: + yield "first" + yield "second" + finally: + entered.set() + hang.wait(5) # cleanup that does not finish + + gen = text_stream() + assert next(gen) == "first" # started by the caller + server = RealtimeServer(lambda conn: None, reject_status=401) + client = FishAudio(api_key="test-key", base_url=server.url) + try: + started = time.monotonic() + with pytest.raises(Exception): + list(client.tts.stream_websocket(gen)) + elapsed = time.monotonic() - started + assert entered.wait(3), "text_stream was not closed" + finally: + hang.set() + client.close() + server.close() + assert elapsed < 1 + + async def test_async_cleanup_already_started_is_not_cut_short(self): + """After a bad item the sender closes text_stream; that cleanup completes.""" + cleaned = asyncio.Event() + + async def text_stream(): + try: + yield "hello" + yield None # not text: ends the stream + yield "never" + finally: + await asyncio.sleep(0.05) # cleanup that takes a moment + cleaned.set() + + async def consume(client): + return [c async for c in client.tts.stream_websocket(text_stream())] + + async with aserving(waiting_script) as (server, client): + with pytest.raises(Exception, match="text"): + await asyncio.wait_for(consume(client), 3) + assert cleaned.is_set(), "text_stream's cleanup was cut short" + server.stop() + + @pytest.mark.parametrize("error", [ValueError("no"), AttributeError("inner")]) + async def test_async_error_from_aiter_is_raised_as_is(self, error): + class Texts: + def __aiter__(self): + raise error + + async def consume(client): + return [c async for c in client.tts.stream_websocket(Texts())] + + async with aserving(waiting_script) as (server, client): + with pytest.raises(type(error)) as raised: + await asyncio.wait_for(consume(client), 3) + server.stop() + assert raised.value is error From 4e02e774d17de51ffe6198875be6a79de838aac3 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 1 Dec 2026 05:05:33 -0800 Subject: [PATCH 13/29] fix(tts): do not lose a send error while text_stream is being closed The sender now closes text_stream in its finally block, which can take a while. A send or encoding error raised before that was only reported once the sender had finished, so a server finish arriving during the cleanup ended the stream as a success. The error is now recorded before the cleanup starts and raised when the stream ends normally. --- src/fishaudio/resources/tts.py | 26 +++++++++++++++---- tests/unit/test_tts_language.py | 44 +++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 5 deletions(-) diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index afb459d..e7f2d2c 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -671,6 +671,8 @@ def text_generator(): # Why text_stream failed, set by the sender; the receive loop # raises it instead of waiting for audio that will not come. failure: list[BaseException] = [] + # Any other error of the sender (a send, an encoding). + sender_error: list[BaseException] = [] def sender(): try: @@ -709,6 +711,12 @@ def sender(): failure.append(e) return ws.send_bytes(ormsgpack.packb(event.model_dump())) + except Exception as e: + # A send or encoding error. Recorded before the + # cleanup below, which can take a while: the stream + # must not end as a success meanwhile. + if not stopped.is_set(): + sender_error.append(e) finally: # By this thread: a generator cannot be closed from # another thread while it is running. @@ -730,8 +738,8 @@ def sender(): stopped.set() if failure: raise failure[0] - if sender_future.done(): - sender_future.result() + if sender_error: + raise sender_error[0] finally: # Runs when the stream ends: it finished, it raised (an error # event, a disconnect, a failed text_stream), or the caller @@ -1286,6 +1294,8 @@ async def receiver() -> None: # Set once the sender is closing text_stream. sender_closing = asyncio.Event() + # Any other error of the sender (a send, an encoding). + sender_error: list[BaseException] = [] def text_stream_failed(error: BaseException) -> None: if not stopped.is_set() and not failure: @@ -1331,6 +1341,12 @@ async def sender() -> None: await ws.send_bytes( ormsgpack.packb(CloseEvent().model_dump()) ) + except Exception as e: + # A send or encoding error. Recorded before the + # cleanup below, which can take a while: the stream + # must not end as a success meanwhile. + if not stopped.is_set(): + sender_error.append(e) finally: # Inside the bounded wait below when the stream ends # first, so a cleanup that does not finish cannot hold @@ -1368,10 +1384,10 @@ def sender_done(task: asyncio.Task[None]) -> None: raise failure[0] # The server can finish while text_stream is still waiting # for input. Do not wait for it then (it is cancelled - # below); a sender that has already ended reports its + # below); a sender that has already failed reports its # error here. - if sender_task.done(): - await sender_task + if sender_error: + raise sender_error[0] finally: # Runs when the stream ends: it finished, it raised (an # error event, a disconnect, a failed text_stream), or the diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index 3544f41..431f0f1 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -909,3 +909,47 @@ async def consume(client): await asyncio.wait_for(consume(client), 3) server.stop() assert raised.value is error + + +def finish_soon_after_text_script(conn): + """Finishes shortly after the first text, without waiting for the stop.""" + while conn.recv().get("event") != "text": + pass + time.sleep(0.05) + conn.send({"event": "audio", "audio": b"audio"}) + conn.send({"event": "finish", "reason": "stop"}) + + +class TestSenderErrorDuringSlowCleanup: + """A send or encoding error is not lost while text_stream's cleanup runs.""" + + def test_sync(self): + def text_stream(): + try: + yield "first" + yield "\ud800" # a lone surrogate: cannot be encoded + finally: + time.sleep(0.2) # cleanup that takes a while + + with serving(finish_soon_after_text_script) as (server, client): + thread, result = _consume_in_thread(client, text_stream()) + thread.join(3) + assert not thread.is_alive() + server.stop() + assert "error" in result, "a failed send ended as a success" + + async def test_async(self): + async def text_stream(): + try: + yield "first" + yield "\ud800" # a lone surrogate: cannot be encoded + finally: + await asyncio.sleep(0.2) # cleanup that takes a while + + async def consume(client): + return [c async for c in client.tts.stream_websocket(text_stream())] + + async with aserving(finish_soon_after_text_script) as (server, client): + with pytest.raises(Exception): # noqa: B017 - the encoder's own error + await asyncio.wait_for(consume(client), 3) + server.stop() From d545c7227d33098024cfa952bf53730897d94af7 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 1 Dec 2026 05:23:15 -0800 Subject: [PATCH 14/29] fix(tts): close sync text_stream off the executor; keep every sender error - sync: a generator suspended at a yield is now closed on a daemon thread. Closed in the executor's worker, cleanup that did not finish kept the interpreter from exiting, since exit joins those threads. - sync: a BaseException from text_stream (such as CancelledError) is recorded like any other error, and a completed sender's result is still checked, so neither ends the stream as a success. - sync and async: an item that cannot be encoded is treated like one that is not text: it ends the stream at once instead of waiting for the server. --- src/fishaudio/resources/realtime.py | 2 +- src/fishaudio/resources/tts.py | 88 ++++++++++++++++++----------- tests/unit/test_tts_language.py | 67 +++++++++++++++++++++- 3 files changed, 122 insertions(+), 35 deletions(-) diff --git a/src/fishaudio/resources/realtime.py b/src/fishaudio/resources/realtime.py index 8b1d797..9d17b62 100644 --- a/src/fishaudio/resources/realtime.py +++ b/src/fishaudio/resources/realtime.py @@ -84,7 +84,7 @@ def iter_websocket_audio( else: try: message = ws.receive_bytes(timeout=poll_seconds) - except (queue.Empty, TimeoutError): # httpx-ws < 0.8 / >= 0.8 + except (queue.Empty, TimeoutError): # no message in time continue data = ormsgpack.unpackb(message) diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index e7f2d2c..9c99eb9 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -118,6 +118,26 @@ def _close_text_stream(text_stream: object) -> None: logger.debug("Closing text_stream failed", exc_info=True) +def _close_text_stream_in_background(text_stream: object) -> None: + """Close a generator text_stream without waiting for its cleanup. + + A generator that has not started, or has ended, runs no code when closed: + that is done here. One suspended at a yield runs its ``finally`` blocks, so + it is closed on a daemon thread. The caller must not be running it. + """ + if not inspect.isgenerator(text_stream): + return + if inspect.getgeneratorstate(text_stream) != inspect.GEN_SUSPENDED: + _close_text_stream(text_stream) + return + threading.Thread( + target=_close_text_stream, + args=(text_stream,), + name="fishaudio-tts-text-stream-close", + daemon=True, + ).start() + + async def _aclose_text_stream(text_stream: object) -> None: """Close an async-generator text_stream. Other iterables are left alone.""" if inspect.isasyncgen(text_stream): @@ -671,7 +691,7 @@ def text_generator(): # Why text_stream failed, set by the sender; the receive loop # raises it instead of waiting for audio that will not come. failure: list[BaseException] = [] - # Any other error of the sender (a send, an encoding). + # Any other error of the sender (a send). sender_error: list[BaseException] = [] def sender(): @@ -683,9 +703,13 @@ def sender(): ) # Check before each read as well as after it: once the # stream is over, text_stream is not read again. + # Errors of text_stream itself, and of turning its + # items into messages (bad data from the caller), end + # the stream: BaseException too, so that one such as + # CancelledError is not taken for success. try: items = iter(text_stream) - except Exception as e: + except BaseException as e: failure.append(e) return while not stopped.is_set(): @@ -698,29 +722,33 @@ def sender(): ormsgpack.packb(CloseEvent().model_dump()) ) return - except Exception as e: + except BaseException as e: if not stopped.is_set(): failure.append(e) return if stopped.is_set(): return - # Normalize strings to TextEvent try: + # Normalize strings to TextEvent event = _normalize_to_event(item) - except Exception as e: + message = ormsgpack.packb(event.model_dump()) + except BaseException as e: failure.append(e) return - ws.send_bytes(ormsgpack.packb(event.model_dump())) - except Exception as e: - # A send or encoding error. Recorded before the - # cleanup below, which can take a while: the stream - # must not end as a success meanwhile. + ws.send_bytes(message) + except BaseException as e: + # A send error. Recorded before the cleanup below, + # which can take a while: the stream must not end as a + # success meanwhile. if not stopped.is_set(): sender_error.append(e) finally: - # By this thread: a generator cannot be closed from - # another thread while it is running. - _close_text_stream(text_stream) + # Once the last read has returned, text_stream is not + # running, so another thread may close it: one of its + # own, so that cleanup which does not finish holds + # neither the stream nor the interpreter's exit (which + # joins the executor's threads). + _close_text_stream_in_background(text_stream) sender_future = executor.submit(sender) @@ -740,6 +768,8 @@ def sender(): raise failure[0] if sender_error: raise sender_error[0] + if sender_future.done(): + sender_future.result() # anything not recorded above finally: # Runs when the stream ends: it finished, it raised (an error # event, a disconnect, a failed text_stream), or the caller @@ -756,21 +786,10 @@ def sender(): finally: # A sender that never ran cannot close text_stream itself. A # generator the caller had already started runs cleanup code when - # closed, so that is done on a thread of its own: the stream (for - # example a failed connection's error) does not wait for it. + # closed: the stream (for example a failed connection's error) + # does not wait for it. if sender_future is None or sender_future.cancel(): - if ( - inspect.isgenerator(text_stream) - and inspect.getgeneratorstate(text_stream) == inspect.GEN_SUSPENDED - ): - threading.Thread( - target=_close_text_stream, - args=(text_stream,), - name="fishaudio-tts-text-stream-close", - daemon=True, - ).start() - else: - _close_text_stream(text_stream) + _close_text_stream_in_background(text_stream) executor.shutdown(wait=False) @@ -1294,7 +1313,7 @@ async def receiver() -> None: # Set once the sender is closing text_stream. sender_closing = asyncio.Event() - # Any other error of the sender (a send, an encoding). + # Any other error of the sender (a send). sender_error: list[BaseException] = [] def text_stream_failed(error: BaseException) -> None: @@ -1329,22 +1348,25 @@ async def sender() -> None: item = await items.__anext__() if stopped.is_set(): return - # Normalize strings to TextEvent + # Normalize strings to TextEvent; an item + # that cannot be encoded is bad data from the + # caller, like one that is not text. event = _normalize_to_event(item) + message = ormsgpack.packb(event.model_dump()) except StopAsyncIteration: break except Exception as e: text_stream_failed(e) return - await ws.send_bytes(ormsgpack.packb(event.model_dump())) + await ws.send_bytes(message) if not stopped.is_set(): await ws.send_bytes( ormsgpack.packb(CloseEvent().model_dump()) ) except Exception as e: - # A send or encoding error. Recorded before the - # cleanup below, which can take a while: the stream - # must not end as a success meanwhile. + # A send error. Recorded before the cleanup below, + # which can take a while: the stream must not end as a + # success meanwhile. if not stopped.is_set(): sender_error.append(e) finally: diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index 431f0f1..16bc509 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -950,6 +950,71 @@ async def consume(client): return [c async for c in client.tts.stream_websocket(text_stream())] async with aserving(finish_soon_after_text_script) as (server, client): - with pytest.raises(Exception): # noqa: B017 - the encoder's own error + with pytest.raises(TypeError): # the encoder's own error, not a timeout + await asyncio.wait_for(consume(client), 3) + server.stop() + + +class TestRoundThreeEdgeCases: + def test_sync_cleanup_runs_on_a_daemon_thread(self): + """Cleanup that does not finish must not hold the interpreter's exit, + which joins the executor's (non-daemon) threads.""" + gate = threading.Event() + cleanup_thread = {} + closed = threading.Event() + + def text_stream(): + try: + yield "first" + gate.wait(5) + yield "late" + finally: + cleanup_thread["name"] = threading.current_thread().name + cleanup_thread["daemon"] = threading.current_thread().daemon + closed.set() + + gen = text_stream() + with serving(early_finish_script) as (server, client): + thread, result = _consume_in_thread(client, gen) + thread.join(3) + assert not thread.is_alive() + gate.set() + assert closed.wait(3) + server.stop() + assert cleanup_thread["daemon"] is True, cleanup_thread + assert cleanup_thread["name"] == "fishaudio-tts-text-stream-close" + + def test_sync_base_exception_from_text_stream_is_raised(self): + error = asyncio.CancelledError("source cancelled") + + def text_stream(): + yield "first" + raise error + + with serving(finish_soon_after_text_script) as (server, client): + thread, result = _consume_in_thread(client, text_stream()) + thread.join(3) + assert not thread.is_alive() + server.stop() + assert result.get("error") is error + + def test_sync_item_that_cannot_be_encoded_is_raised(self): + with serving(waiting_script) as (server, client): + thread, result = _consume_in_thread(client, iter(["hello", "\ud800"])) + thread.join(3) + hung = thread.is_alive() + if not hung: + server.stop() + assert not hung, "still waiting for audio after an item failed to encode" + assert isinstance(result.get("error"), TypeError) + + async def test_async_item_that_cannot_be_encoded_is_raised(self): + async def consume(client): + return [ + c async for c in client.tts.stream_websocket(_aiter("hello", "\ud800")) + ] + + async with aserving(waiting_script) as (server, client): + with pytest.raises(TypeError): # the encoder's own error, not a timeout await asyncio.wait_for(consume(client), 3) server.stop() From 4849fbbb2a790444b85692484506f0fc4bfa8a98 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 1 Dec 2026 05:23:24 -0800 Subject: [PATCH 15/29] docs(tts): say the sync text_stream is closed on a background thread --- src/fishaudio/resources/tts.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 9c99eb9..b95cbd7 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -567,8 +567,9 @@ def stream_websocket( the SDK stops reading it: a read already waiting completes in the worker thread and its text is not sent. When the stream ends, however it ends, the SDK closes a generator text_stream - (`close()`) from the worker thread, so its `finally` blocks - run; the stream does not wait for that. Other iterables are + (`close()`) on a background thread once its last read has + returned, so its `finally` blocks run; neither the stream nor + the interpreter's exit waits for that. Other iterables are not closed. reference_id: Voice reference ID (overrides config.reference_id if provided) references: Reference audio samples (overrides config.references if provided) From 95e6dc8eb6b53baddd0bddf0046ad0721ae04f4c Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 1 Dec 2026 05:34:50 -0800 Subject: [PATCH 16/29] fix(tts): close a sync text_stream on the thread that ran it Closing a suspended sync generator on a background thread (d545c72) broke what it holds when that belongs to the thread that made it, such as an sqlite3 connection. A generator is now closed on the thread that last ran it: the sender's worker thread, or the caller's thread when the sender never ran. Like a read that never returns, cleanup that never finishes keeps that thread; the docstring says so. Async: a BaseException from text_stream other than our cancellation (GeneratorExit, a custom one) ends the stream with that error instead of a success, and a finished sender's result is checked again before reporting success. --- src/fishaudio/resources/tts.py | 58 ++++++++++++--------------------- tests/unit/test_tts_language.py | 57 ++++++++++++++++++++------------ 2 files changed, 58 insertions(+), 57 deletions(-) diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index b95cbd7..ae040e5 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -118,26 +118,6 @@ def _close_text_stream(text_stream: object) -> None: logger.debug("Closing text_stream failed", exc_info=True) -def _close_text_stream_in_background(text_stream: object) -> None: - """Close a generator text_stream without waiting for its cleanup. - - A generator that has not started, or has ended, runs no code when closed: - that is done here. One suspended at a yield runs its ``finally`` blocks, so - it is closed on a daemon thread. The caller must not be running it. - """ - if not inspect.isgenerator(text_stream): - return - if inspect.getgeneratorstate(text_stream) != inspect.GEN_SUSPENDED: - _close_text_stream(text_stream) - return - threading.Thread( - target=_close_text_stream, - args=(text_stream,), - name="fishaudio-tts-text-stream-close", - daemon=True, - ).start() - - async def _aclose_text_stream(text_stream: object) -> None: """Close an async-generator text_stream. Other iterables are left alone.""" if inspect.isasyncgen(text_stream): @@ -567,10 +547,11 @@ def stream_websocket( the SDK stops reading it: a read already waiting completes in the worker thread and its text is not sent. When the stream ends, however it ends, the SDK closes a generator text_stream - (`close()`) on a background thread once its last read has - returned, so its `finally` blocks run; neither the stream nor - the interpreter's exit waits for that. Other iterables are - not closed. + (`close()`) on the worker thread that read it, once its last + read has returned, so its `finally` blocks run there; the + stream does not wait for that. Other iterables are not closed. + Like a read that never returns, cleanup that never finishes + keeps the worker thread, and with it the interpreter's exit. reference_id: Voice reference ID (overrides config.reference_id if provided) references: Reference audio samples (overrides config.references if provided) format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided) @@ -744,12 +725,10 @@ def sender(): if not stopped.is_set(): sender_error.append(e) finally: - # Once the last read has returned, text_stream is not - # running, so another thread may close it: one of its - # own, so that cleanup which does not finish holds - # neither the stream nor the interpreter's exit (which - # joins the executor's threads). - _close_text_stream_in_background(text_stream) + # By this thread, which ran it: a generator cannot be + # closed from another thread while it is running, and + # what it holds may belong to the thread that made it. + _close_text_stream(text_stream) sender_future = executor.submit(sender) @@ -785,12 +764,11 @@ def sender(): # cannot read from a reused fd belonging to the next connection. drain_reader(ws) finally: - # A sender that never ran cannot close text_stream itself. A - # generator the caller had already started runs cleanup code when - # closed: the stream (for example a failed connection's error) - # does not wait for it. + # A sender that never ran cannot close text_stream itself: it is + # closed here, on the caller's thread, which is the one that ran it + # if anything did. if sender_future is None or sender_future.cancel(): - _close_text_stream_in_background(text_stream) + _close_text_stream(text_stream) executor.shutdown(wait=False) @@ -1341,7 +1319,7 @@ async def sender() -> None: return try: items = text_stream.__aiter__() - except Exception as e: + except BaseException as e: text_stream_failed(e) return while True: @@ -1356,7 +1334,11 @@ async def sender() -> None: message = ormsgpack.packb(event.model_dump()) except StopAsyncIteration: break - except Exception as e: + except asyncio.CancelledError: + raise # ours, or reported by sender_done + except BaseException as e: + # BaseException too (GeneratorExit, ...): an + # interrupted text_stream is not a success. text_stream_failed(e) return await ws.send_bytes(message) @@ -1411,6 +1393,8 @@ def sender_done(task: asyncio.Task[None]) -> None: # error here. if sender_error: raise sender_error[0] + if sender_task.done(): + await sender_task # anything not recorded above finally: # Runs when the stream ends: it finished, it raised (an # error event, a disconnect, a failed text_stream), or the diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index 16bc509..a306cf3 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -845,33 +845,29 @@ async def consume(client): class TestClosingTextStreamEdgeCases: - def test_sync_failed_connection_does_not_wait_for_started_generator(self): - """A generator the caller already started is closed off the caller's thread.""" - hang, entered = threading.Event(), threading.Event() + def test_sync_failed_connection_closes_on_the_callers_thread(self): + """A generator the caller started, and the SDK never ran, is closed on + the caller's thread when the connection fails.""" + closed_on = [] def text_stream(): try: yield "first" yield "second" finally: - entered.set() - hang.wait(5) # cleanup that does not finish + closed_on.append(threading.get_ident()) gen = text_stream() - assert next(gen) == "first" # started by the caller + assert next(gen) == "first" # started by the caller, on this thread server = RealtimeServer(lambda conn: None, reject_status=401) client = FishAudio(api_key="test-key", base_url=server.url) try: - started = time.monotonic() - with pytest.raises(Exception): + with pytest.raises(Exception): # noqa: B017 - the upgrade error list(client.tts.stream_websocket(gen)) - elapsed = time.monotonic() - started - assert entered.wait(3), "text_stream was not closed" finally: - hang.set() client.close() server.close() - assert elapsed < 1 + assert closed_on == [threading.get_ident()] async def test_async_cleanup_already_started_is_not_cut_short(self): """After a bad item the sender closes text_stream; that cleanup completes.""" @@ -956,21 +952,21 @@ async def consume(client): class TestRoundThreeEdgeCases: - def test_sync_cleanup_runs_on_a_daemon_thread(self): - """Cleanup that does not finish must not hold the interpreter's exit, - which joins the executor's (non-daemon) threads.""" + def test_sync_generator_is_closed_on_the_thread_that_ran_it(self): + """What a generator holds may belong to the thread that made it (an + sqlite3 connection, for example): it is closed on that thread.""" gate = threading.Event() - cleanup_thread = {} + threads = {} closed = threading.Event() def text_stream(): try: + threads["ran"] = threading.get_ident() yield "first" gate.wait(5) yield "late" finally: - cleanup_thread["name"] = threading.current_thread().name - cleanup_thread["daemon"] = threading.current_thread().daemon + threads["closed"] = threading.get_ident() closed.set() gen = text_stream() @@ -981,8 +977,7 @@ def text_stream(): gate.set() assert closed.wait(3) server.stop() - assert cleanup_thread["daemon"] is True, cleanup_thread - assert cleanup_thread["name"] == "fishaudio-tts-text-stream-close" + assert threads["closed"] == threads["ran"] def test_sync_base_exception_from_text_stream_is_raised(self): error = asyncio.CancelledError("source cancelled") @@ -1018,3 +1013,25 @@ async def consume(client): with pytest.raises(TypeError): # the encoder's own error, not a timeout await asyncio.wait_for(consume(client), 3) server.stop() + + +class _SourceInterrupted(BaseException): + pass + + +class TestAsyncBaseExceptionFromTextStream: + async def test_is_raised_not_taken_for_success(self): + error = _SourceInterrupted("interrupted") + + async def text_stream(): + yield "first" + raise error + + async def consume(client): + return [c async for c in client.tts.stream_websocket(text_stream())] + + async with aserving(finish_soon_after_text_script) as (server, client): + with pytest.raises(_SourceInterrupted) as raised: + await asyncio.wait_for(consume(client), 3) + server.stop() + assert raised.value is error From d15ef9eed9e8e76278dfbdabbcdc8572e3a36846 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 1 Dec 2026 05:48:51 -0800 Subject: [PATCH 17/29] fix(tts): close text_stream only once the SDK has read from it When the connection failed before the sender read text_stream, the SDK still closed it: on the caller's thread for sync, where a generator the caller had started could delay the connection error, and in a new task for async, where its cleanup ran in another context (a ContextVar reset fails there). The SDK now owns closing text_stream from its first read on; one it never read is left to the caller, as it was before. The async docstring now says that a cancellation of text_stream reaches the caller as WebSocketError, so it is not taken for one of their own. --- src/fishaudio/resources/tts.py | 353 ++++++++++++++++---------------- tests/unit/test_tts_language.py | 43 +++- 2 files changed, 212 insertions(+), 184 deletions(-) diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index ae040e5..78bd3a3 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -547,9 +547,11 @@ def stream_websocket( the SDK stops reading it: a read already waiting completes in the worker thread and its text is not sent. When the stream ends, however it ends, the SDK closes a generator text_stream - (`close()`) on the worker thread that read it, once its last - read has returned, so its `finally` blocks run there; the - stream does not wait for that. Other iterables are not closed. + it has started reading (`close()`) on the worker thread that + read it, once its last read has returned, so its `finally` + blocks run there; the stream does not wait for that. One it + never read (the connection failed first) and other iterables + are not closed. Like a read that never returns, cleanup that never finishes keeps the worker thread, and with it the interpreter's exit. reference_id: Voice reference ID (overrides config.reference_id if provided) @@ -675,6 +677,7 @@ def text_generator(): failure: list[BaseException] = [] # Any other error of the sender (a send). sender_error: list[BaseException] = [] + read_from = [False] # whether the SDK has read text_stream def sender(): try: @@ -695,6 +698,8 @@ def sender(): failure.append(e) return while not stopped.is_set(): + # From the first read on, closing it is the SDK's. + read_from[0] = True try: item = next(items) except StopIteration: @@ -728,7 +733,9 @@ def sender(): # By this thread, which ran it: a generator cannot be # closed from another thread while it is running, and # what it holds may belong to the thread that made it. - _close_text_stream(text_stream) + # One the SDK never read from is left to the caller. + if read_from[0]: + _close_text_stream(text_stream) sender_future = executor.submit(sender) @@ -764,11 +771,10 @@ def sender(): # cannot read from a reused fd belonging to the next connection. drain_reader(ws) finally: - # A sender that never ran cannot close text_stream itself: it is - # closed here, on the caller's thread, which is the one that ran it - # if anything did. - if sender_future is None or sender_future.cancel(): - _close_text_stream(text_stream) + # A sender that never ran has not read text_stream: it stays the + # caller's, untouched. + if sender_future is not None: + sender_future.cancel() executor.shutdown(wait=False) @@ -1130,13 +1136,16 @@ async def stream_websocket( Args: text_stream: Async iterator of text chunks to stream. If it - raises, the stream ends and raises that same exception. If the + raises, the stream ends and raises that same exception; if it + is cancelled, the stream raises WebSocketError instead, so the + cancellation is not mistaken for one of your task. If the stream ends first (the server finishes, an error, or you close it), the SDK stops reading it and cancels the task sending it; nothing more is sent. When the stream ends, however it ends, - the SDK closes an async-generator text_stream (`aclose()`), so - its `finally` blocks run; it waits for that at most one second. - Other async iterables are not closed. + the SDK closes an async-generator text_stream it has started + reading (`aclose()`), so its `finally` blocks run; it waits + for that at most one second. One it never read (the connection + failed first) and other async iterables are not closed. reference_id: Voice reference ID (overrides config.reference_id if provided) references: Reference audio samples (overrides config.references if provided) format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided) @@ -1243,185 +1252,175 @@ async def text_generator(): # Prepare WebSocket connection kwargs ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} - sender_started = False - try: - ws: AsyncWebSocketSession - async with aconnect_ws( - "/v1/tts/live", - client=self._client.client, - headers=self._client.get_headers({"model": model}), - **ws_kwargs, - ) as ws: - # Set when the stream ends. Cancelling the sender is not enough - # on its own: a text_stream may catch the cancellation and - # yield again. - stopped = asyncio.Event() - # Why text_stream failed; raised to the caller in place of - # audio that will not come. - failure: list[BaseException] = [] - # Audio chunks, then _END (or the server's error), handed from - # the receiver task to this generator one at a time. - chunks: asyncio.Queue[Any] = asyncio.Queue() - - async def receiver() -> None: - try: - async for audio_chunk in aiter_websocket_audio(ws): - chunks.put_nowait(audio_chunk) - await chunks.join() # until it has been taken + ws: AsyncWebSocketSession + async with aconnect_ws( + "/v1/tts/live", + client=self._client.client, + headers=self._client.get_headers({"model": model}), + **ws_kwargs, + ) as ws: + # Set when the stream ends. Cancelling the sender is not enough + # on its own: a text_stream may catch the cancellation and + # yield again. + stopped = asyncio.Event() + # Why text_stream failed; raised to the caller in place of + # audio that will not come. + failure: list[BaseException] = [] + # Audio chunks, then _END (or the server's error), handed from + # the receiver task to this generator one at a time. + chunks: asyncio.Queue[Any] = asyncio.Queue() + + async def receiver() -> None: + try: + async for audio_chunk in aiter_websocket_audio(ws): + chunks.put_nowait(audio_chunk) + await chunks.join() # until it has been taken + chunks.put_nowait(_END) + except asyncio.CancelledError: + # This task is ours alone: it is cancelled when + # text_stream failed or the stream is being cleaned up. + # Any other cancellation must not end the audio early + # as if it were complete. + if failure or stopped.is_set(): chunks.put_nowait(_END) - except asyncio.CancelledError: - # This task is ours alone: it is cancelled when - # text_stream failed or the stream is being cleaned up. - # Any other cancellation must not end the audio early - # as if it were complete. - if failure or stopped.is_set(): - chunks.put_nowait(_END) - else: - chunks.put_nowait( - _Raise( - WebSocketError( - "Receiving audio was cancelled before " - "the stream ended" - ) + else: + chunks.put_nowait( + _Raise( + WebSocketError( + "Receiving audio was cancelled before " + "the stream ended" ) ) - except BaseException as e: - chunks.put_nowait(_Raise(e)) + ) + except BaseException as e: + chunks.put_nowait(_Raise(e)) - receiver_task = asyncio.create_task(receiver()) + receiver_task = asyncio.create_task(receiver()) - # Set once the sender is closing text_stream. - sender_closing = asyncio.Event() - # Any other error of the sender (a send). - sender_error: list[BaseException] = [] + # Set once the sender is closing text_stream. + sender_closing = asyncio.Event() + # Any other error of the sender (a send). + sender_error: list[BaseException] = [] - def text_stream_failed(error: BaseException) -> None: - if not stopped.is_set() and not failure: - failure.append(error) - receiver_task.cancel() + def text_stream_failed(error: BaseException) -> None: + if not stopped.is_set() and not failure: + failure.append(error) + receiver_task.cancel() - async def sender() -> None: - nonlocal sender_started - sender_started = True - try: - await ws.send_bytes( - ormsgpack.packb( - StartEvent(request=tts_request).model_dump() + async def sender() -> None: + read_from = False # whether the SDK has read text_stream + try: + await ws.send_bytes( + ormsgpack.packb(StartEvent(request=tts_request).model_dump()) + ) + if not hasattr(type(text_stream), "__aiter__"): + text_stream_failed( + TypeError( + "text_stream must be an async iterable, got " + f"{type(text_stream).__name__}" ) ) - if not hasattr(type(text_stream), "__aiter__"): - text_stream_failed( - TypeError( - "text_stream must be an async iterable, got " - f"{type(text_stream).__name__}" - ) - ) - return + return + try: + items = text_stream.__aiter__() + except BaseException as e: + text_stream_failed(e) + return + while True: + # From the first read on, closing it is the SDK's. + read_from = True try: - items = text_stream.__aiter__() + item = await items.__anext__() + if stopped.is_set(): + return + # Normalize strings to TextEvent; an item + # that cannot be encoded is bad data from the + # caller, like one that is not text. + event = _normalize_to_event(item) + message = ormsgpack.packb(event.model_dump()) + except StopAsyncIteration: + break + except asyncio.CancelledError: + raise # ours, or reported by sender_done except BaseException as e: + # BaseException too (GeneratorExit, ...): an + # interrupted text_stream is not a success. text_stream_failed(e) return - while True: - try: - item = await items.__anext__() - if stopped.is_set(): - return - # Normalize strings to TextEvent; an item - # that cannot be encoded is bad data from the - # caller, like one that is not text. - event = _normalize_to_event(item) - message = ormsgpack.packb(event.model_dump()) - except StopAsyncIteration: - break - except asyncio.CancelledError: - raise # ours, or reported by sender_done - except BaseException as e: - # BaseException too (GeneratorExit, ...): an - # interrupted text_stream is not a success. - text_stream_failed(e) - return - await ws.send_bytes(message) - if not stopped.is_set(): - await ws.send_bytes( - ormsgpack.packb(CloseEvent().model_dump()) - ) - except Exception as e: - # A send error. Recorded before the cleanup below, - # which can take a while: the stream must not end as a - # success meanwhile. - if not stopped.is_set(): - sender_error.append(e) - finally: - # Inside the bounded wait below when the stream ends - # first, so a cleanup that does not finish cannot hold - # the connection open. The cleanup below does not - # cancel a sender that has got here: that would cut - # text_stream's own cleanup short. - sender_closing.set() + await ws.send_bytes(message) + if not stopped.is_set(): + await ws.send_bytes(ormsgpack.packb(CloseEvent().model_dump())) + except Exception as e: + # A send error. Recorded before the cleanup below, + # which can take a while: the stream must not end as a + # success meanwhile. + if not stopped.is_set(): + sender_error.append(e) + finally: + # Inside the bounded wait below when the stream ends + # first, so a cleanup that does not finish cannot hold + # the connection open. The cleanup below does not + # cancel a sender that has got here: that would cut + # text_stream's own cleanup short. + # One the SDK never read from is left to the caller: + # its context and cleanup are the caller's. + sender_closing.set() + if read_from: await _aclose_text_stream(text_stream) - def sender_done(task: asyncio.Task[None]) -> None: - # Only the cleanup below cancels the sender, after setting - # stopped: a cancellation before that is not ours (for - # example text_stream awaited something that was cancelled). - if task.cancelled(): - text_stream_failed( - WebSocketError( - "text_stream was cancelled before the stream ended" - ) + def sender_done(task: asyncio.Task[None]) -> None: + # Only the cleanup below cancels the sender, after setting + # stopped: a cancellation before that is not ours (for + # example text_stream awaited something that was cancelled). + if task.cancelled(): + text_stream_failed( + WebSocketError( + "text_stream was cancelled before the stream ended" ) + ) - sender_task = asyncio.create_task(sender()) - sender_task.add_done_callback(sender_done) - - try: - while True: - item = await chunks.get() - chunks.task_done() - if item is _END: - break - if isinstance(item, _Raise): - raise item.error - yield item + sender_task = asyncio.create_task(sender()) + sender_task.add_done_callback(sender_done) - if failure: - raise failure[0] - # The server can finish while text_stream is still waiting - # for input. Do not wait for it then (it is cancelled - # below); a sender that has already failed reports its - # error here. - if sender_error: - raise sender_error[0] - if sender_task.done(): - await sender_task # anything not recorded above - finally: - # Runs when the stream ends: it finished, it raised (an - # error event, a disconnect, a failed text_stream), or the - # caller closed it with aclose(). A plain `break` does not - # close it. The sender is cancelled and closes text_stream; - # the wait is bounded, like the realtime speech-to-text - # session, so a text_stream whose cleanup never finishes - # cannot hold the connection open. asyncio.wait does not - # raise the tasks' errors, and a cancellation of the - # caller's own task still reaches the caller. - stopped.set() - pending = { - task for task in (sender_task, receiver_task) if not task.done() - } - for task in pending: - if task is sender_task and sender_closing.is_set(): - continue # closing text_stream: waited for, not cut - task.cancel() - for task in (sender_task, receiver_task): - task.add_done_callback(_retrieve_exception) - if pending: - await asyncio.wait(pending, timeout=_SENDER_CLEANUP_SECONDS) - finally: - # A sender that never ran cannot close text_stream itself. Bounded - # too: a text_stream the caller had already started has cleanup - # that runs here. - if not sender_started: - closer = asyncio.ensure_future(_aclose_text_stream(text_stream)) - closer.add_done_callback(_retrieve_exception) - await asyncio.wait({closer}, timeout=_SENDER_CLEANUP_SECONDS) + try: + while True: + item = await chunks.get() + chunks.task_done() + if item is _END: + break + if isinstance(item, _Raise): + raise item.error + yield item + + if failure: + raise failure[0] + # The server can finish while text_stream is still waiting + # for input. Do not wait for it then (it is cancelled + # below); a sender that has already failed reports its + # error here. + if sender_error: + raise sender_error[0] + if sender_task.done(): + await sender_task # anything not recorded above + finally: + # Runs when the stream ends: it finished, it raised (an + # error event, a disconnect, a failed text_stream), or the + # caller closed it with aclose(). A plain `break` does not + # close it. The sender is cancelled and closes text_stream; + # the wait is bounded, like the realtime speech-to-text + # session, so a text_stream whose cleanup never finishes + # cannot hold the connection open. asyncio.wait does not + # raise the tasks' errors, and a cancellation of the + # caller's own task still reaches the caller. + stopped.set() + pending = { + task for task in (sender_task, receiver_task) if not task.done() + } + for task in pending: + if task is sender_task and sender_closing.is_set(): + continue # closing text_stream: waited for, not cut + task.cancel() + for task in (sender_task, receiver_task): + task.add_done_callback(_retrieve_exception) + if pending: + await asyncio.wait(pending, timeout=_SENDER_CLEANUP_SECONDS) diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index a306cf3..e93836d 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -8,6 +8,7 @@ import asyncio import contextlib +import inspect import threading import time @@ -845,20 +846,19 @@ async def consume(client): class TestClosingTextStreamEdgeCases: - def test_sync_failed_connection_closes_on_the_callers_thread(self): - """A generator the caller started, and the SDK never ran, is closed on - the caller's thread when the connection fails.""" - closed_on = [] + def test_sync_failed_connection_leaves_an_unread_generator_alone(self): + """The SDK never read it: its cleanup (and when) stays the caller's.""" + cleaned = [] def text_stream(): try: yield "first" yield "second" finally: - closed_on.append(threading.get_ident()) + cleaned.append(True) gen = text_stream() - assert next(gen) == "first" # started by the caller, on this thread + assert next(gen) == "first" # started by the caller server = RealtimeServer(lambda conn: None, reject_status=401) client = FishAudio(api_key="test-key", base_url=server.url) try: @@ -867,7 +867,36 @@ def text_stream(): finally: client.close() server.close() - assert closed_on == [threading.get_ident()] + assert cleaned == [] + assert inspect.getgeneratorstate(gen) == inspect.GEN_SUSPENDED + gen.close() # the caller's to close + assert cleaned == [True] + + async def test_async_failed_connection_leaves_an_unread_generator_alone(self): + """The SDK never read it: its context and cleanup stay the caller's.""" + cleaned = [] + + async def text_stream(): + try: + yield "first" + yield "second" + finally: + cleaned.append(True) + + gen = text_stream() + assert await gen.__anext__() == "first" # started by the caller + server = RealtimeServer(lambda conn: None, reject_status=401) + client = AsyncFishAudio(api_key="test-key", base_url=server.url) + try: + with pytest.raises(Exception): # noqa: B017 - the upgrade error + async for _ in client.tts.stream_websocket(gen): + pass + finally: + await client.close() + server.close() + assert cleaned == [] + await gen.aclose() # the caller's to close + assert cleaned == [True] async def test_async_cleanup_already_started_is_not_cut_short(self): """After a bad item the sender closes text_stream; that cleanup completes.""" From 6702c41ed5ceca9ab668f12717fc5cffb6aa5ac2 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 1 Dec 2026 06:03:26 -0800 Subject: [PATCH 18/29] fix(tts): report every async text_stream cancellation as WebSocketError A CancelledError raised by text_stream.__aiter__() reached the caller as it was, and a sender cancelled by text_stream just before the stream ended could be awaited before its done-callback had converted the cancellation. Both now raise WebSocketError, so a cancellation of text_stream is never mistaken for one of the caller's own task. --- src/fishaudio/resources/tts.py | 23 ++++++++++---- tests/unit/test_tts_language.py | 55 +++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 6 deletions(-) diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 78bd3a3..773f93e 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -118,6 +118,17 @@ def _close_text_stream(text_stream: object) -> None: logger.debug("Closing text_stream failed", exc_info=True) +def _from_text_stream(error: BaseException) -> BaseException: + """The error to raise to the caller for one from the async text_stream. + + A cancellation of text_stream is reported as WebSocketError: raised as it + is, it would look like a cancellation of the caller's own task. + """ + if isinstance(error, asyncio.CancelledError): + return WebSocketError("text_stream was cancelled before the stream ended") + return error + + async def _aclose_text_stream(text_stream: object) -> None: """Close an async-generator text_stream. Other iterables are left alone.""" if inspect.isasyncgen(text_stream): @@ -1304,7 +1315,7 @@ async def receiver() -> None: def text_stream_failed(error: BaseException) -> None: if not stopped.is_set() and not failure: - failure.append(error) + failure.append(_from_text_stream(error)) receiver_task.cancel() async def sender() -> None: @@ -1373,11 +1384,7 @@ def sender_done(task: asyncio.Task[None]) -> None: # stopped: a cancellation before that is not ours (for # example text_stream awaited something that was cancelled). if task.cancelled(): - text_stream_failed( - WebSocketError( - "text_stream was cancelled before the stream ended" - ) - ) + text_stream_failed(asyncio.CancelledError()) sender_task = asyncio.create_task(sender()) sender_task.add_done_callback(sender_done) @@ -1401,6 +1408,10 @@ def sender_done(task: asyncio.Task[None]) -> None: if sender_error: raise sender_error[0] if sender_task.done(): + # Checked here, not only in sender_done: that callback + # may not have run yet. + if sender_task.cancelled(): + raise _from_text_stream(asyncio.CancelledError()) await sender_task # anything not recorded above finally: # Runs when the stream ends: it finished, it raised (an diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index e93836d..532788b 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -1064,3 +1064,58 @@ async def consume(client): await asyncio.wait_for(consume(client), 3) server.stop() assert raised.value is error + + +class TestAsyncCancellationOfTextStream: + """A cancellation from text_stream reaches the caller as WebSocketError, + never as a cancellation of the caller's own task.""" + + async def test_cancelled_in_aiter(self): + class Texts: + def __aiter__(self): + future = asyncio.get_running_loop().create_future() + future.cancel() + return future.result() # raises CancelledError + + async def consume(client): + return [c async for c in client.tts.stream_websocket(Texts())] + + async with aserving(waiting_script) as (server, client): + with pytest.raises(WebSocketError, match="cancelled"): + await asyncio.wait_for(consume(client), 3) + server.stop() + + async def test_cancelled_just_before_the_end_is_seen(self): + """The sender is cancelled by text_stream and the stream then ends + before the sender's done-callback has run.""" + awaited = asyncio.get_running_loop().create_future() + + async def text_stream(): + yield "first" + await awaited + + async def steps(client): + # One task throughout: the stream's connection must be entered + # and left in the same task. + stream = client.tts.stream_websocket(text_stream()) + try: + assert await stream.__anext__() == b"audio" + await asyncio.sleep(0.2) # the finish is read and queued + awaited.cancel() + await asyncio.sleep(0) # the sender ends; its callback is pending + with pytest.raises(WebSocketError, match="cancelled"): + await stream.__anext__() + finally: + await stream.aclose() + + async with aserving(audio_then_finish_after_text_script) as (server, client): + await asyncio.wait_for(steps(client), 5) + server.stop() + + +def audio_then_finish_after_text_script(conn): + """Sends audio and finishes once the first text has arrived.""" + while conn.recv().get("event") != "text": + pass + conn.send({"event": "audio", "audio": b"audio"}) + conn.send({"event": "finish", "reason": "stop"}) From 5cdf1fee0bac75502dc4311b8eb74fd981fbc081 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 1 Dec 2026 06:31:38 -0800 Subject: [PATCH 19/29] test(tts): let the early-finish server script tolerate a client that already left The async BaseException test raises before the script writes its audio and finish, so the write could hit a closed socket (BrokenPipeError in about 1 run in 10). The script now ignores OSError on those writes. --- tests/unit/test_tts_language.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index 532788b..d024a50 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -937,12 +937,17 @@ async def consume(client): def finish_soon_after_text_script(conn): - """Finishes shortly after the first text, without waiting for the stop.""" + """Finishes shortly after the first text, without waiting for the stop. + + The client may already have raised and left by then (that is what some + tests check), so a write to a closed connection is not an error here. + """ while conn.recv().get("event") != "text": pass time.sleep(0.05) - conn.send({"event": "audio", "audio": b"audio"}) - conn.send({"event": "finish", "reason": "stop"}) + with contextlib.suppress(OSError): + conn.send({"event": "audio", "audio": b"audio"}) + conn.send({"event": "finish", "reason": "stop"}) class TestSenderErrorDuringSlowCleanup: From c84b6ff6b25a7fa4018e338c6f3aaa1b452bbadb Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 1 Dec 2026 07:23:05 -0800 Subject: [PATCH 20/29] fix(tts): let the server's finish decide over a failed send; never hang on one One rule for which outcome wins: 1. A failed text_stream ends the stream at once and wins. 2. Otherwise the server decides: finish is success, an error or close is that error. 3. A failed send of ours is raised only when the server has nothing more to say: messages that already arrived are still read, and when none arrives within _DRAIN_SECONDS (or the connection closes) the send error is raised. Same rule as the realtime speech-to-text session. 4. An error while the SDK cleans up (closing text_stream) is logged, never the outcome. Fixes: - A server that finishes and closes the connection before the client's stop no longer fails a complete stream with wsproto's LocalProtocolError (async: a regression in this branch; sync: older). - A failed send with a silent server no longer leaves the stream waiting forever (sync and async). - A cancellation raised by text_stream's cleanup no longer replaces a failed send's error. - The start event is encoded before connecting, so a request that cannot be encoded raises TypeError at once instead of hanging. - A text_stream cancellation reported as WebSocketError keeps the original as its cause. --- src/fishaudio/resources/realtime.py | 50 +++++++- src/fishaudio/resources/tts.py | 84 ++++++++------ tests/unit/test_tts_language.py | 170 ++++++++++++++++++++++++++++ 3 files changed, 267 insertions(+), 37 deletions(-) diff --git a/src/fishaudio/resources/realtime.py b/src/fishaudio/resources/realtime.py index 9d17b62..5ba9f72 100644 --- a/src/fishaudio/resources/realtime.py +++ b/src/fishaudio/resources/realtime.py @@ -9,6 +9,13 @@ from fishaudio.exceptions import WebSocketError +# Once a send has failed, only messages that already arrived are read: when +# none arrives within this time, the send error is raised. A send usually +# fails because the server is ending the connection, and what the server said +# (a finish, an error) is the better answer. Same rule as the realtime +# speech-to-text session. +_DRAIN_SECONDS = 0.05 + def _should_stop(data: dict[str, Any]) -> bool: """ @@ -53,6 +60,7 @@ def iter_websocket_audio( ws, failure: Optional[Callable[[], Optional[BaseException]]] = None, poll_seconds: float = 0.25, + send_failed: Optional[Callable[[], Optional[BaseException]]] = None, ) -> Iterator[bytes]: """ Process WebSocket audio messages (sync). @@ -67,6 +75,11 @@ def iter_websocket_audio( and a failure is raised as it is, instead of waiting for audio that will not come. poll_seconds: How often a waiting receive checks ``failure``. + send_failed: Returns the error of a failed send, or None. Once it + returns one, messages that already arrived are still read (a + finish among them ends the stream normally); when none arrives + within ``_DRAIN_SECONDS``, or the connection closes, that error + is raised. Needs ``failure``. Yields: Audio bytes @@ -78,13 +91,18 @@ def iter_websocket_audio( error = failure() if failure is not None else None if error is not None: raise error + send_error = send_failed() if send_failed is not None else None try: if failure is None: message = ws.receive_bytes() else: try: - message = ws.receive_bytes(timeout=poll_seconds) + message = ws.receive_bytes( + timeout=poll_seconds if send_error is None else _DRAIN_SECONDS + ) except (queue.Empty, TimeoutError): # no message in time + if send_error is not None: + raise send_error continue data = ormsgpack.unpackb(message) @@ -96,10 +114,16 @@ def iter_websocket_audio( yield audio except WebSocketDisconnect: + if send_error is not None: + raise send_error from None raise WebSocketError("WebSocket disconnected unexpectedly") -async def aiter_websocket_audio(ws) -> AsyncIterator[bytes]: +async def aiter_websocket_audio( + ws, + send_failed: Optional[Callable[[], Optional[BaseException]]] = None, + poll_seconds: float = 0.25, +) -> AsyncIterator[bytes]: """ Process WebSocket audio messages (async). @@ -108,6 +132,13 @@ async def aiter_websocket_audio(ws) -> AsyncIterator[bytes]: Args: ws: WebSocket connection from httpx_ws.aconnect_ws + send_failed: Returns the error of a failed send, or None. When given, + a receive waits at most ``poll_seconds`` before checking it + again. Once it returns one, messages that already arrived are + still read (a finish among them ends the stream normally); when + none arrives within ``_DRAIN_SECONDS``, or the connection + closes, that error is raised. + poll_seconds: How often a waiting receive checks ``send_failed``. Yields: Audio bytes @@ -116,8 +147,19 @@ async def aiter_websocket_audio(ws) -> AsyncIterator[bytes]: WebSocketError: On disconnect or error finish event """ while True: + send_error = send_failed() if send_failed is not None else None try: - message = await ws.receive_bytes() + if send_failed is None: + message = await ws.receive_bytes() + else: + try: + message = await ws.receive_bytes( + timeout=poll_seconds if send_error is None else _DRAIN_SECONDS + ) + except (queue.Empty, TimeoutError): # no message in time + if send_error is not None: + raise send_error + continue data = ormsgpack.unpackb(message) if _should_stop(data): @@ -128,4 +170,6 @@ async def aiter_websocket_audio(ws) -> AsyncIterator[bytes]: yield audio except WebSocketDisconnect: + if send_error is not None: + raise send_error from None raise WebSocketError("WebSocket disconnected unexpectedly") diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 773f93e..4284be7 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -110,11 +110,15 @@ def __init__(self, error: BaseException) -> None: def _close_text_stream(text_stream: object) -> None: - """Close a generator text_stream. Other iterables are left alone.""" + """Close a generator text_stream. Other iterables are left alone. + + Runs as cleanup, on the sender's own thread: whatever the close raises is + logged, never raised. It is not how the stream ended. + """ if inspect.isgenerator(text_stream): try: text_stream.close() - except Exception: + except BaseException: logger.debug("Closing text_stream failed", exc_info=True) @@ -125,16 +129,23 @@ def _from_text_stream(error: BaseException) -> BaseException: is, it would look like a cancellation of the caller's own task. """ if isinstance(error, asyncio.CancelledError): - return WebSocketError("text_stream was cancelled before the stream ended") + reported = WebSocketError("text_stream was cancelled before the stream ended") + reported.__cause__ = error + return reported return error async def _aclose_text_stream(text_stream: object) -> None: - """Close an async-generator text_stream. Other iterables are left alone.""" + """Close an async-generator text_stream. Other iterables are left alone. + + Runs as cleanup, in the SDK's own sender task: what the close raises, + a cancellation included, is logged, never raised. It is not how the + stream ended. + """ if inspect.isasyncgen(text_stream): try: await text_stream.aclose() - except Exception: + except (Exception, asyncio.CancelledError): logger.debug("Closing text_stream failed", exc_info=True) @@ -668,6 +679,10 @@ def text_generator(): if language is not None: tts_request.language = language + # Encoded before connecting: a request that cannot be encoded raises + # here instead of leaving the server waiting for it. + start_message = ormsgpack.packb(StartEvent(request=tts_request).model_dump()) + # Prepare WebSocket connection kwargs ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} @@ -686,17 +701,14 @@ def text_generator(): # Why text_stream failed, set by the sender; the receive loop # raises it instead of waiting for audio that will not come. failure: list[BaseException] = [] - # Any other error of the sender (a send). + # Any other error of the sender (a send). The receive loop + # raises it once the server has nothing more to say. sender_error: list[BaseException] = [] read_from = [False] # whether the SDK has read text_stream def sender(): try: - ws.send_bytes( - ormsgpack.packb( - StartEvent(request=tts_request).model_dump() - ) - ) + ws.send_bytes(start_message) # Check before each read as well as after it: once the # stream is over, text_stream is not read again. # Errors of text_stream itself, and of turning its @@ -736,8 +748,8 @@ def sender(): ws.send_bytes(message) except BaseException as e: # A send error. Recorded before the cleanup below, - # which can take a while: the stream must not end as a - # success meanwhile. + # which can take a while, so the receive loop sees it + # at once. if not stopped.is_set(): sender_error.append(e) finally: @@ -756,18 +768,16 @@ def sender(): ws, failure=lambda: failure[0] if failure else None, poll_seconds=_POLL_SECONDS, + send_failed=lambda: sender_error[0] if sender_error else None, ) - # The server can finish while text_stream is still waiting - # for input. Do not wait for it then; a sender that has - # already ended reports its error here. + # The server finished. It can do that while text_stream is + # still waiting for input: do not wait for it then. A + # failed text_stream still fails the stream; a failed send + # does not, once the server has finished. stopped.set() if failure: raise failure[0] - if sender_error: - raise sender_error[0] - if sender_future.done(): - sender_future.result() # anything not recorded above finally: # Runs when the stream ends: it finished, it raised (an error # event, a disconnect, a failed text_stream), or the caller @@ -1260,6 +1270,10 @@ async def text_generator(): if language is not None: tts_request.language = language + # Encoded before connecting: a request that cannot be encoded raises + # here instead of leaving the server waiting for it. + start_message = ormsgpack.packb(StartEvent(request=tts_request).model_dump()) + # Prepare WebSocket connection kwargs ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} @@ -1277,13 +1291,20 @@ async def text_generator(): # Why text_stream failed; raised to the caller in place of # audio that will not come. failure: list[BaseException] = [] + # Any other error of the sender (a send). The receiver raises it + # once the server has nothing more to say. + sender_error: list[BaseException] = [] # Audio chunks, then _END (or the server's error), handed from # the receiver task to this generator one at a time. chunks: asyncio.Queue[Any] = asyncio.Queue() async def receiver() -> None: try: - async for audio_chunk in aiter_websocket_audio(ws): + async for audio_chunk in aiter_websocket_audio( + ws, + send_failed=lambda: sender_error[0] if sender_error else None, + poll_seconds=_POLL_SECONDS, + ): chunks.put_nowait(audio_chunk) await chunks.join() # until it has been taken chunks.put_nowait(_END) @@ -1310,8 +1331,6 @@ async def receiver() -> None: # Set once the sender is closing text_stream. sender_closing = asyncio.Event() - # Any other error of the sender (a send). - sender_error: list[BaseException] = [] def text_stream_failed(error: BaseException) -> None: if not stopped.is_set() and not failure: @@ -1321,9 +1340,7 @@ def text_stream_failed(error: BaseException) -> None: async def sender() -> None: read_from = False # whether the SDK has read text_stream try: - await ws.send_bytes( - ormsgpack.packb(StartEvent(request=tts_request).model_dump()) - ) + await ws.send_bytes(start_message) if not hasattr(type(text_stream), "__aiter__"): text_stream_failed( TypeError( @@ -1363,8 +1380,8 @@ async def sender() -> None: await ws.send_bytes(ormsgpack.packb(CloseEvent().model_dump())) except Exception as e: # A send error. Recorded before the cleanup below, - # which can take a while: the stream must not end as a - # success meanwhile. + # which can take a while, so the receiver sees it at + # once. if not stopped.is_set(): sender_error.append(e) finally: @@ -1399,14 +1416,13 @@ def sender_done(task: asyncio.Task[None]) -> None: raise item.error yield item + # The server finished. It can do that while text_stream is + # still waiting for input: do not wait for it then (it is + # cancelled below). A failed text_stream still fails the + # stream; a failed send does not, once the server has + # finished. if failure: raise failure[0] - # The server can finish while text_stream is still waiting - # for input. Do not wait for it then (it is cancelled - # below); a sender that has already failed reports its - # error here. - if sender_error: - raise sender_error[0] if sender_task.done(): # Checked here, not only in sender_done: that callback # may not have run yet. diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index d024a50..09125ab 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -1124,3 +1124,173 @@ def audio_then_finish_after_text_script(conn): pass conn.send({"event": "audio", "audio": b"audio"}) conn.send({"event": "finish", "reason": "stop"}) + + +def finish_and_close_when(closed): + """Finishes after the first text and closes the connection (code 1000) + without waiting for the client's stop, as a server may; sets ``closed``.""" + + def script(conn): + while conn.recv().get("event") != "text": + pass + conn.send({"event": "audio", "audio": b"audio"}) + conn.send({"event": "finish", "reason": "stop"}) + conn.close(1000) + closed.set() + + return script + + +def _fail_text_sends(monkeypatch, session_class, is_async=False): + """Make every send of a text event fail; return the error it raises.""" + error = RuntimeError("send failed") + real_send = session_class.send_bytes + + if is_async: + + async def send(self, data): + if ormsgpack.unpackb(data).get("event") == "text": + raise error + return await real_send(self, data) + + else: + + def send(self, data): + if ormsgpack.unpackb(data).get("event") == "text": + raise error + return real_send(self, data) + + monkeypatch.setattr(session_class, "send_bytes", send) + return error + + +class TestWhichOutcomeWins: + """The server's finish decides over a failed send of ours; a failed send + decides only when the server says nothing more; an error while the SDK + cleans up never decides; a request that cannot be encoded fails at once.""" + + def test_sync_send_after_the_server_finished_and_closed_is_not_an_error(self): + closed = threading.Event() + ended = threading.Event() + + def text_stream(): + try: + yield "first" + assert closed.wait(5) + time.sleep(0.1) # the client has read the close by now + finally: + ended.set() # its stop is sent next, on a closed connection + + with serving(finish_and_close_when(closed)) as (server, client): + stream = client.tts.stream_websocket(text_stream()) + first = next(stream) + assert ended.wait(5) + time.sleep(0.2) # the stop has been tried by now + rest = list(stream) + server.stop() + assert [first, *rest] == [b"audio"] + + async def test_async_send_after_the_server_finished_and_closed_is_not_an_error( + self, + ): + closed = threading.Event() + ended = asyncio.Event() + + async def text_stream(): + try: + yield "first" + loop = asyncio.get_running_loop() + assert await loop.run_in_executor(None, closed.wait, 5) + await asyncio.sleep(0.1) # the client has read the close by now + finally: + ended.set() # its stop is sent next, on a closed connection + + async def consume(client): + stream = client.tts.stream_websocket(text_stream()) + first = await stream.__anext__() + await ended.wait() + await asyncio.sleep(0.2) # the stop has been tried by now + return [first] + [c async for c in stream] + + async with aserving(finish_and_close_when(closed)) as (server, client): + assert await asyncio.wait_for(consume(client), 5) == [b"audio"] + server.stop() + + def test_sync_failed_send_is_raised_when_the_server_says_nothing(self, monkeypatch): + error = _fail_text_sends(monkeypatch, WebSocketSession) + with serving(waiting_script) as (server, client): + thread, result = _consume_in_thread(client, iter(["hello"])) + thread.join(3) + assert not thread.is_alive(), "a failed send left the stream waiting" + server.stop() + assert result.get("error") is error + + async def test_async_failed_send_is_raised_when_the_server_says_nothing( + self, monkeypatch + ): + error = _fail_text_sends(monkeypatch, AsyncWebSocketSession, is_async=True) + + async def consume(client): + return [c async for c in client.tts.stream_websocket(_aiter("hello"))] + + async with aserving(waiting_script) as (server, client): + with pytest.raises(RuntimeError) as raised: + await asyncio.wait_for(consume(client), 3) + server.stop() + assert raised.value is error + + async def test_async_cancellation_in_cleanup_does_not_hide_a_failed_send( + self, monkeypatch + ): + error = _fail_text_sends(monkeypatch, AsyncWebSocketSession, is_async=True) + + async def text_stream(): + try: + yield "hello" + finally: + # Its cleanup awaits something that was cancelled. + cancelled = asyncio.get_running_loop().create_future() + cancelled.cancel() + await cancelled + + async def consume(client): + return [c async for c in client.tts.stream_websocket(text_stream())] + + async with aserving(waiting_script) as (server, client): + with pytest.raises(RuntimeError) as raised: + await asyncio.wait_for(consume(client), 3) + server.stop() + assert raised.value is error + + def test_sync_request_that_cannot_be_encoded_is_raised(self): + result = {} + + def run(): + try: + result["audio"] = b"".join( + client.tts.stream_websocket(iter(["hello"]), language="\ud800") + ) + except BaseException as e: # noqa: BLE001 - reported to the test + result["error"] = e + + with serving(waiting_script) as (server, client): + thread = threading.Thread(target=run, daemon=True) + thread.start() + thread.join(3) + assert not thread.is_alive(), "an unencodable request hung" + assert server.connection is None # raised before connecting + assert isinstance(result.get("error"), TypeError) + + async def test_async_request_that_cannot_be_encoded_is_raised(self): + async def consume(client): + return [ + c + async for c in client.tts.stream_websocket( + _aiter("hello"), language="\ud800" + ) + ] + + async with aserving(waiting_script) as (server, client): + with pytest.raises(TypeError): + await asyncio.wait_for(consume(client), 3) + assert server.connection is None # raised before connecting From 1d28e113e274f7f8a209f7ae31d32ca839728507 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 1 Dec 2026 07:43:40 -0800 Subject: [PATCH 21/29] fix(tts): a send that fails while receiving still names the cause; cleanup never decides - The receive loops check for a failed send when the connection fails or closes, not only before they start waiting, so a send that failed during the wait is raised instead of a generic disconnect error. - Closing text_stream logs any error, BaseException subclasses included, and never raises it; KeyboardInterrupt and SystemExit still propagate. --- src/fishaudio/resources/realtime.py | 26 +++++-- src/fishaudio/resources/tts.py | 11 ++- tests/unit/test_tts_language.py | 114 ++++++++++++++++++++++++++++ 3 files changed, 141 insertions(+), 10 deletions(-) diff --git a/src/fishaudio/resources/realtime.py b/src/fishaudio/resources/realtime.py index 5ba9f72..1e918e5 100644 --- a/src/fishaudio/resources/realtime.py +++ b/src/fishaudio/resources/realtime.py @@ -78,8 +78,8 @@ def iter_websocket_audio( send_failed: Returns the error of a failed send, or None. Once it returns one, messages that already arrived are still read (a finish among them ends the stream normally); when none arrives - within ``_DRAIN_SECONDS``, or the connection closes, that error - is raised. Needs ``failure``. + within ``_DRAIN_SECONDS``, or the connection closes or fails, + that error is raised. Needs ``failure``. Yields: Audio bytes @@ -104,6 +104,14 @@ def iter_websocket_audio( if send_error is not None: raise send_error continue + except Exception: + # The connection failed or closed while receiving. A send + # that failed meanwhile says why: checked now, not before + # the wait. + send_error = send_failed() if send_failed is not None else None + if send_error is not None: + raise send_error from None + raise data = ormsgpack.unpackb(message) if _should_stop(data): @@ -114,8 +122,6 @@ def iter_websocket_audio( yield audio except WebSocketDisconnect: - if send_error is not None: - raise send_error from None raise WebSocketError("WebSocket disconnected unexpectedly") @@ -137,7 +143,7 @@ async def aiter_websocket_audio( again. Once it returns one, messages that already arrived are still read (a finish among them ends the stream normally); when none arrives within ``_DRAIN_SECONDS``, or the connection - closes, that error is raised. + closes or fails, that error is raised. poll_seconds: How often a waiting receive checks ``send_failed``. Yields: @@ -160,6 +166,14 @@ async def aiter_websocket_audio( if send_error is not None: raise send_error continue + except Exception: + # The connection failed or closed while receiving. A send + # that failed meanwhile says why: checked now, not before + # the wait. + send_error = send_failed() if send_failed is not None else None + if send_error is not None: + raise send_error from None + raise data = ormsgpack.unpackb(message) if _should_stop(data): @@ -170,6 +184,4 @@ async def aiter_websocket_audio( yield audio except WebSocketDisconnect: - if send_error is not None: - raise send_error from None raise WebSocketError("WebSocket disconnected unexpectedly") diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 4284be7..97f4f54 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -113,11 +113,14 @@ def _close_text_stream(text_stream: object) -> None: """Close a generator text_stream. Other iterables are left alone. Runs as cleanup, on the sender's own thread: whatever the close raises is - logged, never raised. It is not how the stream ended. + logged, never raised. It is not how the stream ended. KeyboardInterrupt + and SystemExit still propagate. """ if inspect.isgenerator(text_stream): try: text_stream.close() + except (KeyboardInterrupt, SystemExit): + raise except BaseException: logger.debug("Closing text_stream failed", exc_info=True) @@ -140,12 +143,14 @@ async def _aclose_text_stream(text_stream: object) -> None: Runs as cleanup, in the SDK's own sender task: what the close raises, a cancellation included, is logged, never raised. It is not how the - stream ended. + stream ended. KeyboardInterrupt and SystemExit still propagate. """ if inspect.isasyncgen(text_stream): try: await text_stream.aclose() - except (Exception, asyncio.CancelledError): + except (KeyboardInterrupt, SystemExit): + raise + except BaseException: logger.debug("Closing text_stream failed", exc_info=True) diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index 09125ab..67cf877 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -20,6 +20,7 @@ from fishaudio import AsyncFishAudio, FishAudio, TTSConfig from fishaudio.core import AsyncClientWrapper, ClientWrapper from fishaudio.exceptions import WebSocketError +from fishaudio.resources import tts as tts_module from fishaudio.resources.tts import AsyncTTSClient, TTSClient from fishaudio.types import StartEvent, TTSRequest @@ -1294,3 +1295,116 @@ async def consume(client): with pytest.raises(TypeError): await asyncio.wait_for(consume(client), 3) assert server.connection is None # raised before connecting + + +def close_once(sent_failed): + """Waits until a send of the client has failed, then closes the + connection (code 1000) without a finish.""" + + def script(conn): + conn.recv() # start + assert sent_failed.wait(5) + time.sleep(0.1) # the client has recorded its send error by now + conn.close(1000) + + return script + + +def _fail_text_sends_and_signal(monkeypatch, session_class, is_async=False): + """Like _fail_text_sends; also sets the returned event when one fails.""" + error = RuntimeError("send failed") + sent_failed = threading.Event() + real_send = session_class.send_bytes + + if is_async: + + async def send(self, data): + if ormsgpack.unpackb(data).get("event") == "text": + sent_failed.set() + raise error + return await real_send(self, data) + + else: + + def send(self, data): + if ormsgpack.unpackb(data).get("event") == "text": + sent_failed.set() + raise error + return real_send(self, data) + + monkeypatch.setattr(session_class, "send_bytes", send) + return error, sent_failed + + +class _CleanupAbort(BaseException): + pass + + +class TestFailedSendWhileReceiving: + """A send that fails while the receive is already waiting is still the + reason given when the connection then closes. The receive does not poll + here (_POLL_SECONDS is long), so only the close wakes it.""" + + def test_sync(self, monkeypatch): + monkeypatch.setattr(tts_module, "_POLL_SECONDS", 30) + error, sent_failed = _fail_text_sends_and_signal(monkeypatch, WebSocketSession) + with serving(close_once(sent_failed)) as (server, client): + thread, result = _consume_in_thread(client, iter(["hello"])) + thread.join(5) + assert not thread.is_alive() + server.stop() + assert result.get("error") is error + + async def test_async(self, monkeypatch): + monkeypatch.setattr(tts_module, "_POLL_SECONDS", 30) + error, sent_failed = _fail_text_sends_and_signal( + monkeypatch, AsyncWebSocketSession, is_async=True + ) + + async def consume(client): + return [c async for c in client.tts.stream_websocket(_aiter("hello"))] + + async with aserving(close_once(sent_failed)) as (server, client): + with pytest.raises(RuntimeError) as raised: + await asyncio.wait_for(consume(client), 5) + server.stop() + assert raised.value is error + + +class TestCleanupNeverDecides: + """What closing text_stream raises is logged, not raised: it is not how + the stream ended. KeyboardInterrupt and SystemExit still propagate.""" + + def test_sync_close(self): + def text_stream(): + try: + yield "first" + finally: + raise _CleanupAbort + + items = text_stream() + next(items) + tts_module._close_text_stream(items) # does not raise + + def test_sync_close_keyboard_interrupt_propagates(self): + def text_stream(): + try: + yield "first" + finally: + raise KeyboardInterrupt + + items = text_stream() + next(items) + with pytest.raises(KeyboardInterrupt): + tts_module._close_text_stream(items) + + async def test_async_close(self): + async def text_stream(): + try: + yield "first" + finally: + raise _CleanupAbort + + items = text_stream() + await items.__anext__() + await tts_module._aclose_text_stream(items) # does not raise From 8c0218f174bf8ed1445c101f896f4af9083fa382 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 1 Dec 2026 08:01:49 -0800 Subject: [PATCH 22/29] fix(tts): log sync cleanup errors of every kind; order the receive-race test - On the sync worker thread a raise from closing text_stream reaches no one, so every error there is logged, KeyboardInterrupt and SystemExit included. - The failed-send-while-receiving tests now make the send fail only once the client is waiting in a receive, so they test that order every time. --- src/fishaudio/resources/tts.py | 8 +++----- tests/unit/test_tts_language.py | 29 ++++++++++++++++++++++++----- 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 97f4f54..521b197 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -112,15 +112,13 @@ def __init__(self, error: BaseException) -> None: def _close_text_stream(text_stream: object) -> None: """Close a generator text_stream. Other iterables are left alone. - Runs as cleanup, on the sender's own thread: whatever the close raises is - logged, never raised. It is not how the stream ended. KeyboardInterrupt - and SystemExit still propagate. + Runs as cleanup, on the sender's own worker thread: whatever the close + raises is logged, never raised. It is not how the stream ended, and + raised in a worker thread it would reach no one. """ if inspect.isgenerator(text_stream): try: text_stream.close() - except (KeyboardInterrupt, SystemExit): - raise except BaseException: logger.debug("Closing text_stream failed", exc_info=True) diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index 67cf877..bd1771d 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -1311,27 +1311,42 @@ def script(conn): def _fail_text_sends_and_signal(monkeypatch, session_class, is_async=False): - """Like _fail_text_sends; also sets the returned event when one fails.""" + """Like _fail_text_sends, but a send fails only once the client is + already waiting in a receive; sets the returned event when it fails.""" error = RuntimeError("send failed") sent_failed = threading.Event() + receiving = threading.Event() real_send = session_class.send_bytes + real_receive = session_class.receive_bytes if is_async: + async def receive(self, *args, **kwargs): + receiving.set() + return await real_receive(self, *args, **kwargs) + async def send(self, data): if ormsgpack.unpackb(data).get("event") == "text": + loop = asyncio.get_running_loop() + assert await loop.run_in_executor(None, receiving.wait, 5) sent_failed.set() raise error return await real_send(self, data) else: + def receive(self, *args, **kwargs): + receiving.set() + return real_receive(self, *args, **kwargs) + def send(self, data): if ormsgpack.unpackb(data).get("event") == "text": + assert receiving.wait(5) sent_failed.set() raise error return real_send(self, data) + monkeypatch.setattr(session_class, "receive_bytes", receive) monkeypatch.setattr(session_class, "send_bytes", send) return error, sent_failed @@ -1373,7 +1388,8 @@ async def consume(client): class TestCleanupNeverDecides: """What closing text_stream raises is logged, not raised: it is not how - the stream ended. KeyboardInterrupt and SystemExit still propagate.""" + the stream ended. (Async: KeyboardInterrupt and SystemExit still + propagate.)""" def test_sync_close(self): def text_stream(): @@ -1386,7 +1402,9 @@ def text_stream(): next(items) tts_module._close_text_stream(items) # does not raise - def test_sync_close_keyboard_interrupt_propagates(self): + def test_sync_close_logs_even_keyboard_interrupt(self, caplog): + """It runs on a worker thread, where a raise would reach no one.""" + def text_stream(): try: yield "first" @@ -1395,8 +1413,9 @@ def text_stream(): items = text_stream() next(items) - with pytest.raises(KeyboardInterrupt): - tts_module._close_text_stream(items) + with caplog.at_level("DEBUG", logger=tts_module.logger.name): + tts_module._close_text_stream(items) # does not raise + assert "Closing text_stream failed" in caplog.text async def test_async_close(self): async def text_stream(): From d00c11bd48dbbcd4838b3751f246813ef204374c Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 1 Dec 2026 08:23:47 -0800 Subject: [PATCH 23/29] fix(tts): one outcome rule for the receive loop Written at the top of resources/realtime.py: 1. A failure of text_stream wins, at once: checked when the connection ends and before each queued item, not only before a wait. 2. Otherwise the server decides: finish is success; an error event or a close is WebSocketError. 3. A failed send decides only when the server stays silent: one waiting budget of _DRAIN_SECONDS in all (time the caller spends on a chunk does not count). 4. A connection problem is WebSocketError("WebSocket connection lost"), with the transport error (a failed send preferred) as its cause. 5. Cleanup never decides. Also: iter_websocket_audio bounds its wait with send_failed alone, and an async text_stream cancellation keeps the original CancelledError as cause. --- src/fishaudio/resources/realtime.py | 206 +++++++++++++++--------- src/fishaudio/resources/tts.py | 15 +- tests/unit/test_tts_language.py | 232 +++++++++++++++++++++++++++- 3 files changed, 369 insertions(+), 84 deletions(-) diff --git a/src/fishaudio/resources/realtime.py b/src/fishaudio/resources/realtime.py index 1e918e5..bf5cdef 100644 --- a/src/fishaudio/resources/realtime.py +++ b/src/fishaudio/resources/realtime.py @@ -1,22 +1,74 @@ """Real-time WebSocket streaming helpers.""" import queue +import time from collections.abc import AsyncIterator, Iterator from typing import Any, Callable, Optional import ormsgpack -from httpx_ws import WebSocketDisconnect +from httpx_ws import HTTPXWSException, WebSocketDisconnect from fishaudio.exceptions import WebSocketError -# Once a send has failed, only messages that already arrived are read: when -# none arrives within this time, the send error is raised. A send usually -# fails because the server is ending the connection, and what the server said -# (a finish, an error) is the better answer. Same rule as the realtime -# speech-to-text session. +# Which outcome a stream reports: +# 1. A failure of text_stream (the caller's input) wins, at once. +# 2. Otherwise the server's word decides: a finish is success; an error event +# or a close is WebSocketError. +# 3. A failed send of ours decides only when the server stays silent: after +# it, receiving may wait at most _DRAIN_SECONDS in all (time the caller +# spends on a chunk does not count), so messages that already arrived are +# still read. A send usually fails because the server is ending the +# connection, and what the server said is the better answer. +# 4. A connection problem is WebSocketError, with the transport's error (a +# failed send preferred) as its __cause__. +# 5. An error while cleaning up is never the outcome. _DRAIN_SECONDS = 0.05 +ErrorCheck = Callable[[], Optional[BaseException]] + + +def _check(check: Optional[ErrorCheck]) -> Optional[BaseException]: + return check() if check is not None else None + + +def _connection_lost(cause: BaseException) -> WebSocketError: + error = WebSocketError("WebSocket connection lost") + error.__cause__ = cause + return error + + +def _ended( + error: HTTPXWSException, send_error: Optional[BaseException] +) -> WebSocketError: + """The error for a connection that ended without a finish (rules 2, 4).""" + if isinstance(error, WebSocketDisconnect): + ended = WebSocketError("WebSocket disconnected unexpectedly") + ended.__cause__ = send_error or error + return ended + return _connection_lost(send_error or error) + + +class _Drain: + """The waiting budget once a send has failed (rule 3).""" + + def __init__(self) -> None: + self.left: Optional[float] = None + + def timeout(self, send_error: Optional[BaseException], poll: float) -> float: + if send_error is not None and self.left is None: + self.left = _DRAIN_SECONDS + return poll if self.left is None else max(self.left, 0.001) + + def waited(self, seconds: float) -> None: + if self.left is not None: + self.left -= seconds + + @property + def spent(self) -> bool: + return self.left is not None and self.left <= 0 + + def _should_stop(data: dict[str, Any]) -> bool: """ Check if WebSocket event signals stream should stop. @@ -58,28 +110,25 @@ def _process_audio_event(data: dict[str, Any]) -> Optional[bytes]: def iter_websocket_audio( ws, - failure: Optional[Callable[[], Optional[BaseException]]] = None, + failure: Optional[ErrorCheck] = None, poll_seconds: float = 0.25, - send_failed: Optional[Callable[[], Optional[BaseException]]] = None, + send_failed: Optional[ErrorCheck] = None, ) -> Iterator[bytes]: """ Process WebSocket audio messages (sync). Receives messages from WebSocket, yields audio chunks, handles errors. - Unknown events are ignored and iteration continues. + Unknown events are ignored and iteration continues. Which error is + raised follows the rules at the top of this module. Args: ws: WebSocket connection from httpx_ws.connect_ws - failure: Returns why the text sender failed, or None. When given, a - receive waits at most ``poll_seconds`` before checking it again, - and a failure is raised as it is, instead of waiting for audio - that will not come. - poll_seconds: How often a waiting receive checks ``failure``. - send_failed: Returns the error of a failed send, or None. Once it - returns one, messages that already arrived are still read (a - finish among them ends the stream normally); when none arrives - within ``_DRAIN_SECONDS``, or the connection closes or fails, - that error is raised. Needs ``failure``. + failure: Returns why the text sender's input failed, or None. It is + checked before each receive and when the connection ends, and + raised as it is. + poll_seconds: How often a waiting receive checks ``failure`` and + ``send_failed``. + send_failed: Returns the error of a failed send, or None. Yields: Audio bytes @@ -87,63 +136,69 @@ def iter_websocket_audio( Raises: WebSocketError: On disconnect or error finish event """ + watching = failure is not None or send_failed is not None + drain = _Drain() while True: - error = failure() if failure is not None else None + error = _check(failure) if error is not None: raise error - send_error = send_failed() if send_failed is not None else None + send_error = _check(send_failed) try: - if failure is None: + if not watching: message = ws.receive_bytes() else: + started = time.monotonic() try: message = ws.receive_bytes( - timeout=poll_seconds if send_error is None else _DRAIN_SECONDS + timeout=drain.timeout(send_error, poll_seconds) ) except (queue.Empty, TimeoutError): # no message in time - if send_error is not None: - raise send_error + message = None + finally: + drain.waited(time.monotonic() - started) + if message is None: + if send_error is not None and drain.spent: + raise _connection_lost(send_error) continue - except Exception: - # The connection failed or closed while receiving. A send - # that failed meanwhile says why: checked now, not before - # the wait. - send_error = send_failed() if send_failed is not None else None - if send_error is not None: - raise send_error from None - raise - data = ormsgpack.unpackb(message) - - if _should_stop(data): - break - - audio = _process_audio_event(data) - if audio is not None: - yield audio - - except WebSocketDisconnect: - raise WebSocketError("WebSocket disconnected unexpectedly") + except HTTPXWSException as e: + ended: Optional[HTTPXWSException] = e + else: + ended = None + if ended is not None: + # Checked now, not before the wait: either may have failed + # meanwhile. Raised outside the except block, so the caller's + # own exception is raised untouched. + error = _check(failure) + if error is not None: + raise error + raise _ended(ended, _check(send_failed)) + + assert message is not None # None was handled above + data = ormsgpack.unpackb(message) + if _should_stop(data): + break + audio = _process_audio_event(data) + if audio is not None: + yield audio async def aiter_websocket_audio( ws, - send_failed: Optional[Callable[[], Optional[BaseException]]] = None, + send_failed: Optional[ErrorCheck] = None, poll_seconds: float = 0.25, ) -> AsyncIterator[bytes]: """ Process WebSocket audio messages (async). Receives messages from WebSocket, yields audio chunks, handles errors. - Unknown events are ignored and iteration continues. + Unknown events are ignored and iteration continues. Which error is + raised follows the rules at the top of this module (a failure of the + caller's input is handled by the caller of this function). Args: ws: WebSocket connection from httpx_ws.aconnect_ws send_failed: Returns the error of a failed send, or None. When given, - a receive waits at most ``poll_seconds`` before checking it - again. Once it returns one, messages that already arrived are - still read (a finish among them ends the stream normally); when - none arrives within ``_DRAIN_SECONDS``, or the connection - closes or fails, that error is raised. + a receive waits at most ``poll_seconds`` before checking it again. poll_seconds: How often a waiting receive checks ``send_failed``. Yields: @@ -152,36 +207,39 @@ async def aiter_websocket_audio( Raises: WebSocketError: On disconnect or error finish event """ + drain = _Drain() while True: - send_error = send_failed() if send_failed is not None else None + send_error = _check(send_failed) try: if send_failed is None: message = await ws.receive_bytes() else: + started = time.monotonic() try: message = await ws.receive_bytes( - timeout=poll_seconds if send_error is None else _DRAIN_SECONDS + timeout=drain.timeout(send_error, poll_seconds) ) except (queue.Empty, TimeoutError): # no message in time - if send_error is not None: - raise send_error + message = None + finally: + drain.waited(time.monotonic() - started) + if message is None: + if send_error is not None and drain.spent: + raise _connection_lost(send_error) continue - except Exception: - # The connection failed or closed while receiving. A send - # that failed meanwhile says why: checked now, not before - # the wait. - send_error = send_failed() if send_failed is not None else None - if send_error is not None: - raise send_error from None - raise - data = ormsgpack.unpackb(message) - - if _should_stop(data): - break - - audio = _process_audio_event(data) - if audio is not None: - yield audio - - except WebSocketDisconnect: - raise WebSocketError("WebSocket disconnected unexpectedly") + except HTTPXWSException as e: + ended: Optional[HTTPXWSException] = e + else: + ended = None + if ended is not None: + # Checked now, not before the wait: a send may have failed + # meanwhile. + raise _ended(ended, _check(send_failed)) + + assert message is not None # None was handled above + data = ormsgpack.unpackb(message) + if _should_stop(data): + break + audio = _process_audio_event(data) + if audio is not None: + yield audio diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 521b197..d73ab70 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -1371,8 +1371,15 @@ async def sender() -> None: message = ormsgpack.packb(event.model_dump()) except StopAsyncIteration: break - except asyncio.CancelledError: - raise # ours, or reported by sender_done + except asyncio.CancelledError as e: + # The cleanup below cancels the sender only + # after setting stopped: one before that came + # from text_stream, and is reported with the + # original as its cause. + if stopped.is_set(): + raise + text_stream_failed(e) + return except BaseException as e: # BaseException too (GeneratorExit, ...): an # interrupted text_stream is not a success. @@ -1413,6 +1420,10 @@ def sender_done(task: asyncio.Task[None]) -> None: while True: item = await chunks.get() chunks.task_done() + # A failed text_stream wins over what was already + # queued: audio, or the server's own error. + if failure: + raise failure[0] if item is _END: break if isinstance(item, _Raise): diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index bd1771d..53ab371 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -1224,7 +1224,8 @@ def test_sync_failed_send_is_raised_when_the_server_says_nothing(self, monkeypat thread.join(3) assert not thread.is_alive(), "a failed send left the stream waiting" server.stop() - assert result.get("error") is error + assert isinstance(result.get("error"), WebSocketError) + assert result["error"].__cause__ is error async def test_async_failed_send_is_raised_when_the_server_says_nothing( self, monkeypatch @@ -1235,10 +1236,10 @@ async def consume(client): return [c async for c in client.tts.stream_websocket(_aiter("hello"))] async with aserving(waiting_script) as (server, client): - with pytest.raises(RuntimeError) as raised: + with pytest.raises(WebSocketError) as raised: await asyncio.wait_for(consume(client), 3) server.stop() - assert raised.value is error + assert raised.value.__cause__ is error async def test_async_cancellation_in_cleanup_does_not_hide_a_failed_send( self, monkeypatch @@ -1258,10 +1259,10 @@ async def consume(client): return [c async for c in client.tts.stream_websocket(text_stream())] async with aserving(waiting_script) as (server, client): - with pytest.raises(RuntimeError) as raised: + with pytest.raises(WebSocketError) as raised: await asyncio.wait_for(consume(client), 3) server.stop() - assert raised.value is error + assert raised.value.__cause__ is error def test_sync_request_that_cannot_be_encoded_is_raised(self): result = {} @@ -1368,7 +1369,8 @@ def test_sync(self, monkeypatch): thread.join(5) assert not thread.is_alive() server.stop() - assert result.get("error") is error + assert isinstance(result.get("error"), WebSocketError) + assert result["error"].__cause__ is error async def test_async(self, monkeypatch): monkeypatch.setattr(tts_module, "_POLL_SECONDS", 30) @@ -1380,10 +1382,10 @@ async def consume(client): return [c async for c in client.tts.stream_websocket(_aiter("hello"))] async with aserving(close_once(sent_failed)) as (server, client): - with pytest.raises(RuntimeError) as raised: + with pytest.raises(WebSocketError) as raised: await asyncio.wait_for(consume(client), 5) server.stop() - assert raised.value is error + assert raised.value.__cause__ is error class TestCleanupNeverDecides: @@ -1427,3 +1429,217 @@ async def text_stream(): items = text_stream() await items.__anext__() await tts_module._aclose_text_stream(items) # does not raise + + +def audio_then_close_when(closed, code, chunks=1): + """Sends ``chunks`` audio messages after the first text, then closes with + ``code`` and no finish; sets ``closed``.""" + + def script(conn): + while conn.recv().get("event") != "text": + pass + for _ in range(chunks): + conn.send({"event": "audio", "audio": b"audio"}) + conn.close(code) + closed.set() + + return script + + +def chatter_script(conn): + """Never finishes: sends an unknown event every 20 ms for 3 s.""" + with contextlib.suppress(Exception): # the client may leave first + conn.recv() # start + for _ in range(150): + conn.send({"event": "log"}) + time.sleep(0.02) + + +class TestRefinedOutcomeRules: + """Rules at the top of fishaudio/resources/realtime.py.""" + + def test_sync_server_close_after_a_failed_send_is_a_websocket_error(self): + """Rule 2: the server's close decides; the failed send is the cause.""" + closed = threading.Event() + ended = threading.Event() + + def text_stream(): + try: + yield "first" + assert closed.wait(5) + time.sleep(0.1) # the client has read the close by now + yield "second" # its send fails: the server is closing + finally: + ended.set() + + with serving(audio_then_close_when(closed, 1011)) as (server, client): + stream = client.tts.stream_websocket(text_stream()) + assert next(stream) == b"audio" + assert ended.wait(5) + with pytest.raises(WebSocketError) as raised: + list(stream) + server.stop() + assert raised.value.__cause__ is not None + assert "Event" in str(raised.value.__cause__) # the failed send + + async def test_async_server_close_after_a_failed_send_is_a_websocket_error( + self, + ): + closed = threading.Event() + ended = asyncio.Event() + + async def text_stream(): + try: + yield "first" + loop = asyncio.get_running_loop() + assert await loop.run_in_executor(None, closed.wait, 5) + await asyncio.sleep(0.1) # the client has read the close by now + yield "second" # its send fails: the server is closing + finally: + ended.set() + + async def consume(client): + stream = client.tts.stream_websocket(text_stream()) + assert await stream.__anext__() == b"audio" + await ended.wait() + await asyncio.sleep(0.1) + return [c async for c in stream] + + # Two chunks: the receiver holds the second until the caller takes + # it, so it reads the close only after the send has failed. + script = audio_then_close_when(closed, 1011, chunks=2) + async with aserving(script) as (server, client): + with pytest.raises(WebSocketError) as raised: + await asyncio.wait_for(consume(client), 5) + server.stop() + assert "Event" in str(raised.value.__cause__) # the failed send + + def test_sync_text_stream_failing_during_a_wait_wins_over_the_close( + self, monkeypatch + ): + """Rule 1, checked when the connection ends, not before the wait.""" + monkeypatch.setattr(tts_module, "_POLL_SECONDS", 30) + error = ValueError("source failed") + failed = threading.Event() + + def text_stream(): + yield "first" + time.sleep(0.2) # the receive is waiting by now + failed.set() + raise error + + def script(conn): + while conn.recv().get("event") != "text": + pass + assert failed.wait(5) + time.sleep(0.1) + conn.close(1000) + + with serving(script) as (server, client): + thread, result = _consume_in_thread(client, text_stream()) + thread.join(5) + assert not thread.is_alive() + server.stop() + assert result.get("error") is error + + async def test_async_text_stream_failure_wins_over_a_queued_server_error(self): + """Rule 1, over what the receiver had already queued.""" + error = ValueError("source failed") + sent = threading.Event() + failed = asyncio.Event() + + async def text_stream(): + try: + yield "first" + loop = asyncio.get_running_loop() + assert await loop.run_in_executor(None, sent.wait, 5) + await asyncio.sleep(0.1) # the error event is queued by now + raise error + finally: + failed.set() + + def script(conn): + while conn.recv().get("event") != "text": + pass + conn.send({"event": "audio", "audio": b"audio"}) + conn.send({"event": "error", "error": "server failed"}) + sent.set() + conn.wait_gone() + + async def consume(client): + stream = client.tts.stream_websocket(text_stream()) + assert await stream.__anext__() == b"audio" + await failed.wait() + await asyncio.sleep(0.05) + return [c async for c in stream] + + async with aserving(script) as (server, client): + with pytest.raises(ValueError) as raised: + await asyncio.wait_for(consume(client), 5) + server.stop() + assert raised.value is error + + def test_sync_drain_has_one_budget(self, monkeypatch): + """Rule 3: messages that keep arriving do not postpone a failed send.""" + error = _fail_text_sends(monkeypatch, WebSocketSession) + with serving(chatter_script) as (server, client): + started = time.monotonic() + thread, result = _consume_in_thread(client, iter(["hello"])) + thread.join(5) + elapsed = time.monotonic() - started + assert not thread.is_alive() + server.stop() + assert result["error"].__cause__ is error + assert elapsed < 1.5, f"the failed send waited {elapsed:.2f} s" + + async def test_async_drain_has_one_budget(self, monkeypatch): + error = _fail_text_sends(monkeypatch, AsyncWebSocketSession, is_async=True) + + async def consume(client): + return [c async for c in client.tts.stream_websocket(_aiter("hello"))] + + async with aserving(chatter_script) as (server, client): + started = time.monotonic() + with pytest.raises(WebSocketError) as raised: + await asyncio.wait_for(consume(client), 5) + elapsed = time.monotonic() - started + server.stop() + assert raised.value.__cause__ is error + assert elapsed < 1.5, f"the failed send waited {elapsed:.2f} s" + + async def test_async_cancellation_keeps_the_original_as_cause(self): + error = asyncio.CancelledError("source cancelled") + + async def text_stream(): + yield "first" + raise error + + async def consume(client): + return [c async for c in client.tts.stream_websocket(text_stream())] + + async with aserving(waiting_script) as (server, client): + with pytest.raises(WebSocketError) as raised: + await asyncio.wait_for(consume(client), 3) + server.stop() + assert raised.value.__cause__ is error + + +class TestIterWebsocketAudioWithOnlySendFailed: + def test_does_not_wait_forever(self): + """send_failed alone also bounds the wait (no failure check given).""" + import queue + + from fishaudio.resources.realtime import iter_websocket_audio + + error = RuntimeError("send failed") + + class SilentSession: + def receive_bytes(self, timeout=None): + if timeout is None: + raise AssertionError("an unbounded receive") + time.sleep(timeout) + raise queue.Empty + + with pytest.raises(WebSocketError) as raised: + list(iter_websocket_audio(SilentSession(), send_failed=lambda: error)) + assert raised.value.__cause__ is error From ab5ed6bddb0b81a6702619388f65b9c603cc7eee Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 1 Dec 2026 08:42:15 -0800 Subject: [PATCH 24/29] refactor(tts): run the async stream's connection in a task of its own The async stream held the connection open across its yields and decided the outcome in three places (receiver task, sender task, generator). Now one session task owns the connection, the sender and the receive loop, catches errors inside the connection block, and hands audio and then _End(error) to the generator, which holds no connection itself. Same structure as the realtime speech-to-text session. - httpx-ws >= 0.9 no longer wraps the stream's errors in an ExceptionGroup (the unit suite passes on httpx-ws 0.10.0; 25 tests failed before). - Leaving the stream from another task (wait_for around __anext__, then aclose) or having it finalized by the event loop no longer trips httpx-ws's cancel scope or cancels the caller's task. - Rule 1 now says when a text_stream failure wins: when it comes before the outcome is decided. A cancellation of text_stream after the server's finish was read no longer fails a stream that had already ended. --- src/fishaudio/resources/realtime.py | 4 +- src/fishaudio/resources/tts.py | 254 +++++++++++++++------------- tests/unit/test_tts_language.py | 71 ++++++-- 3 files changed, 198 insertions(+), 131 deletions(-) diff --git a/src/fishaudio/resources/realtime.py b/src/fishaudio/resources/realtime.py index bf5cdef..0a759eb 100644 --- a/src/fishaudio/resources/realtime.py +++ b/src/fishaudio/resources/realtime.py @@ -11,7 +11,9 @@ from fishaudio.exceptions import WebSocketError # Which outcome a stream reports: -# 1. A failure of text_stream (the caller's input) wins, at once. +# 1. A failure of text_stream (the caller's input) that comes before the +# outcome is decided wins, at once: over audio still queued for the +# caller, and over anything the server says after it. # 2. Otherwise the server's word decides: a finish is success; an error event # or a close is WebSocketError. # 3. A failed send of ours decides only when the server stays silent: after diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index d73ab70..32b497b 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -47,7 +47,12 @@ ) from fishaudio.types.shared import warn_if_deprecated_model -from .asr_realtime import _POLL_SECONDS, _SENDER_CLEANUP_SECONDS, _retrieve_exception +from .asr_realtime import ( + _CLOSE_WRITE_SECONDS, + _POLL_SECONDS, + _SENDER_CLEANUP_SECONDS, + _retrieve_exception, +) from .realtime import aiter_websocket_audio, iter_websocket_audio _F = TypeVar("_F", bound=Callable[..., Any]) @@ -98,17 +103,18 @@ def _config_to_tts_request(config: TTSConfig, text: str) -> TTSRequest: logger = logging.getLogger(__name__) -# The end of the audio, handed from the WebSocket receiver to the caller. -_END = object() - -class _Raise: - """An error from the WebSocket receiver, to be raised to the caller.""" +class _End: + """Queue marker: the stream is over, normally or with an error.""" - def __init__(self, error: BaseException) -> None: + def __init__(self, error: Optional[BaseException] = None) -> None: self.error = error +# Queue marker: text_stream failed; the generator raises that at once. +_WAKE = object() + + def _close_text_stream(text_stream: object) -> None: """Close a generator text_stream. Other iterables are left alone. @@ -1280,65 +1286,86 @@ async def text_generator(): # Prepare WebSocket connection kwargs ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} - ws: AsyncWebSocketSession - async with aconnect_ws( + connect = functools.partial( + aconnect_ws, "/v1/tts/live", client=self._client.client, headers=self._client.get_headers({"model": model}), **ws_kwargs, - ) as ws: - # Set when the stream ends. Cancelling the sender is not enough - # on its own: a text_stream may catch the cancellation and - # yield again. - stopped = asyncio.Event() - # Why text_stream failed; raised to the caller in place of - # audio that will not come. - failure: list[BaseException] = [] - # Any other error of the sender (a send). The receiver raises it - # once the server has nothing more to say. + ) + # Set when the stream ends. Cancelling the sender is not enough on + # its own: a text_stream may catch the cancellation and yield again. + stopped = asyncio.Event() + # Why text_stream failed; raised to the caller in place of audio that + # will not come, and over anything already queued. + failure: list[BaseException] = [] + # Audio chunks, then _End, handed from the session task to this + # generator one at a time; _WAKE when text_stream fails. + chunks: asyncio.Queue[Any] = asyncio.Queue() + session = asyncio.create_task( + _run_tts_session( + connect, start_message, text_stream, chunks, failure, stopped + ) + ) + try: + while True: + item = await chunks.get() + chunks.task_done() + if failure: + raise failure[0] + if isinstance(item, _End): + if item.error is not None: + raise item.error + break + yield item + finally: + # Runs when the stream ends: it finished, it raised, or the + # caller closed it (aclose(), or the generator was finalized). A + # plain `break` does not close it. The connection lives in the + # session task, so this generator holds nothing that must be + # closed by the task that opened it; cancelling the session + # closes it. The wait is bounded like the session's own cleanup. + stopped.set() + if not session.done(): + session.cancel() + await asyncio.wait( + {session}, timeout=_SENDER_CLEANUP_SECONDS + _CLOSE_WRITE_SECONDS + ) + session.add_done_callback(_retrieve_exception) + + +async def _run_tts_session( + connect: Callable[[], Any], + start_message: bytes, + text_stream: Any, + chunks: "asyncio.Queue[Any]", + failure: list[BaseException], + stopped: asyncio.Event, +) -> None: + """Run one async TTS stream from connect to close, inside a single task. + + httpx-ws keeps an anyio task group open for the lifetime of the + connection. It must be exited by the task that entered it, and newer + httpx-ws wraps an exception that crosses it in an ExceptionGroup. An async + generator can promise neither (it may be finalized from another task), so + the connection lives here, errors are caught inside the connection block, + and the outcome is handed to the generator as _End(error). Same structure + as the realtime speech-to-text session. + """ + error: Optional[BaseException] = None + try: + ws: AsyncWebSocketSession + async with connect() as ws: + # Any other error of the sender (a send). The receive loop + # raises it once the server has nothing more to say. sender_error: list[BaseException] = [] - # Audio chunks, then _END (or the server's error), handed from - # the receiver task to this generator one at a time. - chunks: asyncio.Queue[Any] = asyncio.Queue() - - async def receiver() -> None: - try: - async for audio_chunk in aiter_websocket_audio( - ws, - send_failed=lambda: sender_error[0] if sender_error else None, - poll_seconds=_POLL_SECONDS, - ): - chunks.put_nowait(audio_chunk) - await chunks.join() # until it has been taken - chunks.put_nowait(_END) - except asyncio.CancelledError: - # This task is ours alone: it is cancelled when - # text_stream failed or the stream is being cleaned up. - # Any other cancellation must not end the audio early - # as if it were complete. - if failure or stopped.is_set(): - chunks.put_nowait(_END) - else: - chunks.put_nowait( - _Raise( - WebSocketError( - "Receiving audio was cancelled before " - "the stream ended" - ) - ) - ) - except BaseException as e: - chunks.put_nowait(_Raise(e)) - - receiver_task = asyncio.create_task(receiver()) - # Set once the sender is closing text_stream. sender_closing = asyncio.Event() - def text_stream_failed(error: BaseException) -> None: + def text_stream_failed(e: BaseException) -> None: if not stopped.is_set() and not failure: - failure.append(_from_text_stream(error)) - receiver_task.cancel() + failure.append(_from_text_stream(e)) + chunks.put_nowait(_WAKE) # the caller raises it at once async def sender() -> None: read_from = False # whether the SDK has read text_stream @@ -1364,18 +1391,18 @@ async def sender() -> None: item = await items.__anext__() if stopped.is_set(): return - # Normalize strings to TextEvent; an item - # that cannot be encoded is bad data from the - # caller, like one that is not text. + # Normalize strings to TextEvent; an item that + # cannot be encoded is bad data from the caller, + # like one that is not text. event = _normalize_to_event(item) message = ormsgpack.packb(event.model_dump()) except StopAsyncIteration: break except asyncio.CancelledError as e: - # The cleanup below cancels the sender only - # after setting stopped: one before that came - # from text_stream, and is reported with the - # original as its cause. + # The cleanup below cancels the sender only after + # setting stopped: one before that came from + # text_stream, and is reported with the original + # as its cause. if stopped.is_set(): raise text_stream_failed(e) @@ -1389,79 +1416,66 @@ async def sender() -> None: if not stopped.is_set(): await ws.send_bytes(ormsgpack.packb(CloseEvent().model_dump())) except Exception as e: - # A send error. Recorded before the cleanup below, - # which can take a while, so the receiver sees it at - # once. + # A send error. Recorded before the cleanup below, which + # can take a while, so the receive loop sees it at once. if not stopped.is_set(): sender_error.append(e) finally: # Inside the bounded wait below when the stream ends - # first, so a cleanup that does not finish cannot hold - # the connection open. The cleanup below does not - # cancel a sender that has got here: that would cut - # text_stream's own cleanup short. - # One the SDK never read from is left to the caller: - # its context and cleanup are the caller's. + # first, so a cleanup that does not finish cannot hold the + # connection open. The cleanup below does not cancel a + # sender that has got here: that would cut text_stream's + # own cleanup short. One the SDK never read from is left + # to the caller: its context and cleanup are the caller's. sender_closing.set() if read_from: await _aclose_text_stream(text_stream) def sender_done(task: asyncio.Task[None]) -> None: # Only the cleanup below cancels the sender, after setting - # stopped: a cancellation before that is not ours (for - # example text_stream awaited something that was cancelled). + # stopped: a cancellation before that is not ours. if task.cancelled(): text_stream_failed(asyncio.CancelledError()) sender_task = asyncio.create_task(sender()) sender_task.add_done_callback(sender_done) - try: - while True: - item = await chunks.get() - chunks.task_done() - # A failed text_stream wins over what was already - # queued: audio, or the server's own error. - if failure: - raise failure[0] - if item is _END: - break - if isinstance(item, _Raise): - raise item.error - yield item - + async for audio_chunk in aiter_websocket_audio( + ws, + send_failed=lambda: sender_error[0] if sender_error else None, + poll_seconds=_POLL_SECONDS, + ): + await chunks.put(audio_chunk) + await chunks.join() # until it has been taken # The server finished. It can do that while text_stream is # still waiting for input: do not wait for it then (it is - # cancelled below). A failed text_stream still fails the - # stream; a failed send does not, once the server has - # finished. - if failure: - raise failure[0] - if sender_task.done(): - # Checked here, not only in sender_done: that callback - # may not have run yet. - if sender_task.cancelled(): - raise _from_text_stream(asyncio.CancelledError()) - await sender_task # anything not recorded above + # cancelled below). A failed send does not fail the stream + # once the server has finished; a failed text_stream does, + # and the generator raises it. + stopped.set() + if not failure and sender_task.done() and sender_task.cancelled(): + # Checked here, not only in sender_done: that callback may + # not have run yet. + error = _from_text_stream(asyncio.CancelledError()) + 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: - # Runs when the stream ends: it finished, it raised (an - # error event, a disconnect, a failed text_stream), or the - # caller closed it with aclose(). A plain `break` does not - # close it. The sender is cancelled and closes text_stream; - # the wait is bounded, like the realtime speech-to-text - # session, so a text_stream whose cleanup never finishes - # cannot hold the connection open. asyncio.wait does not - # raise the tasks' errors, and a cancellation of the - # caller's own task still reaches the caller. stopped.set() - pending = { - task for task in (sender_task, receiver_task) if not task.done() - } - for task in pending: - if task is sender_task and sender_closing.is_set(): - continue # closing text_stream: waited for, not cut - task.cancel() - for task in (sender_task, receiver_task): - task.add_done_callback(_retrieve_exception) - if pending: - await asyncio.wait(pending, timeout=_SENDER_CLEANUP_SECONDS) + if not sender_task.done(): + if not sender_closing.is_set(): + sender_task.cancel() + # Bounded: a text_stream whose cleanup never finishes + # must not keep the connection open. + await asyncio.wait({sender_task}, timeout=_SENDER_CLEANUP_SECONDS) + sender_task.add_done_callback(_retrieve_exception) + # The close frame is a write like any other: bound it, and + # leaving the block closes the transport without it. + 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 Exception as e: + error = error or e # keep the stream's own error over one from closing + await chunks.put(_End(error)) diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index 53ab371..5602203 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -1091,9 +1091,10 @@ async def consume(client): await asyncio.wait_for(consume(client), 3) server.stop() - async def test_cancelled_just_before_the_end_is_seen(self): - """The sender is cancelled by text_stream and the stream then ends - before the sender's done-callback has run.""" + async def test_cancelled_after_the_finish_is_not_a_cancellation(self): + """text_stream is cancelled after the server's finish has been read: + the stream had already ended normally (the server decides), and no + bare CancelledError reaches the caller's task.""" awaited = asyncio.get_running_loop().create_future() async def text_stream(): @@ -1108,8 +1109,8 @@ async def steps(client): assert await stream.__anext__() == b"audio" await asyncio.sleep(0.2) # the finish is read and queued awaited.cancel() - await asyncio.sleep(0) # the sender ends; its callback is pending - with pytest.raises(WebSocketError, match="cancelled"): + await asyncio.sleep(0) + with pytest.raises(StopAsyncIteration): await stream.__anext__() finally: await stream.aclose() @@ -1542,8 +1543,9 @@ def script(conn): server.stop() assert result.get("error") is error - async def test_async_text_stream_failure_wins_over_a_queued_server_error(self): - """Rule 1, over what the receiver had already queued.""" + async def test_async_text_stream_failure_wins_over_queued_audio(self): + """Rule 1: a failure before the outcome is decided wins over audio + still queued, and over the server's error that comes after it.""" error = ValueError("source failed") sent = threading.Event() failed = asyncio.Event() @@ -1553,7 +1555,7 @@ async def text_stream(): yield "first" loop = asyncio.get_running_loop() assert await loop.run_in_executor(None, sent.wait, 5) - await asyncio.sleep(0.1) # the error event is queued by now + await asyncio.sleep(0.1) # the second chunk is queued by now raise error finally: failed.set() @@ -1561,14 +1563,17 @@ async def text_stream(): def script(conn): while conn.recv().get("event") != "text": pass - conn.send({"event": "audio", "audio": b"audio"}) + conn.send({"event": "audio", "audio": b"one"}) + conn.send({"event": "audio", "audio": b"two"}) conn.send({"event": "error", "error": "server failed"}) sent.set() conn.wait_gone() async def consume(client): stream = client.tts.stream_websocket(text_stream()) - assert await stream.__anext__() == b"audio" + # Holding the first chunk keeps the second queued and the + # server's error unread. + assert await stream.__anext__() == b"one" await failed.wait() await asyncio.sleep(0.05) return [c async for c in stream] @@ -1643,3 +1648,49 @@ def receive_bytes(self, timeout=None): with pytest.raises(WebSocketError) as raised: list(iter_websocket_audio(SilentSession(), send_failed=lambda: error)) assert raised.value.__cause__ is error + + +class TestConnectionLivesInItsOwnTask: + """The async stream's connection is opened and closed by one task of its + own, so leaving the stream from another task, or having it finalized by + the event loop, does not trip httpx-ws's task group.""" + + async def test_wait_for_around_anext_then_aclose(self): + async def text_stream(): + yield "first" + await asyncio.sleep(60) + + async with aserving(audio_then_wait_script) as (server, client): + stream = client.tts.stream_websocket(text_stream()) + # wait_for runs __anext__ in a task of its own on Python < 3.12. + assert await asyncio.wait_for(stream.__anext__(), 3) == b"audio" + await asyncio.wait_for(stream.aclose(), 3) + server.stop() + + async def test_error_in_the_loop_body_leaves_the_caller_running(self): + import gc + + loop = asyncio.get_running_loop() + loop_errors = [] + previous = loop.get_exception_handler() + loop.set_exception_handler(lambda _loop, context: loop_errors.append(context)) + + async def text_stream(): + yield "first" + await asyncio.sleep(60) + + async def caller(client): + with contextlib.suppress(OSError): + async for _chunk in client.tts.stream_websocket(text_stream()): + raise OSError("disk full") # no aclose: left to the loop + gc.collect() # the generator is finalized by the event loop + await asyncio.sleep(0.3) + return "still running" + + try: + async with aserving(audio_then_wait_script) as (server, client): + assert await asyncio.wait_for(caller(client), 5) == "still running" + server.stop() + finally: + loop.set_exception_handler(previous) + assert loop_errors == [] From 177295a7663f7a90d9193ff14a25995af43aff6c Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 1 Dec 2026 09:02:38 -0800 Subject: [PATCH 25/29] Test the outcome rules against a real broken write and paired faults Faults are now injected at the network stream under httpx-ws (a failing httpcore write), so the real httpx-ws and wsproto run. New tests try to refute each written rule, including two faults arriving in one wait. One of them found a hole: in the sync stream, a text_stream failure that came while the receive was waiting lost to a server error event that arrived after it. The receive loop now checks for that failure again once a message arrives (rule 1). Rule 3's comment now says what httpx-ws does on a broken write: it closes the connection and reads nothing more. --- src/fishaudio/resources/realtime.py | 13 +- tests/unit/test_tts_language.py | 482 ++++++++++++++++++++++++++++ 2 files changed, 492 insertions(+), 3 deletions(-) diff --git a/src/fishaudio/resources/realtime.py b/src/fishaudio/resources/realtime.py index 0a759eb..e1b767d 100644 --- a/src/fishaudio/resources/realtime.py +++ b/src/fishaudio/resources/realtime.py @@ -18,9 +18,11 @@ # or a close is WebSocketError. # 3. A failed send of ours decides only when the server stays silent: after # it, receiving may wait at most _DRAIN_SECONDS in all (time the caller -# spends on a chunk does not count), so messages that already arrived are -# still read. A send usually fails because the server is ending the -# connection, and what the server said is the better answer. +# spends on a chunk does not count), so messages httpx-ws has already +# received are still read. (On a broken write httpx-ws closes the +# connection and reads nothing more.) A send usually fails because the +# server is ending the connection, and what the server said is the better +# answer. # 4. A connection problem is WebSocketError, with the transport's error (a # failed send preferred) as its __cause__. # 5. An error while cleaning up is never the outcome. @@ -175,6 +177,11 @@ def iter_websocket_audio( raise error raise _ended(ended, _check(send_failed)) + # text_stream may have failed while this receive waited: that came + # first, so it decides over the message (rule 1). + error = _check(failure) + if error is not None: + raise error assert message is not None # None was handled above data = ormsgpack.unpackb(message) if _should_stop(data): diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index 5602203..f1271d8 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -1694,3 +1694,485 @@ async def caller(client): finally: loop.set_exception_handler(previous) assert loop_errors == [] + + +# Faults at the lowest layer: the network stream under httpx-ws. Everything +# above it (httpx-ws, wsproto, the SDK) is the real code. + + +def _break_writes(monkeypatch): + """Once the returned event is set, every write to the network stream + fails as a broken connection does (httpcore.WriteError).""" + import httpcore + from httpcore._backends.anyio import AnyIOStream + from httpcore._backends.sync import SyncStream + + broken = threading.Event() + real_sync_write = SyncStream.write + real_async_write = AnyIOStream.write + + def sync_write(self, buffer, timeout=None): + if broken.is_set(): + raise httpcore.WriteError("Broken pipe") + return real_sync_write(self, buffer, timeout) + + async def async_write(self, buffer, timeout=None): + if broken.is_set(): + raise httpcore.WriteError("Broken pipe") + return await real_async_write(self, buffer, timeout) + + monkeypatch.setattr(SyncStream, "write", sync_write) + monkeypatch.setattr(AnyIOStream, "write", async_write) + return broken + + +def _sync_text_breaking_writes(broken, before=None): + """Yields "hello" with writes broken, so its send fails. ``before`` runs + first (in the sender thread), before writes break.""" + yield "first" + if before is not None: + before() + broken.set() + yield "hello" + + +async def _async_text_breaking_writes(broken, before=None): + yield "first" + if before is not None: + await before() + broken.set() + yield "hello" + + +def _causes(error): + chain = [] + while error is not None: + chain.append(error) + error = error.__cause__ or error.__context__ + return chain + + +def _has_write_error(error): + import httpcore + + return any(isinstance(e, httpcore.WriteError) for e in _causes(error)) + + +def answer_first_text_script(then): + """Answers the first text with audio, then runs ``then(conn)``.""" + + def script(conn): + with contextlib.suppress(Exception): # the client may leave first + while conn.recv().get("event") != "text": + pass + conn.send({"event": "audio", "audio": b"audio"}) + then(conn) + + return script + + +class TestRealWriteFailure: + """Rules 3 and 4, with a real broken write under the real httpx-ws.""" + + def test_sync_silent_server(self, monkeypatch): + broken = _break_writes(monkeypatch) + script = answer_first_text_script(lambda conn: conn.wait_gone()) + with serving(script) as (server, client): + started = time.monotonic() + thread, result = _consume_in_thread( + client, _sync_text_breaking_writes(broken) + ) + thread.join(5) + assert not thread.is_alive(), "a broken write left the stream waiting" + server.stop() + assert time.monotonic() - started < 2 + assert isinstance(result.get("error"), WebSocketError) + assert _has_write_error(result["error"]) + + async def test_async_silent_server(self, monkeypatch): + broken = _break_writes(monkeypatch) + script = answer_first_text_script(lambda conn: conn.wait_gone()) + + async def consume(client): + return [ + c + async for c in client.tts.stream_websocket( + _async_text_breaking_writes(broken) + ) + ] + + async with aserving(script) as (server, client): + with pytest.raises(WebSocketError) as raised: + await asyncio.wait_for(consume(client), 5) + server.stop() + assert _has_write_error(raised.value) + + def test_sync_finish_in_the_same_wait_wins(self, monkeypatch): + """The server's finish has been received when the write fails: the + server's word decides (rule 2 over rule 3).""" + broken = _break_writes(monkeypatch) + sent = threading.Event() + + def then(conn): + conn.send({"event": "finish", "reason": "stop"}) + sent.set() + + def before(): + assert sent.wait(5) + time.sleep(0.1) # httpx-ws has received the finish by now + + with serving(answer_first_text_script(then)) as (server, client): + thread, result = _consume_in_thread( + client, _sync_text_breaking_writes(broken, before) + ) + thread.join(5) + assert not thread.is_alive() + server.stop() + assert result.get("audio") == b"audio", result.get("error") + + async def test_async_finish_in_the_same_wait_wins(self, monkeypatch): + broken = _break_writes(monkeypatch) + sent = threading.Event() + + def then(conn): + conn.send({"event": "finish", "reason": "stop"}) + sent.set() + + async def before(): + loop = asyncio.get_running_loop() + assert await loop.run_in_executor(None, sent.wait, 5) + await asyncio.sleep(0.1) # httpx-ws has received the finish by now + + async def consume(client): + return [ + c + async for c in client.tts.stream_websocket( + _async_text_breaking_writes(broken, before) + ) + ] + + async with aserving(answer_first_text_script(then)) as (server, client): + assert await asyncio.wait_for(consume(client), 5) == [b"audio"] + server.stop() + + def test_sync_drain_has_one_budget(self, monkeypatch): + """A broken write, while unknown events keep arriving every 20 ms.""" + broken = _break_writes(monkeypatch) + + def then(conn): + for _ in range(150): + conn.send({"event": "log"}) + time.sleep(0.02) + + with serving(answer_first_text_script(then)) as (server, client): + started = time.monotonic() + thread, result = _consume_in_thread( + client, _sync_text_breaking_writes(broken) + ) + thread.join(5) + elapsed = time.monotonic() - started + assert not thread.is_alive() + server.stop() + assert isinstance(result.get("error"), WebSocketError) + assert elapsed < 1.5, f"the broken write waited {elapsed:.2f} s" + + async def test_async_drain_has_one_budget(self, monkeypatch): + broken = _break_writes(monkeypatch) + + def then(conn): + for _ in range(150): + conn.send({"event": "log"}) + time.sleep(0.02) + + async def consume(client): + return [ + c + async for c in client.tts.stream_websocket( + _async_text_breaking_writes(broken) + ) + ] + + async with aserving(answer_first_text_script(then)) as (server, client): + started = time.monotonic() + with pytest.raises(WebSocketError): + await asyncio.wait_for(consume(client), 5) + elapsed = time.monotonic() - started + server.stop() + assert elapsed < 1.5, f"the broken write waited {elapsed:.2f} s" + + +class TestPairsOfFaultsInOneWait: + """Two faults arrive while the receive is waiting; the written rules say + which one decides.""" + + def test_sync_text_stream_fails_then_server_error_event(self, monkeypatch): + """Rule 1: the failure came first, so it wins over the server's error.""" + monkeypatch.setattr(tts_module, "_POLL_SECONDS", 30) + error = ValueError("source failed") + failed = threading.Event() + + def text_stream(): + yield "first" + time.sleep(0.2) # the receive is waiting by now + failed.set() + raise error + + def script(conn): + while conn.recv().get("event") != "text": + pass + assert failed.wait(5) + time.sleep(0.1) + conn.send({"event": "error", "error": "server failed"}) + conn.wait_gone() + + with serving(script) as (server, client): + thread, result = _consume_in_thread(client, text_stream()) + thread.join(5) + assert not thread.is_alive() + server.stop() + assert result.get("error") is error + + def test_sync_text_stream_fails_then_server_finish(self, monkeypatch): + """Rule 1: a failed text_stream is not taken for success.""" + monkeypatch.setattr(tts_module, "_POLL_SECONDS", 30) + error = ValueError("source failed") + failed = threading.Event() + + def text_stream(): + yield "first" + time.sleep(0.2) + failed.set() + raise error + + def script(conn): + while conn.recv().get("event") != "text": + pass + assert failed.wait(5) + time.sleep(0.1) + conn.send({"event": "finish", "reason": "stop"}) + conn.wait_gone() + + with serving(script) as (server, client): + thread, result = _consume_in_thread(client, text_stream()) + thread.join(5) + assert not thread.is_alive() + server.stop() + assert result.get("error") is error + + async def test_async_text_stream_fails_then_server_error_event(self): + error = ValueError("source failed") + failed = threading.Event() + + async def text_stream(): + yield "first" + await asyncio.sleep(0.2) + failed.set() + raise error + + def script(conn): + while conn.recv().get("event") != "text": + pass + assert failed.wait(5) + time.sleep(0.1) + conn.send({"event": "error", "error": "server failed"}) + conn.wait_gone() + + async def consume(client): + return [c async for c in client.tts.stream_websocket(text_stream())] + + async with aserving(script) as (server, client): + with pytest.raises(ValueError) as raised: + await asyncio.wait_for(consume(client), 5) + server.stop() + assert raised.value is error + + def test_sync_sender_stops_at_a_broken_write(self, monkeypatch): + """The sender stops at a failed send: text_stream is not read again.""" + broken = _break_writes(monkeypatch) + error = ValueError("source failed") + + def text_stream(): + yield "first" + broken.set() + yield "hello" # this send fails + raise error # never reached: the sender stops at the failed send + + script = answer_first_text_script(lambda conn: conn.wait_gone()) + with serving(script) as (server, client): + thread, result = _consume_in_thread(client, text_stream()) + thread.join(5) + assert not thread.is_alive() + server.stop() + # The sender stops at the failed send, so text_stream never fails: + # the broken write is the outcome. + assert isinstance(result.get("error"), WebSocketError) + assert _has_write_error(result["error"]) + + async def test_async_write_breaks_and_server_closes_in_one_wait(self, monkeypatch): + """Rule 2: the server's close decides; the broken write is its cause.""" + broken = _break_writes(monkeypatch) + closed = threading.Event() + + def then(conn): + conn.close(1011) + closed.set() + + async def before(): + loop = asyncio.get_running_loop() + assert await loop.run_in_executor(None, closed.wait, 5) + await asyncio.sleep(0.1) # httpx-ws has received the close + + async def consume(client): + return [ + c + async for c in client.tts.stream_websocket( + _async_text_breaking_writes(broken, before) + ) + ] + + async with aserving(answer_first_text_script(then)) as (server, client): + with pytest.raises(WebSocketError): + await asyncio.wait_for(consume(client), 5) + server.stop() + + +class TestCleanupNeverDecidesThroughTheStream: + async def test_async_cleanup_error_after_a_finish(self): + """Rule 5 through the public API: text_stream's cleanup raises after + the server has finished; the stream still succeeds.""" + + async def text_stream(): + try: + yield "first" + await asyncio.sleep(60) + finally: + raise _CleanupAbort + + async def consume(client): + return [c async for c in client.tts.stream_websocket(text_stream())] + + async with aserving(audio_then_finish_after_text_script) as (server, client): + assert await asyncio.wait_for(consume(client), 5) == [b"audio"] + server.stop() + + def test_sync_cleanup_error_after_a_finish(self): + """The SDK's close() of a generator suspended at a yield after the + finish runs its cleanup, which raises: logged, not the outcome.""" + finished = threading.Event() + cleaned = threading.Event() + + def text_stream(): + try: + yield "first" + assert finished.wait(5) + time.sleep(0.2) # the caller has read the finish by now + yield "second" # not sent: the stream is over; closed here + finally: + cleaned.set() + raise _CleanupAbort + + def script(conn): + while conn.recv().get("event") != "text": + pass + conn.send({"event": "audio", "audio": b"audio"}) + conn.send({"event": "finish", "reason": "stop"}) + finished.set() + + with serving(script) as (server, client): + thread, result = _consume_in_thread(client, text_stream()) + thread.join(5) + assert not thread.is_alive() + assert cleaned.wait(5) + server.stop() + assert result.get("audio") == b"audio", result.get("error") + + +def _all_answers_then_signal(sent): + """Sends three audio chunks and a finish as soon as the start arrives, + then sets ``sent``.""" + + def script(conn): + with contextlib.suppress(Exception): + conn.recv() # start + for _ in range(3): + conn.send({"event": "audio", "audio": b"audio"}) + conn.send({"event": "finish", "reason": "stop"}) + sent.set() + conn.wait_gone() + + return script + + +class TestSlowCallerAfterAFailedSend: + """Rule 3: time the caller spends on a chunk is not taken from the + waiting budget, so a finish already received still decides.""" + + def test_sync(self, monkeypatch): + _fail_text_sends(monkeypatch, WebSocketSession) + sent = threading.Event() + + def text_stream(): + assert sent.wait(5) + time.sleep(0.1) # let httpx-ws take the messages in + yield "hello" # this send fails + + with serving(_all_answers_then_signal(sent)) as (server, client): + chunks = [] + for chunk in client.tts.stream_websocket(text_stream()): + chunks.append(chunk) + time.sleep(0.1) # longer than the whole budget + server.stop() + assert chunks == [b"audio"] * 3 + + async def test_async(self, monkeypatch): + _fail_text_sends(monkeypatch, AsyncWebSocketSession, is_async=True) + sent = threading.Event() + + async def text_stream(): + loop = asyncio.get_running_loop() + assert await loop.run_in_executor(None, sent.wait, 5) + await asyncio.sleep(0.1) + yield "hello" + + async def consume(client): + chunks = [] + async for chunk in client.tts.stream_websocket(text_stream()): + chunks.append(chunk) + await asyncio.sleep(0.1) + return chunks + + async with aserving(_all_answers_then_signal(sent)) as (server, client): + assert await asyncio.wait_for(consume(client), 5) == [b"audio"] * 3 + server.stop() + + +class TestAsyncTextStreamFailsThenServerFinish: + async def test_failure_is_not_taken_for_success(self): + """Rule 1, async: the failure came first, so a later finish does not + turn it into success.""" + error = ValueError("source failed") + failed = threading.Event() + + async def text_stream(): + yield "first" + await asyncio.sleep(0.2) + failed.set() + raise error + + def script(conn): + with contextlib.suppress(Exception): + while conn.recv().get("event") != "text": + pass + assert failed.wait(5) + time.sleep(0.1) + conn.send({"event": "finish", "reason": "stop"}) + conn.wait_gone() + + async def consume(client): + return [c async for c in client.tts.stream_websocket(text_stream())] + + async with aserving(script) as (server, client): + with pytest.raises(ValueError) as raised: + await asyncio.wait_for(consume(client), 5) + server.stop() + assert raised.value is error From 09fc32b6eb6a9721a58e5b832f7dd11fcd17c140 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:37:01 -0800 Subject: [PATCH 26/29] style(tts): mark the deliberate broad catches for main's ruff rules Main now enables BLE001. Each broad catch in the TTS sender and session records the error and raises it to the consumer, as the same catches in asr_realtime.py are marked. Also drop an unused unpacked variable in a test (RUF059). --- src/fishaudio/resources/tts.py | 18 +++++++++--------- tests/unit/test_tts_language.py | 2 +- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index f4c3cd3..53167c0 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -728,7 +728,7 @@ def sender(): # CancelledError is not taken for success. try: items = iter(text_stream) - except BaseException as e: + except BaseException as e: # noqa: BLE001 - re-raised to the consumer failure.append(e) return while not stopped.is_set(): @@ -743,7 +743,7 @@ def sender(): ormsgpack.packb(CloseEvent().model_dump()) ) return - except BaseException as e: + except BaseException as e: # noqa: BLE001 - re-raised to the consumer if not stopped.is_set(): failure.append(e) return @@ -753,11 +753,11 @@ def sender(): # Normalize strings to TextEvent event = _normalize_to_event(item) message = ormsgpack.packb(event.model_dump()) - except BaseException as e: + except BaseException as e: # noqa: BLE001 - re-raised to the consumer failure.append(e) return ws.send_bytes(message) - except BaseException as e: + except BaseException as e: # noqa: BLE001 - re-raised to the consumer # A send error. Recorded before the cleanup below, # which can take a while, so the receive loop sees it # at once. @@ -1384,7 +1384,7 @@ async def sender() -> None: return try: items = text_stream.__aiter__() - except BaseException as e: + except BaseException as e: # noqa: BLE001 - re-raised to the consumer text_stream_failed(e) return while True: @@ -1410,7 +1410,7 @@ async def sender() -> None: raise text_stream_failed(e) return - except BaseException as e: + except BaseException as e: # noqa: BLE001 - re-raised to the consumer # BaseException too (GeneratorExit, ...): an # interrupted text_stream is not a success. text_stream_failed(e) @@ -1418,7 +1418,7 @@ async def sender() -> None: await ws.send_bytes(message) if not stopped.is_set(): await ws.send_bytes(ormsgpack.packb(CloseEvent().model_dump())) - except Exception as e: + except Exception as e: # noqa: BLE001 - re-raised to the consumer # A send error. Recorded before the cleanup below, which # can take a while, so the receive loop sees it at once. if not stopped.is_set(): @@ -1460,7 +1460,7 @@ def sender_done(task: asyncio.Task[None]) -> None: # Checked here, not only in sender_done: that callback may # not have run yet. error = _from_text_stream(asyncio.CancelledError()) - except Exception as e: + except Exception as e: # noqa: BLE001 - re-raised to the consumer # Leave the connection block without an exception: newer # httpx-ws wraps one that crosses it in an ExceptionGroup. error = e @@ -1479,6 +1479,6 @@ def sender_done(task: asyncio.Task[None]) -> None: 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 Exception as e: + except Exception as e: # noqa: BLE001 - re-raised to the consumer error = error or e # keep the stream's own error over one from closing await chunks.put(_End(error)) diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index f1271d8..1556bd6 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -1006,7 +1006,7 @@ def text_stream(): gen = text_stream() with serving(early_finish_script) as (server, client): - thread, result = _consume_in_thread(client, gen) + thread, _ = _consume_in_thread(client, gen) thread.join(3) assert not thread.is_alive() gate.set() From 5d9f592fb9167a0a5c85ceb59cd048d94361dc2c Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:58:28 -0800 Subject: [PATCH 27/29] fix(tts): async stream no longer waits forever when the session ends without an outcome The async generator waited on the chunk queue alone. A session task that ends by a BaseException that is not an Exception queues no outcome: a handshake whose request hook awaits a cancelled future, for example. The read then waited forever. It now waits for the queue and the session task together, as asr_realtime.py does, and raises what ended the session (CancelledError in that case, as before the session task). The async sender also checks that the stream is still running before each read of text_stream, as the sync sender does, so an aclose() that lands while a write is finishing no longer takes one more item from the caller's source. Tests: both cases fail before this change. The server scripts of the paired-fault tests now tolerate a client that has already left. --- src/fishaudio/resources/tts.py | 35 +++++++++- tests/unit/test_tts_language.py | 114 +++++++++++++++++++++++++++----- 2 files changed, 129 insertions(+), 20 deletions(-) diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 53167c0..d98b03f 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -3,6 +3,7 @@ import asyncio import base64 import binascii +import contextlib import functools import inspect import json @@ -1312,7 +1313,7 @@ async def text_generator(): ) try: while True: - item = await chunks.get() + item = await _next_chunk(chunks, session) chunks.task_done() if failure: raise failure[0] @@ -1337,6 +1338,34 @@ async def text_generator(): session.add_done_callback(_retrieve_exception) +async def _next_chunk( + chunks: "asyncio.Queue[Any]", session: "asyncio.Task[None]" +) -> Any: + """The next item the session task queued. + + The session queues _End last whenever it ends by itself. One ended by a + BaseException that is not an Exception (a handshake whose request hook + was cancelled, for example) queues nothing, so waiting on the queue alone + would wait forever: wait for the queue and the session together, as + asr_realtime.py does, and raise what ended the session. + """ + getter = asyncio.ensure_future(chunks.get()) + try: + await asyncio.wait({getter, session}, return_when=asyncio.FIRST_COMPLETED) + finally: + if not getter.done(): + getter.cancel() + if getter.done() and not getter.cancelled(): + return getter.result() + with contextlib.suppress(asyncio.QueueEmpty): + return chunks.get_nowait() + if session.cancelled(): + raise asyncio.CancelledError() + error = session.exception() + assert error is not None # a session that returns has queued _End + raise error + + async def _run_tts_session( connect: Callable[[], Any], start_message: bytes, @@ -1387,7 +1416,9 @@ async def sender() -> None: except BaseException as e: # noqa: BLE001 - re-raised to the consumer text_stream_failed(e) return - while True: + # Checked before each read as well as after it: once the + # stream is over, text_stream is not read again. + while not stopped.is_set(): # From the first read on, closing it is the SDK's. read_from = True try: diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index 1556bd6..aed75f1 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -1918,12 +1918,14 @@ def text_stream(): raise error def script(conn): - while conn.recv().get("event") != "text": - pass - assert failed.wait(5) - time.sleep(0.1) - conn.send({"event": "error", "error": "server failed"}) - conn.wait_gone() + # The client may have left by the time the server speaks. + with contextlib.suppress(Exception): + while conn.recv().get("event") != "text": + pass + assert failed.wait(5) + time.sleep(0.1) + conn.send({"event": "error", "error": "server failed"}) + conn.wait_gone() with serving(script) as (server, client): thread, result = _consume_in_thread(client, text_stream()) @@ -1945,12 +1947,14 @@ def text_stream(): raise error def script(conn): - while conn.recv().get("event") != "text": - pass - assert failed.wait(5) - time.sleep(0.1) - conn.send({"event": "finish", "reason": "stop"}) - conn.wait_gone() + # The client may have left by the time the server speaks. + with contextlib.suppress(Exception): + while conn.recv().get("event") != "text": + pass + assert failed.wait(5) + time.sleep(0.1) + conn.send({"event": "finish", "reason": "stop"}) + conn.wait_gone() with serving(script) as (server, client): thread, result = _consume_in_thread(client, text_stream()) @@ -1970,12 +1974,14 @@ async def text_stream(): raise error def script(conn): - while conn.recv().get("event") != "text": - pass - assert failed.wait(5) - time.sleep(0.1) - conn.send({"event": "error", "error": "server failed"}) - conn.wait_gone() + # The client may have left by the time the server speaks. + with contextlib.suppress(Exception): + while conn.recv().get("event") != "text": + pass + assert failed.wait(5) + time.sleep(0.1) + conn.send({"event": "error", "error": "server failed"}) + conn.wait_gone() async def consume(client): return [c async for c in client.tts.stream_websocket(text_stream())] @@ -2176,3 +2182,75 @@ async def consume(client): await asyncio.wait_for(consume(client), 5) server.stop() assert raised.value is error + + +class TestAsyncSessionEndsWithoutAnOutcome: + async def test_cancelled_handshake_is_raised_not_waited_on(self): + """A request hook that awaits a cancelled future (a shared token + refresh that was cancelled, say) ends the handshake with + CancelledError, which is not an Exception: the session task ends + without queueing an outcome. The read raises it, as before the + session task existed, instead of waiting forever.""" + + async def refresh_token(request): + future = asyncio.get_running_loop().create_future() + future.cancel() + await future + + async def text_stream(): + yield "hello" + + async with httpx.AsyncClient( + base_url="https://unit.test", event_hooks={"request": [refresh_token]} + ) as http: + client = AsyncFishAudio(api_key="test", httpx_client=http) + stream = client.tts.stream_websocket(text_stream()) + read = asyncio.ensure_future(stream.__anext__()) + done, _ = await asyncio.wait({read}, timeout=2) + if not done: + read.cancel() + await asyncio.gather(read, return_exceptions=True) + assert done, "the read waited for an outcome that will not come" + assert read.cancelled() + await stream.aclose() + + +class TestAsyncSenderAfterTheStreamEnds: + async def test_text_stream_is_not_read_again(self, monkeypatch): + """aclose() while a write has finished but the sender has not yet + resumed: the sender stops before its next read.""" + reads = [] + written = asyncio.Event() + release = asyncio.Event() + + async def text_stream(): + reads.append("first") + yield "first" + reads.append("second") + yield "second" + + real_send = AsyncWebSocketSession.send_bytes + + async def send(self, data): + await real_send(self, data) + if ormsgpack.unpackb(data).get("text") == "first": + written.set() + await release.wait() + + monkeypatch.setattr(AsyncWebSocketSession, "send_bytes", send) + + def script(conn): + with contextlib.suppress(Exception): + while conn.recv().get("event") != "text": + pass + conn.send({"event": "audio", "audio": b"audio"}) + conn.wait_gone() + + async with aserving(script) as (server, client): + stream = client.tts.stream_websocket(text_stream()) + assert await asyncio.wait_for(stream.__anext__(), 5) == b"audio" + await asyncio.wait_for(written.wait(), 5) + release.set() # the sender can resume, but has not yet + await stream.aclose() + server.stop() + assert reads == ["first"] From 45175071b8615b66065daef9cc703677648c3886 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:09:33 -0800 Subject: [PATCH 28/29] refactor(tts): narrow stream_websocket to language, the error event and ending This change now promises three things only: `language` reaches the request on all ten methods; a server error event raises WebSocketError with the server's message at once; and stream_websocket always ends. Removed, with their tests: the rules on which outcome wins when two faults meet (a failed send against a finish, send against receive, cleanup against outcome, sync against async), the drain budget, the cause preference, closing the caller's text_stream, and the stop flags that existed for those orderings. What remains for the stream to end: - the receive polls, and when the server is silent it raises the sender's error (a failed text_stream or send), since the server is then waiting for text that will not come; - the stream does not wait for the sender once the server has finished; - async: the connection runs in a task of its own (httpx-ws >= 0.9 wraps an exception that leaves its connection block in an ExceptionGroup), the generator waits on that task as well as its queue, and every cleanup wait is bounded. tests/unit/test_tts_language.py goes from 2256 lines and 155 tests to 299 lines and 47: one table for the ten methods, and seven tests that fail on main's code (or, for the cancelled handshake, on the session task without the second wait). --- src/fishaudio/resources/realtime.py | 199 +-- src/fishaudio/resources/tts.py | 382 +---- tests/unit/test_realtime.py | 6 - tests/unit/test_tts_language.py | 2283 ++------------------------- 4 files changed, 287 insertions(+), 2583 deletions(-) diff --git a/src/fishaudio/resources/realtime.py b/src/fishaudio/resources/realtime.py index e1b767d..44d2d21 100644 --- a/src/fishaudio/resources/realtime.py +++ b/src/fishaudio/resources/realtime.py @@ -1,78 +1,17 @@ """Real-time WebSocket streaming helpers.""" import queue -import time from collections.abc import AsyncIterator, Iterator from typing import Any, Callable, Optional import ormsgpack -from httpx_ws import HTTPXWSException, WebSocketDisconnect +from httpx_ws import WebSocketDisconnect from fishaudio.exceptions import WebSocketError -# Which outcome a stream reports: -# 1. A failure of text_stream (the caller's input) that comes before the -# outcome is decided wins, at once: over audio still queued for the -# caller, and over anything the server says after it. -# 2. Otherwise the server's word decides: a finish is success; an error event -# or a close is WebSocketError. -# 3. A failed send of ours decides only when the server stays silent: after -# it, receiving may wait at most _DRAIN_SECONDS in all (time the caller -# spends on a chunk does not count), so messages httpx-ws has already -# received are still read. (On a broken write httpx-ws closes the -# connection and reads nothing more.) A send usually fails because the -# server is ending the connection, and what the server said is the better -# answer. -# 4. A connection problem is WebSocketError, with the transport's error (a -# failed send preferred) as its __cause__. -# 5. An error while cleaning up is never the outcome. -_DRAIN_SECONDS = 0.05 - - ErrorCheck = Callable[[], Optional[BaseException]] -def _check(check: Optional[ErrorCheck]) -> Optional[BaseException]: - return check() if check is not None else None - - -def _connection_lost(cause: BaseException) -> WebSocketError: - error = WebSocketError("WebSocket connection lost") - error.__cause__ = cause - return error - - -def _ended( - error: HTTPXWSException, send_error: Optional[BaseException] -) -> WebSocketError: - """The error for a connection that ended without a finish (rules 2, 4).""" - if isinstance(error, WebSocketDisconnect): - ended = WebSocketError("WebSocket disconnected unexpectedly") - ended.__cause__ = send_error or error - return ended - return _connection_lost(send_error or error) - - -class _Drain: - """The waiting budget once a send has failed (rule 3).""" - - def __init__(self) -> None: - self.left: Optional[float] = None - - def timeout(self, send_error: Optional[BaseException], poll: float) -> float: - if send_error is not None and self.left is None: - self.left = _DRAIN_SECONDS - return poll if self.left is None else max(self.left, 0.001) - - def waited(self, seconds: float) -> None: - if self.left is not None: - self.left -= seconds - - @property - def spent(self) -> bool: - return self.left is not None and self.left <= 0 - - def _should_stop(data: dict[str, Any]) -> bool: """ Check if WebSocket event signals stream should stop. @@ -114,25 +53,21 @@ def _process_audio_event(data: dict[str, Any]) -> Optional[bytes]: def iter_websocket_audio( ws, - failure: Optional[ErrorCheck] = None, + sender_failed: Optional[ErrorCheck] = None, poll_seconds: float = 0.25, - send_failed: Optional[ErrorCheck] = None, ) -> Iterator[bytes]: """ Process WebSocket audio messages (sync). Receives messages from WebSocket, yields audio chunks, handles errors. - Unknown events are ignored and iteration continues. Which error is - raised follows the rules at the top of this module. + Unknown events are ignored and iteration continues. Args: ws: WebSocket connection from httpx_ws.connect_ws - failure: Returns why the text sender's input failed, or None. It is - checked before each receive and when the connection ends, and - raised as it is. - poll_seconds: How often a waiting receive checks ``failure`` and - ``send_failed``. - send_failed: Returns the error of a failed send, or None. + sender_failed: Returns the error of the text sender, or None. When + given, a receive waits at most ``poll_seconds``; if nothing has + arrived by then and the sender has failed, its error is raised. + poll_seconds: How long a receive waits before checking ``sender_failed``. Yields: Audio bytes @@ -140,75 +75,52 @@ def iter_websocket_audio( Raises: WebSocketError: On disconnect or error finish event """ - watching = failure is not None or send_failed is not None - drain = _Drain() while True: - error = _check(failure) - if error is not None: - raise error - send_error = _check(send_failed) try: - if not watching: + if sender_failed is None: message = ws.receive_bytes() else: - started = time.monotonic() try: - message = ws.receive_bytes( - timeout=drain.timeout(send_error, poll_seconds) - ) - except (queue.Empty, TimeoutError): # no message in time + message = ws.receive_bytes(timeout=poll_seconds) + except (queue.Empty, TimeoutError): # nothing within poll_seconds message = None - finally: - drain.waited(time.monotonic() - started) if message is None: - if send_error is not None and drain.spent: - raise _connection_lost(send_error) + # Raised outside the except block, so the exception is + # raised as it is. + error = sender_failed() + if error is not None: + raise error continue - except HTTPXWSException as e: - ended: Optional[HTTPXWSException] = e - else: - ended = None - if ended is not None: - # Checked now, not before the wait: either may have failed - # meanwhile. Raised outside the except block, so the caller's - # own exception is raised untouched. - error = _check(failure) - if error is not None: - raise error - raise _ended(ended, _check(send_failed)) - - # text_stream may have failed while this receive waited: that came - # first, so it decides over the message (rule 1). - error = _check(failure) - if error is not None: - raise error - assert message is not None # None was handled above - data = ormsgpack.unpackb(message) - if _should_stop(data): - break - audio = _process_audio_event(data) - if audio is not None: - yield audio + data = ormsgpack.unpackb(message) + + if _should_stop(data): + break + + audio = _process_audio_event(data) + if audio is not None: + yield audio + + except WebSocketDisconnect: + raise WebSocketError("WebSocket disconnected unexpectedly") async def aiter_websocket_audio( ws, - send_failed: Optional[ErrorCheck] = None, + sender_failed: Optional[ErrorCheck] = None, poll_seconds: float = 0.25, ) -> AsyncIterator[bytes]: """ Process WebSocket audio messages (async). Receives messages from WebSocket, yields audio chunks, handles errors. - Unknown events are ignored and iteration continues. Which error is - raised follows the rules at the top of this module (a failure of the - caller's input is handled by the caller of this function). + Unknown events are ignored and iteration continues. Args: ws: WebSocket connection from httpx_ws.aconnect_ws - send_failed: Returns the error of a failed send, or None. When given, - a receive waits at most ``poll_seconds`` before checking it again. - poll_seconds: How often a waiting receive checks ``send_failed``. + sender_failed: Returns the error of the text sender, or None. When + given, a receive waits at most ``poll_seconds``; if nothing has + arrived by then and the sender has failed, its error is raised. + poll_seconds: How long a receive waits before checking ``sender_failed``. Yields: Audio bytes @@ -216,39 +128,30 @@ async def aiter_websocket_audio( Raises: WebSocketError: On disconnect or error finish event """ - drain = _Drain() while True: - send_error = _check(send_failed) try: - if send_failed is None: + if sender_failed is None: message = await ws.receive_bytes() else: - started = time.monotonic() try: - message = await ws.receive_bytes( - timeout=drain.timeout(send_error, poll_seconds) - ) - except (queue.Empty, TimeoutError): # no message in time + message = await ws.receive_bytes(timeout=poll_seconds) + except (queue.Empty, TimeoutError): # nothing within poll_seconds message = None - finally: - drain.waited(time.monotonic() - started) if message is None: - if send_error is not None and drain.spent: - raise _connection_lost(send_error) + # Raised outside the except block, so the exception is + # raised as it is. + error = sender_failed() + if error is not None: + raise error continue - except HTTPXWSException as e: - ended: Optional[HTTPXWSException] = e - else: - ended = None - if ended is not None: - # Checked now, not before the wait: a send may have failed - # meanwhile. - raise _ended(ended, _check(send_failed)) - - assert message is not None # None was handled above - data = ormsgpack.unpackb(message) - if _should_stop(data): - break - audio = _process_audio_event(data) - if audio is not None: - yield audio + data = ormsgpack.unpackb(message) + + if _should_stop(data): + break + + audio = _process_audio_event(data) + if audio is not None: + yield audio + + except WebSocketDisconnect: + raise WebSocketError("WebSocket disconnected unexpectedly") diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index d98b03f..7f3e828 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -7,10 +7,9 @@ import functools import inspect import json -import logging import threading from collections.abc import AsyncIterable, Iterable, Iterator -from concurrent.futures import Future, ThreadPoolExecutor +from concurrent.futures import ThreadPoolExecutor from typing import Any, Callable, Optional, TypeVar, Union, cast import ormsgpack @@ -103,9 +102,6 @@ def _config_to_tts_request(config: TTSConfig, text: str) -> TTSRequest: ) -logger = logging.getLogger(__name__) - - class _End: """Queue marker: the stream is over, normally or with an error.""" @@ -113,53 +109,6 @@ def __init__(self, error: Optional[BaseException] = None) -> None: self.error = error -# Queue marker: text_stream failed; the generator raises that at once. -_WAKE = object() - - -def _close_text_stream(text_stream: object) -> None: - """Close a generator text_stream. Other iterables are left alone. - - Runs as cleanup, on the sender's own worker thread: whatever the close - raises is logged, never raised. It is not how the stream ended, and - raised in a worker thread it would reach no one. - """ - if inspect.isgenerator(text_stream): - try: - text_stream.close() - except BaseException: - logger.debug("Closing text_stream failed", exc_info=True) - - -def _from_text_stream(error: BaseException) -> BaseException: - """The error to raise to the caller for one from the async text_stream. - - A cancellation of text_stream is reported as WebSocketError: raised as it - is, it would look like a cancellation of the caller's own task. - """ - if isinstance(error, asyncio.CancelledError): - reported = WebSocketError("text_stream was cancelled before the stream ended") - reported.__cause__ = error - return reported - return error - - -async def _aclose_text_stream(text_stream: object) -> None: - """Close an async-generator text_stream. Other iterables are left alone. - - Runs as cleanup, in the SDK's own sender task: what the close raises, - a cancellation included, is logged, never raised. It is not how the - stream ended. KeyboardInterrupt and SystemExit still propagate. - """ - if inspect.isasyncgen(text_stream): - try: - await text_stream.aclose() - except (KeyboardInterrupt, SystemExit): - raise - except BaseException: - logger.debug("Closing text_stream failed", exc_info=True) - - def _normalize_to_event( item: Union[str, TextEvent, FlushEvent], ) -> Union[TextEvent, FlushEvent]: @@ -574,19 +523,8 @@ def stream_websocket( Perfect for conversational AI, live captioning, and streaming applications. Args: - text_stream: Iterator of text chunks to stream. If it raises, - the stream ends and raises that same exception. If the stream - ends first (the server finishes, an error, or you close it), - the SDK stops reading it: a read already waiting completes in - the worker thread and its text is not sent. When the stream - ends, however it ends, the SDK closes a generator text_stream - it has started reading (`close()`) on the worker thread that - read it, once its last read has returned, so its `finally` - blocks run there; the stream does not wait for that. One it - never read (the connection failed first) and other iterables - are not closed. - Like a read that never returns, cleanup that never finishes - keeps the worker thread, and with it the interpreter's exit. + text_stream: Iterator of text chunks to stream. If it raises, the + stream raises that exception. reference_id: Voice reference ID (overrides config.reference_id if provided) references: Reference audio samples (overrides config.references if provided) format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided) @@ -603,9 +541,11 @@ def stream_websocket( See WebSocketOptions class for available parameters. Returns: - Iterator of audio bytes. To stop reading early, close it (for - example with `contextlib.closing`): a plain `break` leaves the - connection open and the text sender running until it is closed. + Iterator of audio bytes + + Raises: + WebSocketError: When the server reports an error (for example an + invalid language tag) or the connection closes unexpectedly. Example: ```python @@ -691,7 +631,7 @@ def text_generator(): tts_request.language = language # Encoded before connecting: a request that cannot be encoded raises - # here instead of leaving the server waiting for it. + # here, before anything is sent. start_message = ormsgpack.packb(StartEvent(request=tts_request).model_dump()) # Prepare WebSocket connection kwargs @@ -699,7 +639,6 @@ def text_generator(): headers = _handshake_headers(self._client, model, ws_options) executor = ThreadPoolExecutor(max_workers=max_workers) - sender_future: Optional[Future[None]] = None try: ws: WebSocketSession @@ -710,104 +649,41 @@ def text_generator(): **ws_kwargs, ) as ws: stopped = threading.Event() - # Why text_stream failed, set by the sender; the receive loop - # raises it instead of waiting for audio that will not come. - failure: list[BaseException] = [] - # Any other error of the sender (a send). The receive loop - # raises it once the server has nothing more to say. sender_error: list[BaseException] = [] - read_from = [False] # whether the SDK has read text_stream def sender(): try: ws.send_bytes(start_message) - # Check before each read as well as after it: once the - # stream is over, text_stream is not read again. - # Errors of text_stream itself, and of turning its - # items into messages (bad data from the caller), end - # the stream: BaseException too, so that one such as - # CancelledError is not taken for success. - try: - items = iter(text_stream) - except BaseException as e: # noqa: BLE001 - re-raised to the consumer - failure.append(e) - return - while not stopped.is_set(): - # From the first read on, closing it is the SDK's. - read_from[0] = True - try: - item = next(items) - except StopIteration: - # text_stream can end after the stream has. - if not stopped.is_set(): - ws.send_bytes( - ormsgpack.packb(CloseEvent().model_dump()) - ) - return - except BaseException as e: # noqa: BLE001 - re-raised to the consumer - if not stopped.is_set(): - failure.append(e) - return + # Normalize strings to TextEvent + for item in text_stream: if stopped.is_set(): return - try: - # Normalize strings to TextEvent - event = _normalize_to_event(item) - message = ormsgpack.packb(event.model_dump()) - except BaseException as e: # noqa: BLE001 - re-raised to the consumer - failure.append(e) - return - ws.send_bytes(message) - except BaseException as e: # noqa: BLE001 - re-raised to the consumer - # A send error. Recorded before the cleanup below, - # which can take a while, so the receive loop sees it - # at once. + event = _normalize_to_event(item) + ws.send_bytes(ormsgpack.packb(event.model_dump())) if not stopped.is_set(): - sender_error.append(e) - finally: - # By this thread, which ran it: a generator cannot be - # closed from another thread while it is running, and - # what it holds may belong to the thread that made it. - # One the SDK never read from is left to the caller. - if read_from[0]: - _close_text_stream(text_stream) + ws.send_bytes(ormsgpack.packb(CloseEvent().model_dump())) + except BaseException as e: # noqa: BLE001 - raised to the consumer + sender_error.append(e) - sender_future = executor.submit(sender) + executor.submit(sender) try: - # Process incoming audio messages + # Process incoming audio messages. If the sender fails, the + # server waits for text that will not come: the receive + # raises the sender's error once the server is silent. yield from iter_websocket_audio( ws, - failure=lambda: failure[0] if failure else None, + sender_failed=lambda: sender_error[0] if sender_error else None, poll_seconds=_POLL_SECONDS, - send_failed=lambda: sender_error[0] if sender_error else None, ) - - # The server finished. It can do that while text_stream is - # still waiting for input: do not wait for it then. A - # failed text_stream still fails the stream; a failed send - # does not, once the server has finished. - stopped.set() - if failure: - raise failure[0] finally: - # Runs when the stream ends: it finished, it raised (an error - # event, a disconnect, a failed text_stream), or the caller - # closed it. A plain `break` does not close it. The sender - # then stops before its next read or send, and closes - # text_stream. A thread cannot be interrupted while - # text_stream itself blocks: it returns once text_stream - # yields or ends, without sending anything more. The stream - # does not wait for that. + # The stream does not wait for the sender: once the server + # has finished, text_stream may still be waiting for input. stopped.set() # 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) finally: - # A sender that never ran has not read text_stream: it stays the - # caller's, untouched. - if sender_future is not None: - sender_future.cancel() executor.shutdown(wait=False) @@ -1168,17 +1044,8 @@ async def stream_websocket( Perfect for conversational AI, live captioning, and streaming applications. Args: - text_stream: Async iterator of text chunks to stream. If it - raises, the stream ends and raises that same exception; if it - is cancelled, the stream raises WebSocketError instead, so the - cancellation is not mistaken for one of your task. If the - stream ends first (the server finishes, an error, or you close - it), the SDK stops reading it and cancels the task sending it; - nothing more is sent. When the stream ends, however it ends, - the SDK closes an async-generator text_stream it has started - reading (`aclose()`), so its `finally` blocks run; it waits - for that at most one second. One it never read (the connection - failed first) and other async iterables are not closed. + text_stream: Async iterator of text chunks to stream. If it raises, + the stream raises that exception. reference_id: Voice reference ID (overrides config.reference_id if provided) references: Reference audio samples (overrides config.references if provided) format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided) @@ -1194,10 +1061,11 @@ async def stream_websocket( See WebSocketOptions class for available parameters. Returns: - Async iterator of audio bytes. To stop reading early, close it with - `await stream.aclose()` (or `contextlib.aclosing` on Python 3.10+): - a plain `break` leaves the connection open and the text sender - running until it is closed. + Async iterator of audio bytes + + Raises: + WebSocketError: When the server reports an error (for example an + invalid language tag) or the connection closes unexpectedly. Example: ```python @@ -1283,13 +1151,12 @@ async def text_generator(): tts_request.language = language # Encoded before connecting: a request that cannot be encoded raises - # here instead of leaving the server waiting for it. + # here, before anything is sent. start_message = ormsgpack.packb(StartEvent(request=tts_request).model_dump()) # Prepare WebSocket connection kwargs ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} headers = _handshake_headers(self._client, model, ws_options) - connect = functools.partial( aconnect_ws, "/v1/tts/live", @@ -1297,39 +1164,26 @@ async def text_generator(): headers=headers, **ws_kwargs, ) - # Set when the stream ends. Cancelling the sender is not enough on - # its own: a text_stream may catch the cancellation and yield again. - stopped = asyncio.Event() - # Why text_stream failed; raised to the caller in place of audio that - # will not come, and over anything already queued. - failure: list[BaseException] = [] - # Audio chunks, then _End, handed from the session task to this - # generator one at a time; _WAKE when text_stream fails. - chunks: asyncio.Queue[Any] = asyncio.Queue() + # The connection lives in a task of its own, which hands over audio + # and then _End. httpx-ws >= 0.9 wraps an exception that leaves its + # connection block in an ExceptionGroup, and its cancel scope must + # be left by the task that entered it; neither then reaches the + # caller. + chunks: asyncio.Queue[Any] = asyncio.Queue(maxsize=1) session = asyncio.create_task( - _run_tts_session( - connect, start_message, text_stream, chunks, failure, stopped - ) + _run_tts_session(connect, start_message, text_stream, chunks) ) try: while True: item = await _next_chunk(chunks, session) - chunks.task_done() - if failure: - raise failure[0] if isinstance(item, _End): if item.error is not None: raise item.error - break + return yield item finally: - # Runs when the stream ends: it finished, it raised, or the - # caller closed it (aclose(), or the generator was finalized). A - # plain `break` does not close it. The connection lives in the - # session task, so this generator holds nothing that must be - # closed by the task that opened it; cancelling the session - # closes it. The wait is bounded like the session's own cleanup. - stopped.set() + # The stream ended or the caller closed it: closing the + # connection is the session's; wait for that within a bound. if not session.done(): session.cancel() await asyncio.wait( @@ -1366,150 +1220,60 @@ async def _next_chunk( raise error +def _sender_failed(sender: "asyncio.Task[None]") -> Optional[BaseException]: + if not sender.done(): + return None + if sender.cancelled(): + # Only text_stream can cancel the sender while audio is received. + return WebSocketError("text_stream was cancelled") + return sender.exception() + + async def _run_tts_session( connect: Callable[[], Any], start_message: bytes, text_stream: Any, chunks: "asyncio.Queue[Any]", - failure: list[BaseException], - stopped: asyncio.Event, ) -> None: - """Run one async TTS stream from connect to close, inside a single task. - - httpx-ws keeps an anyio task group open for the lifetime of the - connection. It must be exited by the task that entered it, and newer - httpx-ws wraps an exception that crosses it in an ExceptionGroup. An async - generator can promise neither (it may be finalized from another task), so - the connection lives here, errors are caught inside the connection block, - and the outcome is handed to the generator as _End(error). Same structure - as the realtime speech-to-text session. - """ + """Run the connection, sender and receive loop; queue audio, then _End.""" error: Optional[BaseException] = None try: ws: AsyncWebSocketSession async with connect() as ws: - # Any other error of the sender (a send). The receive loop - # raises it once the server has nothing more to say. - sender_error: list[BaseException] = [] - # Set once the sender is closing text_stream. - sender_closing = asyncio.Event() - - def text_stream_failed(e: BaseException) -> None: - if not stopped.is_set() and not failure: - failure.append(_from_text_stream(e)) - chunks.put_nowait(_WAKE) # the caller raises it at once - - async def sender() -> None: - read_from = False # whether the SDK has read text_stream - try: - await ws.send_bytes(start_message) - if not hasattr(type(text_stream), "__aiter__"): - text_stream_failed( - TypeError( - "text_stream must be an async iterable, got " - f"{type(text_stream).__name__}" - ) - ) - return - try: - items = text_stream.__aiter__() - except BaseException as e: # noqa: BLE001 - re-raised to the consumer - text_stream_failed(e) - return - # Checked before each read as well as after it: once the - # stream is over, text_stream is not read again. - while not stopped.is_set(): - # From the first read on, closing it is the SDK's. - read_from = True - try: - item = await items.__anext__() - if stopped.is_set(): - return - # Normalize strings to TextEvent; an item that - # cannot be encoded is bad data from the caller, - # like one that is not text. - event = _normalize_to_event(item) - message = ormsgpack.packb(event.model_dump()) - except StopAsyncIteration: - break - except asyncio.CancelledError as e: - # The cleanup below cancels the sender only after - # setting stopped: one before that came from - # text_stream, and is reported with the original - # as its cause. - if stopped.is_set(): - raise - text_stream_failed(e) - return - except BaseException as e: # noqa: BLE001 - re-raised to the consumer - # BaseException too (GeneratorExit, ...): an - # interrupted text_stream is not a success. - text_stream_failed(e) - return - await ws.send_bytes(message) - if not stopped.is_set(): - await ws.send_bytes(ormsgpack.packb(CloseEvent().model_dump())) - except Exception as e: # noqa: BLE001 - re-raised to the consumer - # A send error. Recorded before the cleanup below, which - # can take a while, so the receive loop sees it at once. - if not stopped.is_set(): - sender_error.append(e) - finally: - # Inside the bounded wait below when the stream ends - # first, so a cleanup that does not finish cannot hold the - # connection open. The cleanup below does not cancel a - # sender that has got here: that would cut text_stream's - # own cleanup short. One the SDK never read from is left - # to the caller: its context and cleanup are the caller's. - sender_closing.set() - if read_from: - await _aclose_text_stream(text_stream) - - def sender_done(task: asyncio.Task[None]) -> None: - # Only the cleanup below cancels the sender, after setting - # stopped: a cancellation before that is not ours. - if task.cancelled(): - text_stream_failed(asyncio.CancelledError()) + + async def sender(): + await ws.send_bytes(start_message) + # Normalize strings to TextEvent + async for item in text_stream: + event = _normalize_to_event(item) + await ws.send_bytes(ormsgpack.packb(event.model_dump())) + await ws.send_bytes(ormsgpack.packb(CloseEvent().model_dump())) sender_task = asyncio.create_task(sender()) - sender_task.add_done_callback(sender_done) try: - async for audio_chunk in aiter_websocket_audio( + # If the sender fails, the server waits for text that will not + # come: the receive raises the sender's error once the server + # is silent. + async for audio in aiter_websocket_audio( ws, - send_failed=lambda: sender_error[0] if sender_error else None, + sender_failed=lambda: _sender_failed(sender_task), poll_seconds=_POLL_SECONDS, ): - await chunks.put(audio_chunk) - await chunks.join() # until it has been taken - # The server finished. It can do that while text_stream is - # still waiting for input: do not wait for it then (it is - # cancelled below). A failed send does not fail the stream - # once the server has finished; a failed text_stream does, - # and the generator raises it. - stopped.set() - if not failure and sender_task.done() and sender_task.cancelled(): - # Checked here, not only in sender_done: that callback may - # not have run yet. - error = _from_text_stream(asyncio.CancelledError()) + await chunks.put(audio) except Exception as e: # noqa: BLE001 - re-raised to the consumer - # Leave the connection block without an exception: newer - # httpx-ws wraps one that crosses it in an ExceptionGroup. + # Not raised here: newer httpx-ws wraps an exception that + # leaves the connection block in an ExceptionGroup. error = e finally: - stopped.set() + # Once the server has finished, text_stream may still be + # waiting for input: stop the sender, within a bound. if not sender_task.done(): - if not sender_closing.is_set(): - sender_task.cancel() - # Bounded: a text_stream whose cleanup never finishes - # must not keep the connection open. + sender_task.cancel() await asyncio.wait({sender_task}, timeout=_SENDER_CLEANUP_SECONDS) sender_task.add_done_callback(_retrieve_exception) - # The close frame is a write like any other: bound it, and - # leaving the block closes the transport without it. - try: + # A peer that stops reading must not hold the close. + with contextlib.suppress(Exception): 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 Exception as e: # noqa: BLE001 - re-raised to the consumer - error = error or e # keep the stream's own error over one from closing + error = error or e await chunks.put(_End(error)) diff --git a/tests/unit/test_realtime.py b/tests/unit/test_realtime.py index 54e662c..446ae3c 100644 --- a/tests/unit/test_realtime.py +++ b/tests/unit/test_realtime.py @@ -60,12 +60,6 @@ def test_finish_event_with_error_raises_exception(self): with pytest.raises(WebSocketError, match="WebSocket stream ended with error"): _process_audio_event(data) - def test_error_event_raises_with_server_message(self): - """An error event (sent when the server rejects the start event) raises.""" - data = {"event": "error", "error": 'Invalid language "en us".'} - with pytest.raises(WebSocketError, match='Invalid language "en us"'): - _process_audio_event(data) - def test_finish_event_with_stop_returns_none(self): """Test that finish event with stop reason returns None.""" data = {"event": "finish", "reason": "stop"} diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index aed75f1..d1a3c3f 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -1,41 +1,38 @@ -"""Tests for the text-to-speech `language` option on every entry point. +"""Tests for the text-to-speech `language` option and for how stream_websocket ends. -HTTP requests go through real httpx transports and WebSocket sessions through a +HTTP requests go through httpx.MockTransport and WebSocket sessions through a local server (see realtime_server.py), so the assertions read the bytes the SDK -actually sends. An unset language must not appear on the wire at all, not even -as nil. +actually sends. """ import asyncio import contextlib -import inspect import threading -import time import httpx import ormsgpack import pytest -from httpx_ws import AsyncWebSocketSession, WebSocketSession from fishaudio import AsyncFishAudio, FishAudio, TTSConfig -from fishaudio.core import AsyncClientWrapper, ClientWrapper from fishaudio.exceptions import WebSocketError from fishaudio.resources import tts as tts_module -from fishaudio.resources.tts import AsyncTTSClient, TTSClient -from fishaudio.types import StartEvent, TTSRequest from .realtime_server import RealtimeServer BASE_URL = "https://api.test.fish.audio" - SSE_BODY = ( b'event: message\ndata: {"audio_base64": "", "content": "", "alignment": null}\n\n' ) - -# (call kwargs, expected "language" in the body; None means absent) +METHODS = [ + "convert", + "stream", + "convert_with_timestamps", + "stream_with_timestamps", + "stream_websocket", +] +# (call kwargs, the "language" sent; None means not sent at all) CASES = [ pytest.param({}, None, id="unset"), - pytest.param({"config": TTSConfig()}, None, id="default-config"), pytest.param({"language": "es-MX"}, "es-MX", id="parameter"), pytest.param({"config": TTSConfig(language="zh-CN")}, "zh-CN", id="config"), pytest.param( @@ -43,157 +40,39 @@ "es-MX", id="parameter-overrides-config", ), - pytest.param({"language": "ES_mx"}, "ES_mx", id="sent-as-given"), - pytest.param({"language": ""}, "", id="empty-string-sent-as-given"), ] -def _check(body, expected): - if expected is None: - assert "language" not in body - else: - assert body["language"] == expected - - -def _capture(seen, response_body): - def handler(request): - seen.append(request) - return httpx.Response(200, content=response_body) - - return handler - - -def _sync_tts(seen, response_body=b"audio"): - transport = httpx.MockTransport(_capture(seen, response_body)) - http = httpx.Client(base_url=BASE_URL, transport=transport) - return TTSClient(ClientWrapper(api_key="test", httpx_client=http)) - - -def _async_tts(seen, response_body=b"audio"): - transport = httpx.MockTransport(_capture(seen, response_body)) - http = httpx.AsyncClient(base_url=BASE_URL, transport=transport) - return AsyncTTSClient(AsyncClientWrapper(api_key="test", httpx_client=http)) - - -class TestTypes: - def test_config_defaults_to_unset(self): - assert TTSConfig().language is None - - def test_request_omits_unset_language_in_every_dump(self): - request = TTSRequest(text="hi") - assert "language" not in request.model_dump() - assert "language" not in request.model_dump(exclude_none=True) - assert "language" not in StartEvent(request=request).model_dump()["request"] - - def test_request_keeps_a_set_language(self): - request = TTSRequest(text="hi", language="es-MX") - assert request.model_dump()["language"] == "es-MX" - assert StartEvent(request=request).model_dump()["request"]["language"] == ( - "es-MX" - ) - - def test_serialization_schema_keeps_every_field(self): - # Dropping an unset language must not change the published schema: - # every field stays described and text stays required. - schema = TTSRequest.model_json_schema(mode="serialization") - assert set(schema["properties"]) == set(TTSRequest.model_fields) - assert schema["required"] == ["text"] - assert schema["properties"]["language"]["anyOf"] == [ - {"type": "string"}, - {"type": "null"}, - ] - nested = StartEvent.model_json_schema(mode="serialization")["$defs"] - assert set(nested["TTSRequest"]["properties"]) == set(TTSRequest.model_fields) - - def test_other_none_fields_are_unchanged(self): - # Only language is dropped when unset; the start event keeps sending the - # other optional fields as nil, as it did before. - dumped = StartEvent(request=TTSRequest(text="")).model_dump()["request"] - assert dumped["reference_id"] is None - assert dumped["sample_rate"] is None - assert dumped["prosody"] is None - - -class TestHTTP: - @pytest.mark.parametrize("kwargs, expected", CASES) - def test_convert(self, kwargs, expected): - seen = [] - _sync_tts(seen).convert(text="La entrada cuesta $300.", **kwargs) - assert seen[0].url.path == "/v1/tts" - _check(ormsgpack.unpackb(seen[0].content), expected) - - @pytest.mark.parametrize("kwargs, expected", CASES) - def test_stream(self, kwargs, expected): - seen = [] - _sync_tts(seen).stream(text="Hi", **kwargs).collect() - _check(ormsgpack.unpackb(seen[0].content), expected) - - @pytest.mark.parametrize("kwargs, expected", CASES) - def test_convert_with_timestamps(self, kwargs, expected): - seen = [] - _sync_tts(seen, SSE_BODY).convert_with_timestamps(text="Hi", **kwargs) - assert seen[0].url.path == "/v1/tts/stream/with-timestamp" - _check(ormsgpack.unpackb(seen[0].content), expected) - - @pytest.mark.parametrize("kwargs, expected", CASES) - def test_stream_with_timestamps(self, kwargs, expected): - seen = [] - _sync_tts(seen, SSE_BODY).stream_with_timestamps(text="Hi", **kwargs).close() - _check(ormsgpack.unpackb(seen[0].content), expected) - - @pytest.mark.parametrize("kwargs, expected", CASES) - async def test_async_convert(self, kwargs, expected): - seen = [] - await _async_tts(seen).convert(text="Hi", **kwargs) - _check(ormsgpack.unpackb(seen[0].content), expected) - - @pytest.mark.parametrize("kwargs, expected", CASES) - async def test_async_stream(self, kwargs, expected): - seen = [] - stream = await _async_tts(seen).stream(text="Hi", **kwargs) - await stream.collect() - _check(ormsgpack.unpackb(seen[0].content), expected) - - @pytest.mark.parametrize("kwargs, expected", CASES) - async def test_async_convert_with_timestamps(self, kwargs, expected): - seen = [] - await _async_tts(seen, SSE_BODY).convert_with_timestamps(text="Hi", **kwargs) - _check(ormsgpack.unpackb(seen[0].content), expected) - - @pytest.mark.parametrize("kwargs, expected", CASES) - async def test_async_stream_with_timestamps(self, kwargs, expected): - seen = [] - stream = await _async_tts(seen, SSE_BODY).stream_with_timestamps( - text="Hi", **kwargs - ) - await stream.aclose() - _check(ormsgpack.unpackb(seen[0].content), expected) - - -def tts_script(conn): - """Read the start event and the text, then answer with audio and finish.""" +def finish_script(conn): + """Answer once the text has ended: audio, then finish.""" while conn.recv().get("event") != "stop": pass conn.send({"event": "audio", "audio": b"audio"}) conn.send({"event": "finish", "reason": "stop"}) +def finish_after_first_text_script(conn): + """Finish after the first text, while text_stream is still open.""" + with contextlib.suppress(Exception): # the client may leave first + while conn.recv().get("event") != "text": + pass + conn.send({"event": "audio", "audio": b"audio"}) + conn.send({"event": "finish", "reason": "stop"}) + conn.wait_gone() + + def rejecting_script(conn): """What the API does with an invalid start event: an error event, then silence.""" - conn.recv() - conn.send({"event": "error", "error": 'Invalid language "en us".'}) + with contextlib.suppress(Exception): + conn.recv() + conn.send({"event": "error", "error": 'Invalid language "en us".'}) + conn.wait_gone() -def rejecting_after_text_script(conn): - """Like rejecting_script, but rejects only once the first text has arrived. - - The sender-shutdown tests need the sender to be past its first text and - blocked in text_stream when the error comes; rejecting right after the - start event lets the error win that race and the tests time out. - """ - while conn.recv().get("event") != "text": - pass - conn.send({"event": "error", "error": 'Invalid language "en us".'}) +def silent_script(conn): + """Read everything and never answer.""" + with contextlib.suppress(Exception): + conn.wait_gone() @contextlib.contextmanager @@ -218,2039 +97,203 @@ async def aserving(script): server.close() -async def _aiter(*items): - for item in items: - yield item - - -class TestWebSocket: - @pytest.mark.parametrize("kwargs, expected", CASES) - def test_start_event(self, kwargs, expected): - with serving(tts_script) as (server, client): - audio = b"".join(client.tts.stream_websocket(iter(["Hola"]), **kwargs)) - conn = server.stop() - assert audio == b"audio" - assert conn.path == "/v1/tts/live" - start = conn.received[0] - assert start["event"] == "start" - _check(start["request"], expected) - - @pytest.mark.parametrize("kwargs, expected", CASES) - async def test_async_start_event(self, kwargs, expected): - async with aserving(tts_script) as (server, client): - chunks = [ - chunk - async for chunk in client.tts.stream_websocket(_aiter("Hola"), **kwargs) - ] - conn = server.stop() - assert b"".join(chunks) == b"audio" - _check(conn.received[0]["request"], expected) - - def test_rejected_start_event_raises_instead_of_hanging(self): - with serving(rejecting_script) as (server, client): - with pytest.raises(WebSocketError, match='Invalid language "en us"'): - list(client.tts.stream_websocket(iter(["Hola"]), language="en us")) - server.stop() - - async def test_async_rejected_start_event_raises_instead_of_hanging(self): - async with aserving(rejecting_script) as (server, client): - with pytest.raises(WebSocketError, match='Invalid language "en us"'): - async for _ in client.tts.stream_websocket( - _aiter("Hola"), language="en us" - ): - pass - server.stop() - - def test_error_after_text_stops_the_sender_before_its_next_read(self, monkeypatch): - """Once the stream has raised, the sender neither reads text_stream again nor sends.""" - release = threading.Event() - attempted = [] - real_send = WebSocketSession.send_bytes - - def held_send(self, data): - message = ormsgpack.unpackb(data) - attempted.append(message) - result = real_send(self, data) - if message.get("text") == "Hola": - release.wait(5) # hold the sender here until the stream has ended - return result - - monkeypatch.setattr(WebSocketSession, "send_bytes", held_send) - reads = [] - - def text_stream(): - reads.append("Hola") - yield "Hola" - reads.append("late") - yield "late" - - with serving(rejecting_after_text_script) as (server, client): - with pytest.raises(WebSocketError): - list(client.tts.stream_websocket(text_stream(), language="en us")) - release.set() - time.sleep(0.3) - server.stop() - assert reads == ["Hola"] - assert [m.get("text") for m in attempted if m["event"] == "text"] == ["Hola"] - - async def test_async_error_after_text_cancels_the_sender(self): - """After the error the sender task is cancelled, not left pending.""" - never = asyncio.Event() - cancelled = asyncio.Event() - - async def text_stream(): - try: - yield "Hola" - await never.wait() - yield "late" - finally: - cancelled.set() - - async with aserving(rejecting_after_text_script) as (server, client): - with pytest.raises(WebSocketError): - async for _ in client.tts.stream_websocket( - text_stream(), language="en us" - ): - pass - assert cancelled.is_set() - server.stop() - - -def endless_listener_script(conn): - """Answers the first text with audio, then reads until the client leaves.""" - while conn.recv().get("event") != "text": - pass - conn.send({"event": "audio", "audio": b"audio"}) - - -class TestClosingTheStream: - def test_closing_stops_the_sender(self, monkeypatch): - sent = [] - real_send = WebSocketSession.send_bytes - - def recording_send(self, data): - sent.append(ormsgpack.unpackb(data)) - return real_send(self, data) - - monkeypatch.setattr(WebSocketSession, "send_bytes", recording_send) - - def text_stream(): - for i in range(200): - time.sleep(0.01) - yield f"chunk {i}" - - with serving(endless_listener_script) as (server, client): - with contextlib.closing( - client.tts.stream_websocket(text_stream()) - ) as stream: - for _ in stream: - break - sent_at_close = len(sent) - time.sleep(0.3) - server.stop() - assert len(sent) == sent_at_close - - async def test_aclose_cancels_the_sender(self, monkeypatch): - sent = [] - real_send = AsyncWebSocketSession.send_bytes - - async def recording_send(self, data): - sent.append(ormsgpack.unpackb(data)) - return await real_send(self, data) - - monkeypatch.setattr(AsyncWebSocketSession, "send_bytes", recording_send) - - async def text_stream(): - for i in range(200): - await asyncio.sleep(0.01) - yield f"chunk {i}" - - async with aserving(endless_listener_script) as (server, client): - stream = client.tts.stream_websocket(text_stream()) - try: - async for _ in stream: - break - finally: - await stream.aclose() - sent_at_close = len(sent) - await asyncio.sleep(0.3) - server.stop() - assert len(sent) == sent_at_close - - -def _record_sends(monkeypatch, session_class, is_async=False): - """Record every message the SDK tries to send, before it is sent.""" - attempted = [] - real_send = session_class.send_bytes - - if is_async: - - async def recording_send(self, data): - attempted.append(ormsgpack.unpackb(data)) - return await real_send(self, data) - - else: - - def recording_send(self, data): - attempted.append(ormsgpack.unpackb(data)) - return real_send(self, data) - - monkeypatch.setattr(session_class, "send_bytes", recording_send) - return attempted - - -def early_finish_script(conn): - """Finishes after the first text, without waiting for the client's stop.""" - while conn.recv().get("event") != "text": - pass - conn.send({"event": "audio", "audio": b"audio"}) - conn.send({"event": "finish", "reason": "stop"}) - - -def finish_when(waiting): - """Like early_finish_script, but finishes only once text_stream has entered - the read it blocks in (``waiting`` is set right before it): otherwise the - finish can arrive before the sender reads again, and that read never comes. - """ - - def script(conn): - while conn.recv().get("event") != "text": - pass - assert waiting.wait(5) - conn.send({"event": "audio", "audio": b"audio"}) - conn.send({"event": "finish", "reason": "stop"}) - - return script - - -class TestTextStreamOutlivesTheStream: - def test_text_stream_ending_after_an_error_sends_no_stop(self, monkeypatch): - """text_stream ends only after the stream raised: no stop on a closed socket.""" - attempted = _record_sends(monkeypatch, WebSocketSession) - gate = threading.Event() - ended = threading.Event() - - def text_stream(): - try: - yield "Hola" - gate.wait(5) # still waiting for input when the error comes - finally: - ended.set() - - with serving(rejecting_after_text_script) as (server, client): - with pytest.raises(WebSocketError): - list(client.tts.stream_websocket(text_stream(), language="en us")) - gate.set() - assert ended.wait(5) - time.sleep(0.2) # let the sender return after text_stream ended - server.stop() - assert [m["event"] for m in attempted] == ["start", "text"] - - def test_finish_while_text_stream_waits_ends_the_stream(self, monkeypatch): - attempted = _record_sends(monkeypatch, WebSocketSession) - gate = threading.Event() - waiting = threading.Event() - late_read = threading.Event() - - def text_stream(): - yield "first" - waiting.set() - gate.wait(5) - late_read.set() - yield "late" - - result = {} - - def consume(client): - result["audio"] = b"".join(client.tts.stream_websocket(text_stream())) - - with serving(finish_when(waiting)) as (server, client): - consumer = threading.Thread(target=consume, args=(client,), daemon=True) - consumer.start() - consumer.join(2) - ended_before_text_stream = not consumer.is_alive() - gate.set() - consumer.join(5) - assert late_read.wait(5) - time.sleep(0.2) # the sender's chance to send "late" - server.stop() - assert ended_before_text_stream - assert result["audio"] == b"audio" - assert [m.get("text") for m in attempted if m["event"] == "text"] == ["first"] - - async def test_async_finish_while_text_stream_waits_ends_the_stream( - self, monkeypatch - ): - attempted = _record_sends(monkeypatch, AsyncWebSocketSession, is_async=True) - never = asyncio.Event() - closed = asyncio.Event() - - async def text_stream(): - try: - yield "first" - await never.wait() - yield "late" - finally: - closed.set() - - async def consume(client): - return [chunk async for chunk in client.tts.stream_websocket(text_stream())] - - async with aserving(early_finish_script) as (server, client): - chunks = await asyncio.wait_for(consume(client), 2) - await asyncio.wait_for(closed.wait(), 2) - server.stop() - assert b"".join(chunks) == b"audio" - assert [m.get("text") for m in attempted if m["event"] == "text"] == ["first"] - - async def test_async_text_stream_that_ignores_cancellation_sends_nothing_more( - self, monkeypatch - ): - """A text_stream may catch the cancellation and yield again: not sent.""" - attempted = _record_sends(monkeypatch, AsyncWebSocketSession, is_async=True) - never = asyncio.Event() - waiting = threading.Event() # read by the server's thread - late_yielded = asyncio.Event() - - async def text_stream(): - yield "first" - try: - waiting.set() - await never.wait() - except asyncio.CancelledError: - late_yielded.set() - yield "late" - - async def consume(client): - return [chunk async for chunk in client.tts.stream_websocket(text_stream())] - - async with aserving(finish_when(waiting)) as (server, client): - chunks = await asyncio.wait_for(consume(client), 2) - await asyncio.wait_for(late_yielded.wait(), 2) - await asyncio.sleep(0.2) # the sender's chance to send "late" - server.stop() - assert b"".join(chunks) == b"audio" - assert [m["event"] for m in attempted] == ["start", "text"] - - -def waiting_script(conn): - """Answers every text with audio and waits for the client's stop.""" - conn.recv() # start - while conn.recv().get("event") != "stop": - conn.send({"event": "audio", "audio": b"audio"}) - conn.send({"event": "finish", "reason": "stop"}) - - -def audio_then_wait_script(conn): - """Sends audio right after the start event, then waits until the client leaves.""" - conn.recv() # start - conn.send({"event": "audio", "audio": b"audio"}) - conn.wait_gone() - - -def audio_then_finish_script(conn): - """Sends audio and finishes right after the start event.""" - conn.recv() # start - conn.send({"event": "audio", "audio": b"audio"}) - conn.send({"event": "finish", "reason": "stop"}) +@pytest.fixture +def short_waits(monkeypatch): + monkeypatch.setattr(tts_module, "_POLL_SECONDS", 0.02) + monkeypatch.setattr(tts_module, "_SENDER_CLEANUP_SECONDS", 0.05) -def _consume_in_thread(client, text_stream, mode="all"): - """Read the stream in a thread; return (thread, result dict).""" +def _consume(client, text_stream, **kwargs): + """Read the stream in a thread, so a stream that never ends fails the + test instead of hanging it. Returns (audio, error).""" result = {} def run(): try: - it = client.tts.stream_websocket(text_stream) - if mode == "close_after_first": - result["audio"] = next(it) - it.close() - else: - result["audio"] = b"".join(it) - except BaseException as e: # noqa: BLE001 - reported to the test + result["audio"] = b"".join( + client.tts.stream_websocket(text_stream, **kwargs) + ) + except Exception as e: # noqa: BLE001 - reported to the test result["error"] = e thread = threading.Thread(target=run, daemon=True) thread.start() - return thread, result - - -def _block_text_sends(monkeypatch): - """Make the async SDK's sends of text events block, as on a server that stopped reading.""" - real_send = AsyncWebSocketSession.send_bytes - never = asyncio.Event() - - async def send(self, data): - if ormsgpack.unpackb(data).get("event") == "text": - await never.wait() - return await real_send(self, data) - - monkeypatch.setattr(AsyncWebSocketSession, "send_bytes", send) - - -class TestTextStreamErrorsReachTheCaller: - """An error in text_stream ends the stream with that error, not a hang.""" - - def test_sync_text_stream_error_is_raised(self): - error = ValueError("text stream failed") - - def text_stream(): - yield "hello" - raise error + thread.join(5) + assert not thread.is_alive(), "stream_websocket did not end" + return result.get("audio"), result.get("error") - with serving(waiting_script) as (server, client): - thread, result = _consume_in_thread(client, text_stream()) - thread.join(3) - hung = thread.is_alive() - if not hung: - server.stop() - assert not hung, "still waiting for audio after text_stream raised" - assert result["error"] is error - def test_sync_item_that_is_not_text_is_raised(self): - with serving(waiting_script) as (server, client): - thread, result = _consume_in_thread(client, iter(["hello", None])) - thread.join(3) - hung = thread.is_alive() - if not hung: - server.stop() - assert not hung - assert "text" in str(result["error"]) +async def _aiter(*items): + for item in items: + yield item - async def test_async_text_stream_error_is_raised(self): - error = ValueError("text stream failed") - async def text_stream(): - yield "hello" - await asyncio.sleep(0.02) - raise error +async def _aconsume(client, text_stream, **kwargs): + async def run(): + return b"".join( + [c async for c in client.tts.stream_websocket(text_stream, **kwargs)] + ) - async def consume(client): - return [c async for c in client.tts.stream_websocket(text_stream())] + # Not asyncio.wait_for: it would wait for a stream that ignores + # cancellation, and hang the test run instead of failing it. + task = asyncio.ensure_future(run()) + done, _ = await asyncio.wait({task}, timeout=5) + assert done, "stream_websocket did not end" + return task.result() - async with aserving(waiting_script) as (server, client): - with pytest.raises(ValueError) as raised: - await asyncio.wait_for(consume(client), 3) - server.stop() - assert raised.value is error - async def test_async_item_that_is_not_text_is_raised(self): - async def consume(client): - return [c async for c in client.tts.stream_websocket(_aiter("hello", None))] +def _sent_sync(method, kwargs): + if method == "stream_websocket": + with serving(finish_script) as (server, client): + assert b"".join(client.tts.stream_websocket(iter(["Hi"]), **kwargs)) + return server.stop().received[0]["request"] + seen = [] - async with aserving(waiting_script) as (server, client): - with pytest.raises(Exception, match="text"): - await asyncio.wait_for(consume(client), 3) - server.stop() + def handler(request): + seen.append(request) + return httpx.Response(200, content=SSE_BODY if "time" in method else b"a") - async def test_async_caller_cancellation_is_not_swallowed(self): - """Cancelling the caller's own task while it waits for audio cancels it.""" - never = asyncio.Event() + http = httpx.Client(base_url=BASE_URL, transport=httpx.MockTransport(handler)) + with FishAudio(api_key="test", httpx_client=http) as client: + result = getattr(client.tts, method)(text="Hi", **kwargs) + if method.startswith("stream"): + result.close() + return ormsgpack.unpackb(seen[0].content) - async def text_stream(): - yield "hello" - await never.wait() - async def consume(client): - return [c async for c in client.tts.stream_websocket(text_stream())] +async def _sent_async(method, kwargs): + if method == "stream_websocket": + async with aserving(finish_script) as (server, client): + assert await _aconsume(client, _aiter("Hi"), **kwargs) + return server.stop().received[0]["request"] + seen = [] - async with aserving(waiting_script) as (server, client): - task = asyncio.ensure_future(consume(client)) - await asyncio.sleep(0.3) - task.cancel() - with pytest.raises(asyncio.CancelledError): - await asyncio.wait_for(task, 3) - server.stop() + def handler(request): + seen.append(request) + return httpx.Response(200, content=SSE_BODY if "time" in method else b"a") + http = httpx.AsyncClient(base_url=BASE_URL, transport=httpx.MockTransport(handler)) + async with AsyncFishAudio(api_key="test", httpx_client=http) as client: + result = await getattr(client.tts, method)(text="Hi", **kwargs) + if method.startswith("stream"): + await result.aclose() + return ormsgpack.unpackb(seen[0].content) -class TestTextStreamIsClosed: - """The SDK closes a generator text_stream when the stream ends, however it ends.""" - @staticmethod - def _sync_generator(gate, closed): - def text_stream(): - try: - yield "first" - gate.wait(5) # the stream ends while this read waits - yield "late" # the sender takes it and stops: suspended here - yield "never" - finally: - closed.set() +def _check(sent, expected): + if expected is None: + assert "language" not in sent + else: + assert sent["language"] == expected - return text_stream() - @pytest.mark.parametrize( - ("script", "mode", "expect_error"), - [ - (rejecting_after_text_script, "all", WebSocketError), - (None, "close_after_first", None), - (early_finish_script, "all", None), - ], - ids=["server_error", "early_close", "normal_end"], - ) - def test_sync_generator_is_closed(self, script, mode, expect_error): - if script is None: +@pytest.mark.parametrize("method", METHODS) +@pytest.mark.parametrize("kwargs, expected", CASES) +def test_language_is_sent(method, kwargs, expected): + _check(_sent_sync(method, kwargs), expected) - def script(conn): - while conn.recv().get("event") != "text": - pass - conn.send({"event": "audio", "audio": b"audio"}) - conn.wait_gone() - gate, closed = threading.Event(), threading.Event() - gen = self._sync_generator(gate, closed) # held: not closed by GC - with serving(script) as (server, client): - thread, result = _consume_in_thread(client, gen, mode) - thread.join(3) - assert not thread.is_alive() - gate.set() - assert closed.wait(3), "text_stream was left open" - server.stop() - if expect_error: - assert isinstance(result.get("error"), expect_error) - else: - assert result["audio"] == b"audio" +@pytest.mark.parametrize("method", METHODS) +@pytest.mark.parametrize("kwargs, expected", CASES) +async def test_async_language_is_sent(method, kwargs, expected): + _check(await _sent_async(method, kwargs), expected) - def test_sync_generator_cleanup_that_hangs_does_not_hold_the_stream(self): - gate, entered, hang = threading.Event(), threading.Event(), threading.Event() - def text_stream(): - try: - yield "first" - gate.wait(5) - yield "late" - finally: - entered.set() - hang.wait(5) # cleanup that does not finish +class TestStreamWebsocketEnds: + """stream_websocket ends on every path below instead of waiting forever.""" - gen = text_stream() - with serving(early_finish_script) as (server, client): - thread, result = _consume_in_thread(client, gen) - thread.join(3) - assert not thread.is_alive() - gate.set() - assert entered.wait(3), "text_stream was not closed" + def test_server_error_event(self): + with serving(rejecting_script) as (server, client): + _, error = _consume(client, iter(["Hola"]), language="en us") server.stop() - hang.set() - assert result["audio"] == b"audio" - - def test_iterable_that_is_not_a_generator_is_left_alone(self): - """Guard: only generators are closed; this passes before the change too.""" - - class Texts: - closed = False + assert isinstance(error, WebSocketError) + assert 'Invalid language "en us"' in str(error) - def __iter__(self): - return iter(["hello"]) - - def close(self): - Texts.closed = True - - with serving(tts_script) as (server, client): - audio = b"".join(client.tts.stream_websocket(Texts())) + async def test_async_server_error_event(self): + async with aserving(rejecting_script) as (server, client): + with pytest.raises(WebSocketError, match='Invalid language "en us"'): + await _aconsume(client, _aiter("Hola"), language="en us") server.stop() - assert audio == b"audio" - assert Texts.closed is False - - @pytest.mark.parametrize( - ("script", "mode", "expect_error"), - [ - (rejecting_script, "all", WebSocketError), - (audio_then_wait_script, "close_after_first", None), - (audio_then_finish_script, "all", None), - ], - ids=["server_error", "early_close", "normal_end"], - ) - async def test_async_generator_is_closed( - self, monkeypatch, script, mode, expect_error - ): - _block_text_sends(monkeypatch) # the generator stays suspended at its yield - closed = asyncio.Event() - - async def text_stream(): - try: - yield "first" - yield "never" - finally: - closed.set() - gen = text_stream() # held: not closed by GC + def test_text_stream_error(self, short_waits): + error = ValueError("source failed") - async def consume(client): - stream = client.tts.stream_websocket(gen) - if mode == "close_after_first": - try: - return await stream.__anext__() - finally: - await stream.aclose() - return b"".join([c async for c in stream]) + def text_stream(): + yield "Hola" + raise error - async with aserving(script) as (server, client): - if expect_error: - with pytest.raises(expect_error): - await asyncio.wait_for(consume(client), 3) - else: - assert await asyncio.wait_for(consume(client), 3) == b"audio" - assert closed.is_set(), "text_stream was left open" + with serving(silent_script) as (server, client): + _, raised = _consume(client, text_stream()) server.stop() + assert raised is error - async def test_async_generator_cleanup_that_hangs_is_bounded(self, monkeypatch): - _block_text_sends(monkeypatch) - entered = asyncio.Event() - never = asyncio.Event() + async def test_async_text_stream_error(self, short_waits): + error = ValueError("source failed") async def text_stream(): - try: - yield "first" - finally: - entered.set() - await never.wait() # cleanup that does not finish - - gen = text_stream() - - async def consume(client): - return b"".join([c async for c in client.tts.stream_websocket(gen)]) - - try: - async with aserving(audio_then_finish_script) as (server, client): - loop = asyncio.get_running_loop() - started = loop.time() - assert await asyncio.wait_for(consume(client), 3) == b"audio" - elapsed = loop.time() - started - assert entered.is_set(), "text_stream was not closed" - server.stop() - finally: - never.set() # let the cleanup end before the event loop closes - await asyncio.sleep(0.05) - assert elapsed < 2.5 - - -class TestTextStreamThatIsNotIterable: - def test_sync(self): - with serving(waiting_script) as (server, client): - thread, result = _consume_in_thread(client, 42) - thread.join(3) - hung = thread.is_alive() - if not hung: - server.stop() - assert not hung - assert isinstance(result["error"], TypeError) - - async def test_async(self): - async def consume(client): - return [c async for c in client.tts.stream_websocket(["hello"])] + yield "Hola" + raise error - async with aserving(waiting_script) as (server, client): - with pytest.raises(TypeError, match="async iterable"): - await asyncio.wait_for(consume(client), 3) + async with aserving(silent_script) as (server, client): + with pytest.raises(ValueError) as raised: + await _aconsume(client, text_stream()) server.stop() + assert raised.value is error - -class TestClosingTextStreamEdgeCases: - def test_sync_failed_connection_leaves_an_unread_generator_alone(self): - """The SDK never read it: its cleanup (and when) stays the caller's.""" - cleaned = [] + def test_finish_while_text_stream_waits(self): + release = threading.Event() def text_stream(): - try: - yield "first" - yield "second" - finally: - cleaned.append(True) + yield "Hola" + release.wait(10) - gen = text_stream() - assert next(gen) == "first" # started by the caller - server = RealtimeServer(lambda conn: None, reject_status=401) - client = FishAudio(api_key="test-key", base_url=server.url) try: - with pytest.raises(Exception): # noqa: B017 - the upgrade error - list(client.tts.stream_websocket(gen)) + with serving(finish_after_first_text_script) as (server, client): + audio, error = _consume(client, text_stream()) + server.stop() finally: - client.close() - server.close() - assert cleaned == [] - assert inspect.getgeneratorstate(gen) == inspect.GEN_SUSPENDED - gen.close() # the caller's to close - assert cleaned == [True] + release.set() + assert error is None + assert audio == b"audio" - async def test_async_failed_connection_leaves_an_unread_generator_alone(self): - """The SDK never read it: its context and cleanup stay the caller's.""" - cleaned = [] + async def test_async_finish_while_text_stream_ignores_cancellation( + self, short_waits + ): + released = asyncio.Event() async def text_stream(): - try: - yield "first" - yield "second" - finally: - cleaned.append(True) + yield "Hola" + while not released.is_set(): + with contextlib.suppress(asyncio.CancelledError): + await asyncio.sleep(10) - gen = text_stream() - assert await gen.__anext__() == "first" # started by the caller - server = RealtimeServer(lambda conn: None, reject_status=401) - client = AsyncFishAudio(api_key="test-key", base_url=server.url) try: - with pytest.raises(Exception): # noqa: B017 - the upgrade error - async for _ in client.tts.stream_websocket(gen): - pass + async with aserving(finish_after_first_text_script) as (server, client): + assert await _aconsume(client, text_stream()) == b"audio" + server.stop() finally: - await client.close() - server.close() - assert cleaned == [] - await gen.aclose() # the caller's to close - assert cleaned == [True] - - async def test_async_cleanup_already_started_is_not_cut_short(self): - """After a bad item the sender closes text_stream; that cleanup completes.""" - cleaned = asyncio.Event() - - async def text_stream(): - try: - yield "hello" - yield None # not text: ends the stream - yield "never" - finally: - await asyncio.sleep(0.05) # cleanup that takes a moment - cleaned.set() - - async def consume(client): - return [c async for c in client.tts.stream_websocket(text_stream())] - - async with aserving(waiting_script) as (server, client): - with pytest.raises(Exception, match="text"): - await asyncio.wait_for(consume(client), 3) - assert cleaned.is_set(), "text_stream's cleanup was cut short" - server.stop() - - @pytest.mark.parametrize("error", [ValueError("no"), AttributeError("inner")]) - async def test_async_error_from_aiter_is_raised_as_is(self, error): - class Texts: - def __aiter__(self): - raise error - - async def consume(client): - return [c async for c in client.tts.stream_websocket(Texts())] - - async with aserving(waiting_script) as (server, client): - with pytest.raises(type(error)) as raised: - await asyncio.wait_for(consume(client), 3) - server.stop() - assert raised.value is error - - -def finish_soon_after_text_script(conn): - """Finishes shortly after the first text, without waiting for the stop. - - The client may already have raised and left by then (that is what some - tests check), so a write to a closed connection is not an error here. - """ - while conn.recv().get("event") != "text": - pass - time.sleep(0.05) - with contextlib.suppress(OSError): - conn.send({"event": "audio", "audio": b"audio"}) - conn.send({"event": "finish", "reason": "stop"}) - - -class TestSenderErrorDuringSlowCleanup: - """A send or encoding error is not lost while text_stream's cleanup runs.""" - - def test_sync(self): - def text_stream(): - try: - yield "first" - yield "\ud800" # a lone surrogate: cannot be encoded - finally: - time.sleep(0.2) # cleanup that takes a while - - with serving(finish_soon_after_text_script) as (server, client): - thread, result = _consume_in_thread(client, text_stream()) - thread.join(3) - assert not thread.is_alive() - server.stop() - assert "error" in result, "a failed send ended as a success" + released.set() - async def test_async(self): - async def text_stream(): - try: - yield "first" - yield "\ud800" # a lone surrogate: cannot be encoded - finally: - await asyncio.sleep(0.2) # cleanup that takes a while - - async def consume(client): - return [c async for c in client.tts.stream_websocket(text_stream())] - - async with aserving(finish_soon_after_text_script) as (server, client): - with pytest.raises(TypeError): # the encoder's own error, not a timeout - await asyncio.wait_for(consume(client), 3) - server.stop() + async def test_async_cancelled_handshake(self): + """A request hook that awaits a cancelled future ends the handshake + with CancelledError, which is not an Exception: it is raised, not + waited on.""" - -class TestRoundThreeEdgeCases: - def test_sync_generator_is_closed_on_the_thread_that_ran_it(self): - """What a generator holds may belong to the thread that made it (an - sqlite3 connection, for example): it is closed on that thread.""" - gate = threading.Event() - threads = {} - closed = threading.Event() - - def text_stream(): - try: - threads["ran"] = threading.get_ident() - yield "first" - gate.wait(5) - yield "late" - finally: - threads["closed"] = threading.get_ident() - closed.set() - - gen = text_stream() - with serving(early_finish_script) as (server, client): - thread, _ = _consume_in_thread(client, gen) - thread.join(3) - assert not thread.is_alive() - gate.set() - assert closed.wait(3) - server.stop() - assert threads["closed"] == threads["ran"] - - def test_sync_base_exception_from_text_stream_is_raised(self): - error = asyncio.CancelledError("source cancelled") - - def text_stream(): - yield "first" - raise error - - with serving(finish_soon_after_text_script) as (server, client): - thread, result = _consume_in_thread(client, text_stream()) - thread.join(3) - assert not thread.is_alive() - server.stop() - assert result.get("error") is error - - def test_sync_item_that_cannot_be_encoded_is_raised(self): - with serving(waiting_script) as (server, client): - thread, result = _consume_in_thread(client, iter(["hello", "\ud800"])) - thread.join(3) - hung = thread.is_alive() - if not hung: - server.stop() - assert not hung, "still waiting for audio after an item failed to encode" - assert isinstance(result.get("error"), TypeError) - - async def test_async_item_that_cannot_be_encoded_is_raised(self): - async def consume(client): - return [ - c async for c in client.tts.stream_websocket(_aiter("hello", "\ud800")) - ] - - async with aserving(waiting_script) as (server, client): - with pytest.raises(TypeError): # the encoder's own error, not a timeout - await asyncio.wait_for(consume(client), 3) - server.stop() - - -class _SourceInterrupted(BaseException): - pass - - -class TestAsyncBaseExceptionFromTextStream: - async def test_is_raised_not_taken_for_success(self): - error = _SourceInterrupted("interrupted") - - async def text_stream(): - yield "first" - raise error - - async def consume(client): - return [c async for c in client.tts.stream_websocket(text_stream())] - - async with aserving(finish_soon_after_text_script) as (server, client): - with pytest.raises(_SourceInterrupted) as raised: - await asyncio.wait_for(consume(client), 3) - server.stop() - assert raised.value is error - - -class TestAsyncCancellationOfTextStream: - """A cancellation from text_stream reaches the caller as WebSocketError, - never as a cancellation of the caller's own task.""" - - async def test_cancelled_in_aiter(self): - class Texts: - def __aiter__(self): - future = asyncio.get_running_loop().create_future() - future.cancel() - return future.result() # raises CancelledError - - async def consume(client): - return [c async for c in client.tts.stream_websocket(Texts())] - - async with aserving(waiting_script) as (server, client): - with pytest.raises(WebSocketError, match="cancelled"): - await asyncio.wait_for(consume(client), 3) - server.stop() - - async def test_cancelled_after_the_finish_is_not_a_cancellation(self): - """text_stream is cancelled after the server's finish has been read: - the stream had already ended normally (the server decides), and no - bare CancelledError reaches the caller's task.""" - awaited = asyncio.get_running_loop().create_future() - - async def text_stream(): - yield "first" - await awaited - - async def steps(client): - # One task throughout: the stream's connection must be entered - # and left in the same task. - stream = client.tts.stream_websocket(text_stream()) - try: - assert await stream.__anext__() == b"audio" - await asyncio.sleep(0.2) # the finish is read and queued - awaited.cancel() - await asyncio.sleep(0) - with pytest.raises(StopAsyncIteration): - await stream.__anext__() - finally: - await stream.aclose() - - async with aserving(audio_then_finish_after_text_script) as (server, client): - await asyncio.wait_for(steps(client), 5) - server.stop() - - -def audio_then_finish_after_text_script(conn): - """Sends audio and finishes once the first text has arrived.""" - while conn.recv().get("event") != "text": - pass - conn.send({"event": "audio", "audio": b"audio"}) - conn.send({"event": "finish", "reason": "stop"}) - - -def finish_and_close_when(closed): - """Finishes after the first text and closes the connection (code 1000) - without waiting for the client's stop, as a server may; sets ``closed``.""" - - def script(conn): - while conn.recv().get("event") != "text": - pass - conn.send({"event": "audio", "audio": b"audio"}) - conn.send({"event": "finish", "reason": "stop"}) - conn.close(1000) - closed.set() - - return script - - -def _fail_text_sends(monkeypatch, session_class, is_async=False): - """Make every send of a text event fail; return the error it raises.""" - error = RuntimeError("send failed") - real_send = session_class.send_bytes - - if is_async: - - async def send(self, data): - if ormsgpack.unpackb(data).get("event") == "text": - raise error - return await real_send(self, data) - - else: - - def send(self, data): - if ormsgpack.unpackb(data).get("event") == "text": - raise error - return real_send(self, data) - - monkeypatch.setattr(session_class, "send_bytes", send) - return error - - -class TestWhichOutcomeWins: - """The server's finish decides over a failed send of ours; a failed send - decides only when the server says nothing more; an error while the SDK - cleans up never decides; a request that cannot be encoded fails at once.""" - - def test_sync_send_after_the_server_finished_and_closed_is_not_an_error(self): - closed = threading.Event() - ended = threading.Event() - - def text_stream(): - try: - yield "first" - assert closed.wait(5) - time.sleep(0.1) # the client has read the close by now - finally: - ended.set() # its stop is sent next, on a closed connection - - with serving(finish_and_close_when(closed)) as (server, client): - stream = client.tts.stream_websocket(text_stream()) - first = next(stream) - assert ended.wait(5) - time.sleep(0.2) # the stop has been tried by now - rest = list(stream) - server.stop() - assert [first, *rest] == [b"audio"] - - async def test_async_send_after_the_server_finished_and_closed_is_not_an_error( - self, - ): - closed = threading.Event() - ended = asyncio.Event() - - async def text_stream(): - try: - yield "first" - loop = asyncio.get_running_loop() - assert await loop.run_in_executor(None, closed.wait, 5) - await asyncio.sleep(0.1) # the client has read the close by now - finally: - ended.set() # its stop is sent next, on a closed connection - - async def consume(client): - stream = client.tts.stream_websocket(text_stream()) - first = await stream.__anext__() - await ended.wait() - await asyncio.sleep(0.2) # the stop has been tried by now - return [first] + [c async for c in stream] - - async with aserving(finish_and_close_when(closed)) as (server, client): - assert await asyncio.wait_for(consume(client), 5) == [b"audio"] - server.stop() - - def test_sync_failed_send_is_raised_when_the_server_says_nothing(self, monkeypatch): - error = _fail_text_sends(monkeypatch, WebSocketSession) - with serving(waiting_script) as (server, client): - thread, result = _consume_in_thread(client, iter(["hello"])) - thread.join(3) - assert not thread.is_alive(), "a failed send left the stream waiting" - server.stop() - assert isinstance(result.get("error"), WebSocketError) - assert result["error"].__cause__ is error - - async def test_async_failed_send_is_raised_when_the_server_says_nothing( - self, monkeypatch - ): - error = _fail_text_sends(monkeypatch, AsyncWebSocketSession, is_async=True) - - async def consume(client): - return [c async for c in client.tts.stream_websocket(_aiter("hello"))] - - async with aserving(waiting_script) as (server, client): - with pytest.raises(WebSocketError) as raised: - await asyncio.wait_for(consume(client), 3) - server.stop() - assert raised.value.__cause__ is error - - async def test_async_cancellation_in_cleanup_does_not_hide_a_failed_send( - self, monkeypatch - ): - error = _fail_text_sends(monkeypatch, AsyncWebSocketSession, is_async=True) - - async def text_stream(): - try: - yield "hello" - finally: - # Its cleanup awaits something that was cancelled. - cancelled = asyncio.get_running_loop().create_future() - cancelled.cancel() - await cancelled - - async def consume(client): - return [c async for c in client.tts.stream_websocket(text_stream())] - - async with aserving(waiting_script) as (server, client): - with pytest.raises(WebSocketError) as raised: - await asyncio.wait_for(consume(client), 3) - server.stop() - assert raised.value.__cause__ is error - - def test_sync_request_that_cannot_be_encoded_is_raised(self): - result = {} - - def run(): - try: - result["audio"] = b"".join( - client.tts.stream_websocket(iter(["hello"]), language="\ud800") - ) - except BaseException as e: # noqa: BLE001 - reported to the test - result["error"] = e - - with serving(waiting_script) as (server, client): - thread = threading.Thread(target=run, daemon=True) - thread.start() - thread.join(3) - assert not thread.is_alive(), "an unencodable request hung" - assert server.connection is None # raised before connecting - assert isinstance(result.get("error"), TypeError) - - async def test_async_request_that_cannot_be_encoded_is_raised(self): - async def consume(client): - return [ - c - async for c in client.tts.stream_websocket( - _aiter("hello"), language="\ud800" - ) - ] - - async with aserving(waiting_script) as (server, client): - with pytest.raises(TypeError): - await asyncio.wait_for(consume(client), 3) - assert server.connection is None # raised before connecting - - -def close_once(sent_failed): - """Waits until a send of the client has failed, then closes the - connection (code 1000) without a finish.""" - - def script(conn): - conn.recv() # start - assert sent_failed.wait(5) - time.sleep(0.1) # the client has recorded its send error by now - conn.close(1000) - - return script - - -def _fail_text_sends_and_signal(monkeypatch, session_class, is_async=False): - """Like _fail_text_sends, but a send fails only once the client is - already waiting in a receive; sets the returned event when it fails.""" - error = RuntimeError("send failed") - sent_failed = threading.Event() - receiving = threading.Event() - real_send = session_class.send_bytes - real_receive = session_class.receive_bytes - - if is_async: - - async def receive(self, *args, **kwargs): - receiving.set() - return await real_receive(self, *args, **kwargs) - - async def send(self, data): - if ormsgpack.unpackb(data).get("event") == "text": - loop = asyncio.get_running_loop() - assert await loop.run_in_executor(None, receiving.wait, 5) - sent_failed.set() - raise error - return await real_send(self, data) - - else: - - def receive(self, *args, **kwargs): - receiving.set() - return real_receive(self, *args, **kwargs) - - def send(self, data): - if ormsgpack.unpackb(data).get("event") == "text": - assert receiving.wait(5) - sent_failed.set() - raise error - return real_send(self, data) - - monkeypatch.setattr(session_class, "receive_bytes", receive) - monkeypatch.setattr(session_class, "send_bytes", send) - return error, sent_failed - - -class _CleanupAbort(BaseException): - pass - - -class TestFailedSendWhileReceiving: - """A send that fails while the receive is already waiting is still the - reason given when the connection then closes. The receive does not poll - here (_POLL_SECONDS is long), so only the close wakes it.""" - - def test_sync(self, monkeypatch): - monkeypatch.setattr(tts_module, "_POLL_SECONDS", 30) - error, sent_failed = _fail_text_sends_and_signal(monkeypatch, WebSocketSession) - with serving(close_once(sent_failed)) as (server, client): - thread, result = _consume_in_thread(client, iter(["hello"])) - thread.join(5) - assert not thread.is_alive() - server.stop() - assert isinstance(result.get("error"), WebSocketError) - assert result["error"].__cause__ is error - - async def test_async(self, monkeypatch): - monkeypatch.setattr(tts_module, "_POLL_SECONDS", 30) - error, sent_failed = _fail_text_sends_and_signal( - monkeypatch, AsyncWebSocketSession, is_async=True - ) - - async def consume(client): - return [c async for c in client.tts.stream_websocket(_aiter("hello"))] - - async with aserving(close_once(sent_failed)) as (server, client): - with pytest.raises(WebSocketError) as raised: - await asyncio.wait_for(consume(client), 5) - server.stop() - assert raised.value.__cause__ is error - - -class TestCleanupNeverDecides: - """What closing text_stream raises is logged, not raised: it is not how - the stream ended. (Async: KeyboardInterrupt and SystemExit still - propagate.)""" - - def test_sync_close(self): - def text_stream(): - try: - yield "first" - finally: - raise _CleanupAbort - - items = text_stream() - next(items) - tts_module._close_text_stream(items) # does not raise - - def test_sync_close_logs_even_keyboard_interrupt(self, caplog): - """It runs on a worker thread, where a raise would reach no one.""" - - def text_stream(): - try: - yield "first" - finally: - raise KeyboardInterrupt - - items = text_stream() - next(items) - with caplog.at_level("DEBUG", logger=tts_module.logger.name): - tts_module._close_text_stream(items) # does not raise - assert "Closing text_stream failed" in caplog.text - - async def test_async_close(self): - async def text_stream(): - try: - yield "first" - finally: - raise _CleanupAbort - - items = text_stream() - await items.__anext__() - await tts_module._aclose_text_stream(items) # does not raise - - -def audio_then_close_when(closed, code, chunks=1): - """Sends ``chunks`` audio messages after the first text, then closes with - ``code`` and no finish; sets ``closed``.""" - - def script(conn): - while conn.recv().get("event") != "text": - pass - for _ in range(chunks): - conn.send({"event": "audio", "audio": b"audio"}) - conn.close(code) - closed.set() - - return script - - -def chatter_script(conn): - """Never finishes: sends an unknown event every 20 ms for 3 s.""" - with contextlib.suppress(Exception): # the client may leave first - conn.recv() # start - for _ in range(150): - conn.send({"event": "log"}) - time.sleep(0.02) - - -class TestRefinedOutcomeRules: - """Rules at the top of fishaudio/resources/realtime.py.""" - - def test_sync_server_close_after_a_failed_send_is_a_websocket_error(self): - """Rule 2: the server's close decides; the failed send is the cause.""" - closed = threading.Event() - ended = threading.Event() - - def text_stream(): - try: - yield "first" - assert closed.wait(5) - time.sleep(0.1) # the client has read the close by now - yield "second" # its send fails: the server is closing - finally: - ended.set() - - with serving(audio_then_close_when(closed, 1011)) as (server, client): - stream = client.tts.stream_websocket(text_stream()) - assert next(stream) == b"audio" - assert ended.wait(5) - with pytest.raises(WebSocketError) as raised: - list(stream) - server.stop() - assert raised.value.__cause__ is not None - assert "Event" in str(raised.value.__cause__) # the failed send - - async def test_async_server_close_after_a_failed_send_is_a_websocket_error( - self, - ): - closed = threading.Event() - ended = asyncio.Event() - - async def text_stream(): - try: - yield "first" - loop = asyncio.get_running_loop() - assert await loop.run_in_executor(None, closed.wait, 5) - await asyncio.sleep(0.1) # the client has read the close by now - yield "second" # its send fails: the server is closing - finally: - ended.set() - - async def consume(client): - stream = client.tts.stream_websocket(text_stream()) - assert await stream.__anext__() == b"audio" - await ended.wait() - await asyncio.sleep(0.1) - return [c async for c in stream] - - # Two chunks: the receiver holds the second until the caller takes - # it, so it reads the close only after the send has failed. - script = audio_then_close_when(closed, 1011, chunks=2) - async with aserving(script) as (server, client): - with pytest.raises(WebSocketError) as raised: - await asyncio.wait_for(consume(client), 5) - server.stop() - assert "Event" in str(raised.value.__cause__) # the failed send - - def test_sync_text_stream_failing_during_a_wait_wins_over_the_close( - self, monkeypatch - ): - """Rule 1, checked when the connection ends, not before the wait.""" - monkeypatch.setattr(tts_module, "_POLL_SECONDS", 30) - error = ValueError("source failed") - failed = threading.Event() - - def text_stream(): - yield "first" - time.sleep(0.2) # the receive is waiting by now - failed.set() - raise error - - def script(conn): - while conn.recv().get("event") != "text": - pass - assert failed.wait(5) - time.sleep(0.1) - conn.close(1000) - - with serving(script) as (server, client): - thread, result = _consume_in_thread(client, text_stream()) - thread.join(5) - assert not thread.is_alive() - server.stop() - assert result.get("error") is error - - async def test_async_text_stream_failure_wins_over_queued_audio(self): - """Rule 1: a failure before the outcome is decided wins over audio - still queued, and over the server's error that comes after it.""" - error = ValueError("source failed") - sent = threading.Event() - failed = asyncio.Event() - - async def text_stream(): - try: - yield "first" - loop = asyncio.get_running_loop() - assert await loop.run_in_executor(None, sent.wait, 5) - await asyncio.sleep(0.1) # the second chunk is queued by now - raise error - finally: - failed.set() - - def script(conn): - while conn.recv().get("event") != "text": - pass - conn.send({"event": "audio", "audio": b"one"}) - conn.send({"event": "audio", "audio": b"two"}) - conn.send({"event": "error", "error": "server failed"}) - sent.set() - conn.wait_gone() - - async def consume(client): - stream = client.tts.stream_websocket(text_stream()) - # Holding the first chunk keeps the second queued and the - # server's error unread. - assert await stream.__anext__() == b"one" - await failed.wait() - await asyncio.sleep(0.05) - return [c async for c in stream] - - async with aserving(script) as (server, client): - with pytest.raises(ValueError) as raised: - await asyncio.wait_for(consume(client), 5) - server.stop() - assert raised.value is error - - def test_sync_drain_has_one_budget(self, monkeypatch): - """Rule 3: messages that keep arriving do not postpone a failed send.""" - error = _fail_text_sends(monkeypatch, WebSocketSession) - with serving(chatter_script) as (server, client): - started = time.monotonic() - thread, result = _consume_in_thread(client, iter(["hello"])) - thread.join(5) - elapsed = time.monotonic() - started - assert not thread.is_alive() - server.stop() - assert result["error"].__cause__ is error - assert elapsed < 1.5, f"the failed send waited {elapsed:.2f} s" - - async def test_async_drain_has_one_budget(self, monkeypatch): - error = _fail_text_sends(monkeypatch, AsyncWebSocketSession, is_async=True) - - async def consume(client): - return [c async for c in client.tts.stream_websocket(_aiter("hello"))] - - async with aserving(chatter_script) as (server, client): - started = time.monotonic() - with pytest.raises(WebSocketError) as raised: - await asyncio.wait_for(consume(client), 5) - elapsed = time.monotonic() - started - server.stop() - assert raised.value.__cause__ is error - assert elapsed < 1.5, f"the failed send waited {elapsed:.2f} s" - - async def test_async_cancellation_keeps_the_original_as_cause(self): - error = asyncio.CancelledError("source cancelled") - - async def text_stream(): - yield "first" - raise error - - async def consume(client): - return [c async for c in client.tts.stream_websocket(text_stream())] - - async with aserving(waiting_script) as (server, client): - with pytest.raises(WebSocketError) as raised: - await asyncio.wait_for(consume(client), 3) - server.stop() - assert raised.value.__cause__ is error - - -class TestIterWebsocketAudioWithOnlySendFailed: - def test_does_not_wait_forever(self): - """send_failed alone also bounds the wait (no failure check given).""" - import queue - - from fishaudio.resources.realtime import iter_websocket_audio - - error = RuntimeError("send failed") - - class SilentSession: - def receive_bytes(self, timeout=None): - if timeout is None: - raise AssertionError("an unbounded receive") - time.sleep(timeout) - raise queue.Empty - - with pytest.raises(WebSocketError) as raised: - list(iter_websocket_audio(SilentSession(), send_failed=lambda: error)) - assert raised.value.__cause__ is error - - -class TestConnectionLivesInItsOwnTask: - """The async stream's connection is opened and closed by one task of its - own, so leaving the stream from another task, or having it finalized by - the event loop, does not trip httpx-ws's task group.""" - - async def test_wait_for_around_anext_then_aclose(self): - async def text_stream(): - yield "first" - await asyncio.sleep(60) - - async with aserving(audio_then_wait_script) as (server, client): - stream = client.tts.stream_websocket(text_stream()) - # wait_for runs __anext__ in a task of its own on Python < 3.12. - assert await asyncio.wait_for(stream.__anext__(), 3) == b"audio" - await asyncio.wait_for(stream.aclose(), 3) - server.stop() - - async def test_error_in_the_loop_body_leaves_the_caller_running(self): - import gc - - loop = asyncio.get_running_loop() - loop_errors = [] - previous = loop.get_exception_handler() - loop.set_exception_handler(lambda _loop, context: loop_errors.append(context)) - - async def text_stream(): - yield "first" - await asyncio.sleep(60) - - async def caller(client): - with contextlib.suppress(OSError): - async for _chunk in client.tts.stream_websocket(text_stream()): - raise OSError("disk full") # no aclose: left to the loop - gc.collect() # the generator is finalized by the event loop - await asyncio.sleep(0.3) - return "still running" - - try: - async with aserving(audio_then_wait_script) as (server, client): - assert await asyncio.wait_for(caller(client), 5) == "still running" - server.stop() - finally: - loop.set_exception_handler(previous) - assert loop_errors == [] - - -# Faults at the lowest layer: the network stream under httpx-ws. Everything -# above it (httpx-ws, wsproto, the SDK) is the real code. - - -def _break_writes(monkeypatch): - """Once the returned event is set, every write to the network stream - fails as a broken connection does (httpcore.WriteError).""" - import httpcore - from httpcore._backends.anyio import AnyIOStream - from httpcore._backends.sync import SyncStream - - broken = threading.Event() - real_sync_write = SyncStream.write - real_async_write = AnyIOStream.write - - def sync_write(self, buffer, timeout=None): - if broken.is_set(): - raise httpcore.WriteError("Broken pipe") - return real_sync_write(self, buffer, timeout) - - async def async_write(self, buffer, timeout=None): - if broken.is_set(): - raise httpcore.WriteError("Broken pipe") - return await real_async_write(self, buffer, timeout) - - monkeypatch.setattr(SyncStream, "write", sync_write) - monkeypatch.setattr(AnyIOStream, "write", async_write) - return broken - - -def _sync_text_breaking_writes(broken, before=None): - """Yields "hello" with writes broken, so its send fails. ``before`` runs - first (in the sender thread), before writes break.""" - yield "first" - if before is not None: - before() - broken.set() - yield "hello" - - -async def _async_text_breaking_writes(broken, before=None): - yield "first" - if before is not None: - await before() - broken.set() - yield "hello" - - -def _causes(error): - chain = [] - while error is not None: - chain.append(error) - error = error.__cause__ or error.__context__ - return chain - - -def _has_write_error(error): - import httpcore - - return any(isinstance(e, httpcore.WriteError) for e in _causes(error)) - - -def answer_first_text_script(then): - """Answers the first text with audio, then runs ``then(conn)``.""" - - def script(conn): - with contextlib.suppress(Exception): # the client may leave first - while conn.recv().get("event") != "text": - pass - conn.send({"event": "audio", "audio": b"audio"}) - then(conn) - - return script - - -class TestRealWriteFailure: - """Rules 3 and 4, with a real broken write under the real httpx-ws.""" - - def test_sync_silent_server(self, monkeypatch): - broken = _break_writes(monkeypatch) - script = answer_first_text_script(lambda conn: conn.wait_gone()) - with serving(script) as (server, client): - started = time.monotonic() - thread, result = _consume_in_thread( - client, _sync_text_breaking_writes(broken) - ) - thread.join(5) - assert not thread.is_alive(), "a broken write left the stream waiting" - server.stop() - assert time.monotonic() - started < 2 - assert isinstance(result.get("error"), WebSocketError) - assert _has_write_error(result["error"]) - - async def test_async_silent_server(self, monkeypatch): - broken = _break_writes(monkeypatch) - script = answer_first_text_script(lambda conn: conn.wait_gone()) - - async def consume(client): - return [ - c - async for c in client.tts.stream_websocket( - _async_text_breaking_writes(broken) - ) - ] - - async with aserving(script) as (server, client): - with pytest.raises(WebSocketError) as raised: - await asyncio.wait_for(consume(client), 5) - server.stop() - assert _has_write_error(raised.value) - - def test_sync_finish_in_the_same_wait_wins(self, monkeypatch): - """The server's finish has been received when the write fails: the - server's word decides (rule 2 over rule 3).""" - broken = _break_writes(monkeypatch) - sent = threading.Event() - - def then(conn): - conn.send({"event": "finish", "reason": "stop"}) - sent.set() - - def before(): - assert sent.wait(5) - time.sleep(0.1) # httpx-ws has received the finish by now - - with serving(answer_first_text_script(then)) as (server, client): - thread, result = _consume_in_thread( - client, _sync_text_breaking_writes(broken, before) - ) - thread.join(5) - assert not thread.is_alive() - server.stop() - assert result.get("audio") == b"audio", result.get("error") - - async def test_async_finish_in_the_same_wait_wins(self, monkeypatch): - broken = _break_writes(monkeypatch) - sent = threading.Event() - - def then(conn): - conn.send({"event": "finish", "reason": "stop"}) - sent.set() - - async def before(): - loop = asyncio.get_running_loop() - assert await loop.run_in_executor(None, sent.wait, 5) - await asyncio.sleep(0.1) # httpx-ws has received the finish by now - - async def consume(client): - return [ - c - async for c in client.tts.stream_websocket( - _async_text_breaking_writes(broken, before) - ) - ] - - async with aserving(answer_first_text_script(then)) as (server, client): - assert await asyncio.wait_for(consume(client), 5) == [b"audio"] - server.stop() - - def test_sync_drain_has_one_budget(self, monkeypatch): - """A broken write, while unknown events keep arriving every 20 ms.""" - broken = _break_writes(monkeypatch) - - def then(conn): - for _ in range(150): - conn.send({"event": "log"}) - time.sleep(0.02) - - with serving(answer_first_text_script(then)) as (server, client): - started = time.monotonic() - thread, result = _consume_in_thread( - client, _sync_text_breaking_writes(broken) - ) - thread.join(5) - elapsed = time.monotonic() - started - assert not thread.is_alive() - server.stop() - assert isinstance(result.get("error"), WebSocketError) - assert elapsed < 1.5, f"the broken write waited {elapsed:.2f} s" - - async def test_async_drain_has_one_budget(self, monkeypatch): - broken = _break_writes(monkeypatch) - - def then(conn): - for _ in range(150): - conn.send({"event": "log"}) - time.sleep(0.02) - - async def consume(client): - return [ - c - async for c in client.tts.stream_websocket( - _async_text_breaking_writes(broken) - ) - ] - - async with aserving(answer_first_text_script(then)) as (server, client): - started = time.monotonic() - with pytest.raises(WebSocketError): - await asyncio.wait_for(consume(client), 5) - elapsed = time.monotonic() - started - server.stop() - assert elapsed < 1.5, f"the broken write waited {elapsed:.2f} s" - - -class TestPairsOfFaultsInOneWait: - """Two faults arrive while the receive is waiting; the written rules say - which one decides.""" - - def test_sync_text_stream_fails_then_server_error_event(self, monkeypatch): - """Rule 1: the failure came first, so it wins over the server's error.""" - monkeypatch.setattr(tts_module, "_POLL_SECONDS", 30) - error = ValueError("source failed") - failed = threading.Event() - - def text_stream(): - yield "first" - time.sleep(0.2) # the receive is waiting by now - failed.set() - raise error - - def script(conn): - # The client may have left by the time the server speaks. - with contextlib.suppress(Exception): - while conn.recv().get("event") != "text": - pass - assert failed.wait(5) - time.sleep(0.1) - conn.send({"event": "error", "error": "server failed"}) - conn.wait_gone() - - with serving(script) as (server, client): - thread, result = _consume_in_thread(client, text_stream()) - thread.join(5) - assert not thread.is_alive() - server.stop() - assert result.get("error") is error - - def test_sync_text_stream_fails_then_server_finish(self, monkeypatch): - """Rule 1: a failed text_stream is not taken for success.""" - monkeypatch.setattr(tts_module, "_POLL_SECONDS", 30) - error = ValueError("source failed") - failed = threading.Event() - - def text_stream(): - yield "first" - time.sleep(0.2) - failed.set() - raise error - - def script(conn): - # The client may have left by the time the server speaks. - with contextlib.suppress(Exception): - while conn.recv().get("event") != "text": - pass - assert failed.wait(5) - time.sleep(0.1) - conn.send({"event": "finish", "reason": "stop"}) - conn.wait_gone() - - with serving(script) as (server, client): - thread, result = _consume_in_thread(client, text_stream()) - thread.join(5) - assert not thread.is_alive() - server.stop() - assert result.get("error") is error - - async def test_async_text_stream_fails_then_server_error_event(self): - error = ValueError("source failed") - failed = threading.Event() - - async def text_stream(): - yield "first" - await asyncio.sleep(0.2) - failed.set() - raise error - - def script(conn): - # The client may have left by the time the server speaks. - with contextlib.suppress(Exception): - while conn.recv().get("event") != "text": - pass - assert failed.wait(5) - time.sleep(0.1) - conn.send({"event": "error", "error": "server failed"}) - conn.wait_gone() - - async def consume(client): - return [c async for c in client.tts.stream_websocket(text_stream())] - - async with aserving(script) as (server, client): - with pytest.raises(ValueError) as raised: - await asyncio.wait_for(consume(client), 5) - server.stop() - assert raised.value is error - - def test_sync_sender_stops_at_a_broken_write(self, monkeypatch): - """The sender stops at a failed send: text_stream is not read again.""" - broken = _break_writes(monkeypatch) - error = ValueError("source failed") - - def text_stream(): - yield "first" - broken.set() - yield "hello" # this send fails - raise error # never reached: the sender stops at the failed send - - script = answer_first_text_script(lambda conn: conn.wait_gone()) - with serving(script) as (server, client): - thread, result = _consume_in_thread(client, text_stream()) - thread.join(5) - assert not thread.is_alive() - server.stop() - # The sender stops at the failed send, so text_stream never fails: - # the broken write is the outcome. - assert isinstance(result.get("error"), WebSocketError) - assert _has_write_error(result["error"]) - - async def test_async_write_breaks_and_server_closes_in_one_wait(self, monkeypatch): - """Rule 2: the server's close decides; the broken write is its cause.""" - broken = _break_writes(monkeypatch) - closed = threading.Event() - - def then(conn): - conn.close(1011) - closed.set() - - async def before(): - loop = asyncio.get_running_loop() - assert await loop.run_in_executor(None, closed.wait, 5) - await asyncio.sleep(0.1) # httpx-ws has received the close - - async def consume(client): - return [ - c - async for c in client.tts.stream_websocket( - _async_text_breaking_writes(broken, before) - ) - ] - - async with aserving(answer_first_text_script(then)) as (server, client): - with pytest.raises(WebSocketError): - await asyncio.wait_for(consume(client), 5) - server.stop() - - -class TestCleanupNeverDecidesThroughTheStream: - async def test_async_cleanup_error_after_a_finish(self): - """Rule 5 through the public API: text_stream's cleanup raises after - the server has finished; the stream still succeeds.""" - - async def text_stream(): - try: - yield "first" - await asyncio.sleep(60) - finally: - raise _CleanupAbort - - async def consume(client): - return [c async for c in client.tts.stream_websocket(text_stream())] - - async with aserving(audio_then_finish_after_text_script) as (server, client): - assert await asyncio.wait_for(consume(client), 5) == [b"audio"] - server.stop() - - def test_sync_cleanup_error_after_a_finish(self): - """The SDK's close() of a generator suspended at a yield after the - finish runs its cleanup, which raises: logged, not the outcome.""" - finished = threading.Event() - cleaned = threading.Event() - - def text_stream(): - try: - yield "first" - assert finished.wait(5) - time.sleep(0.2) # the caller has read the finish by now - yield "second" # not sent: the stream is over; closed here - finally: - cleaned.set() - raise _CleanupAbort - - def script(conn): - while conn.recv().get("event") != "text": - pass - conn.send({"event": "audio", "audio": b"audio"}) - conn.send({"event": "finish", "reason": "stop"}) - finished.set() - - with serving(script) as (server, client): - thread, result = _consume_in_thread(client, text_stream()) - thread.join(5) - assert not thread.is_alive() - assert cleaned.wait(5) - server.stop() - assert result.get("audio") == b"audio", result.get("error") - - -def _all_answers_then_signal(sent): - """Sends three audio chunks and a finish as soon as the start arrives, - then sets ``sent``.""" - - def script(conn): - with contextlib.suppress(Exception): - conn.recv() # start - for _ in range(3): - conn.send({"event": "audio", "audio": b"audio"}) - conn.send({"event": "finish", "reason": "stop"}) - sent.set() - conn.wait_gone() - - return script - - -class TestSlowCallerAfterAFailedSend: - """Rule 3: time the caller spends on a chunk is not taken from the - waiting budget, so a finish already received still decides.""" - - def test_sync(self, monkeypatch): - _fail_text_sends(monkeypatch, WebSocketSession) - sent = threading.Event() - - def text_stream(): - assert sent.wait(5) - time.sleep(0.1) # let httpx-ws take the messages in - yield "hello" # this send fails - - with serving(_all_answers_then_signal(sent)) as (server, client): - chunks = [] - for chunk in client.tts.stream_websocket(text_stream()): - chunks.append(chunk) - time.sleep(0.1) # longer than the whole budget - server.stop() - assert chunks == [b"audio"] * 3 - - async def test_async(self, monkeypatch): - _fail_text_sends(monkeypatch, AsyncWebSocketSession, is_async=True) - sent = threading.Event() - - async def text_stream(): - loop = asyncio.get_running_loop() - assert await loop.run_in_executor(None, sent.wait, 5) - await asyncio.sleep(0.1) - yield "hello" - - async def consume(client): - chunks = [] - async for chunk in client.tts.stream_websocket(text_stream()): - chunks.append(chunk) - await asyncio.sleep(0.1) - return chunks - - async with aserving(_all_answers_then_signal(sent)) as (server, client): - assert await asyncio.wait_for(consume(client), 5) == [b"audio"] * 3 - server.stop() - - -class TestAsyncTextStreamFailsThenServerFinish: - async def test_failure_is_not_taken_for_success(self): - """Rule 1, async: the failure came first, so a later finish does not - turn it into success.""" - error = ValueError("source failed") - failed = threading.Event() - - async def text_stream(): - yield "first" - await asyncio.sleep(0.2) - failed.set() - raise error - - def script(conn): - with contextlib.suppress(Exception): - while conn.recv().get("event") != "text": - pass - assert failed.wait(5) - time.sleep(0.1) - conn.send({"event": "finish", "reason": "stop"}) - conn.wait_gone() - - async def consume(client): - return [c async for c in client.tts.stream_websocket(text_stream())] - - async with aserving(script) as (server, client): - with pytest.raises(ValueError) as raised: - await asyncio.wait_for(consume(client), 5) - server.stop() - assert raised.value is error - - -class TestAsyncSessionEndsWithoutAnOutcome: - async def test_cancelled_handshake_is_raised_not_waited_on(self): - """A request hook that awaits a cancelled future (a shared token - refresh that was cancelled, say) ends the handshake with - CancelledError, which is not an Exception: the session task ends - without queueing an outcome. The read raises it, as before the - session task existed, instead of waiting forever.""" - - async def refresh_token(request): - future = asyncio.get_running_loop().create_future() - future.cancel() - await future - - async def text_stream(): - yield "hello" + async def refresh_token(request): + future = asyncio.get_running_loop().create_future() + future.cancel() + await future async with httpx.AsyncClient( - base_url="https://unit.test", event_hooks={"request": [refresh_token]} + base_url=BASE_URL, event_hooks={"request": [refresh_token]} ) as http: client = AsyncFishAudio(api_key="test", httpx_client=http) - stream = client.tts.stream_websocket(text_stream()) + stream = client.tts.stream_websocket(_aiter("Hola")) read = asyncio.ensure_future(stream.__anext__()) - done, _ = await asyncio.wait({read}, timeout=2) + done, _ = await asyncio.wait({read}, timeout=5) if not done: read.cancel() await asyncio.gather(read, return_exceptions=True) - assert done, "the read waited for an outcome that will not come" + assert done, "stream_websocket did not end" assert read.cancelled() await stream.aclose() - - -class TestAsyncSenderAfterTheStreamEnds: - async def test_text_stream_is_not_read_again(self, monkeypatch): - """aclose() while a write has finished but the sender has not yet - resumed: the sender stops before its next read.""" - reads = [] - written = asyncio.Event() - release = asyncio.Event() - - async def text_stream(): - reads.append("first") - yield "first" - reads.append("second") - yield "second" - - real_send = AsyncWebSocketSession.send_bytes - - async def send(self, data): - await real_send(self, data) - if ormsgpack.unpackb(data).get("text") == "first": - written.set() - await release.wait() - - monkeypatch.setattr(AsyncWebSocketSession, "send_bytes", send) - - def script(conn): - with contextlib.suppress(Exception): - while conn.recv().get("event") != "text": - pass - conn.send({"event": "audio", "audio": b"audio"}) - conn.wait_gone() - - async with aserving(script) as (server, client): - stream = client.tts.stream_websocket(text_stream()) - assert await asyncio.wait_for(stream.__anext__(), 5) == b"audio" - await asyncio.wait_for(written.wait(), 5) - release.set() # the sender can resume, but has not yet - await stream.aclose() - server.stop() - assert reads == ["first"] From 4e0d96d295e71e0683f26514ad05e230be0f35ef Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:41:20 -0800 Subject: [PATCH 29/29] fix(tts): a finish does not hide a text_stream failure already recorded When text_stream raised after yielding some text and the server then finished on that text within the receive's poll, the stream ended as a success with partial audio; main raised the text_stream error. The receive now checks for a recorded sender failure before it accepts a finish. It does not wait for a sender that is still running. Docstrings now say what is true: a sync stream that ends while text_stream is blocked leaves the worker thread until that read returns; an async text_stream cancelled from inside is reported as WebSocketError("text_stream was cancelled"); a connection that breaks without a close raises httpx_ws.WebSocketNetworkError, as on main. --- src/fishaudio/resources/realtime.py | 12 +++++++ src/fishaudio/resources/tts.py | 17 +++++++--- tests/unit/test_tts_language.py | 49 +++++++++++++++++++++++++++++ 3 files changed, 74 insertions(+), 4 deletions(-) diff --git a/src/fishaudio/resources/realtime.py b/src/fishaudio/resources/realtime.py index 44d2d21..d72cedf 100644 --- a/src/fishaudio/resources/realtime.py +++ b/src/fishaudio/resources/realtime.py @@ -94,6 +94,12 @@ def iter_websocket_audio( data = ormsgpack.unpackb(message) if _should_stop(data): + # A finish does not hide a sender failure already recorded: + # the server may have finished on the text sent before it. + if sender_failed is not None: + error = sender_failed() + if error is not None: + raise error break audio = _process_audio_event(data) @@ -147,6 +153,12 @@ async def aiter_websocket_audio( data = ormsgpack.unpackb(message) if _should_stop(data): + # A finish does not hide a sender failure already recorded: + # the server may have finished on the text sent before it. + if sender_failed is not None: + error = sender_failed() + if error is not None: + raise error break audio = _process_audio_event(data) diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 7f3e828..b1a1de7 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -524,7 +524,10 @@ def stream_websocket( Args: text_stream: Iterator of text chunks to stream. If it raises, the - stream raises that exception. + stream raises that exception. If the stream ends while + text_stream is blocked waiting for its next item, the worker + thread stays until that read returns, which can keep the + process from exiting. reference_id: Voice reference ID (overrides config.reference_id if provided) references: Reference audio samples (overrides config.references if provided) format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided) @@ -545,7 +548,9 @@ def stream_websocket( Raises: WebSocketError: When the server reports an error (for example an - invalid language tag) or the connection closes unexpectedly. + invalid language tag) or closes the connection before it + finishes. A connection that breaks without a close raises + httpx_ws.WebSocketNetworkError. Example: ```python @@ -1045,7 +1050,9 @@ async def stream_websocket( Args: text_stream: Async iterator of text chunks to stream. If it raises, - the stream raises that exception. + the stream raises that exception; if it is cancelled from + inside, the stream raises WebSocketError("text_stream was + cancelled"). reference_id: Voice reference ID (overrides config.reference_id if provided) references: Reference audio samples (overrides config.references if provided) format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided) @@ -1065,7 +1072,9 @@ async def stream_websocket( Raises: WebSocketError: When the server reports an error (for example an - invalid language tag) or the connection closes unexpectedly. + invalid language tag) or closes the connection before it + finishes. A connection that breaks without a close raises + httpx_ws.WebSocketNetworkError. Example: ```python diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index d1a3c3f..540ae9c 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -8,6 +8,7 @@ import asyncio import contextlib import threading +import time import httpx import ormsgpack @@ -297,3 +298,51 @@ async def refresh_token(request): assert done, "stream_websocket did not end" assert read.cancelled() await stream.aclose() + + def test_text_stream_error_before_a_finish(self): + """The server finishes on the text sent before text_stream failed: + the failure is still raised, as on main.""" + error = ValueError("source failed") + failed = threading.Event() + + def text_stream(): + yield "Hola" + failed.set() + raise error + + with serving(_finish_once(failed)) as (server, client): + _, raised = _consume(client, text_stream()) + server.stop() + assert raised is error + + async def test_async_text_stream_error_before_a_finish(self): + error = ValueError("source failed") + failed = threading.Event() + + async def text_stream(): + yield "Hola" + failed.set() + raise error + + async with aserving(_finish_once(failed)) as (server, client): + with pytest.raises(ValueError) as raised: + await _aconsume(client, text_stream()) + server.stop() + assert raised.value is error + + +def _finish_once(failed): + """After the first text, wait until text_stream has failed, then send + audio and a normal finish at once (well within the receive's poll).""" + + def script(conn): + with contextlib.suppress(Exception): + while conn.recv().get("event") != "text": + pass + assert failed.wait(5) + time.sleep(0.05) # the sender records the failure meanwhile + conn.send({"event": "audio", "audio": b"audio"}) + conn.send({"event": "finish", "reason": "stop"}) + conn.wait_gone() + + return script