From bc30ec6d6b7d747224bfeebee24b160647e533f6 Mon Sep 17 00:00:00 2001 From: Chen-Yang Su Date: Tue, 1 Dec 2026 02:29:52 -0800 Subject: [PATCH] fix(tts): clean up sender task and propagate sender errors in async stream_websocket --- src/fishaudio/resources/tts.py | 70 ++++++++++++--- tests/unit/test_tts_realtime.py | 148 ++++++++++++++++++++++++++++++++ 2 files changed, 206 insertions(+), 12 deletions(-) diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 9269890..bbcf8d1 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 @@ -1076,19 +1077,64 @@ async def text_generator(): ) as ws: 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: - event = _normalize_to_event(item) - await ws.send_bytes(ormsgpack.packb(event.model_dump())) - await ws.send_bytes(ormsgpack.packb(CloseEvent().model_dump())) + try: + await ws.send_bytes( + ormsgpack.packb(StartEvent(request=tts_request).model_dump()) + ) + # 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())) + finally: + if inspect.isasyncgen(text_stream): + with contextlib.suppress(Exception): + await text_stream.aclose() sender_task = asyncio.create_task(sender()) + audio_iter = aiter_websocket_audio(ws) + next_chunk: Optional[asyncio.Task[bytes]] = None - # Process incoming audio messages - async for audio_chunk in aiter_websocket_audio(ws): - yield audio_chunk + async def _next_audio() -> bytes: + return await audio_iter.__anext__() - await sender_task + try: + # Process incoming audio messages + while True: + if sender_task.done(): + await sender_task + async for audio_chunk in audio_iter: + yield audio_chunk + break + next_chunk = asyncio.create_task(_next_audio()) + done, _ = await asyncio.wait( + {next_chunk, sender_task}, + return_when=asyncio.FIRST_COMPLETED, + ) + if next_chunk not in done: + await sender_task + try: + audio_chunk = await next_chunk + except StopAsyncIteration: + break + finally: + next_chunk = None + yield audio_chunk + await sender_task + finally: + if next_chunk is not None: + if not next_chunk.done(): + next_chunk.cancel() + with contextlib.suppress(asyncio.CancelledError, Exception): + await next_chunk + elif not next_chunk.cancelled(): + next_chunk.exception() + if inspect.isasyncgen(audio_iter): + with contextlib.suppress(Exception): + await audio_iter.aclose() + if not sender_task.done(): + sender_task.cancel() + with contextlib.suppress(asyncio.CancelledError, Exception): + await sender_task + elif not sender_task.cancelled(): + sender_task.exception() diff --git a/tests/unit/test_tts_realtime.py b/tests/unit/test_tts_realtime.py index 99e2f13..8226cc8 100644 --- a/tests/unit/test_tts_realtime.py +++ b/tests/unit/test_tts_realtime.py @@ -1,14 +1,20 @@ """Tests for TTS realtime streaming.""" +import asyncio +import gc from unittest.mock import AsyncMock, MagicMock, Mock, patch import ormsgpack import pytest +from fishaudio import AsyncFishAudio from fishaudio.core import AsyncClientWrapper, ClientWrapper, WebSocketOptions +from fishaudio.exceptions import WebSocketError from fishaudio.resources.tts import AsyncTTSClient, TTSClient from fishaudio.types import FlushEvent, Prosody, ReferenceAudio, TextEvent, TTSConfig +from .realtime_server import RealtimeServer + @pytest.fixture def mock_client_wrapper(mock_api_key): @@ -722,3 +728,145 @@ async def text_stream(): assert ( mock_aconnect_ws.call_args[1]["keepalive_ping_timeout_seconds"] == 60.0 ) + + +class TestAsyncTTSRealtimeCleanup: + """Real-transport cleanup tests for AsyncTTSClient.stream_websocket.""" + + @pytest.mark.asyncio + async def test_stream_websocket_cancels_sender_on_server_error(self): + unhandled = [] + loop = asyncio.get_running_loop() + previous_handler = loop.get_exception_handler() + loop.set_exception_handler(lambda _loop, ctx: unhandled.append(ctx)) + + def error_script(conn): + start = conn.recv() + assert start["event"] == "start" + conn.send({"event": "audio", "audio": b"chunk1"}) + conn.send({"event": "finish", "reason": "error"}) + + server = RealtimeServer(error_script) + stream_closed = False + + async def slow_text_stream(): + nonlocal stream_closed + try: + for i in range(5): + yield f"word {i}" + await asyncio.sleep(0.05) + finally: + stream_closed = True + + try: + async with AsyncFishAudio(api_key="test", base_url=server.url) as client: + received = [] + with pytest.raises(WebSocketError): + async for chunk in client.tts.stream_websocket(slow_text_stream()): + received.append(chunk) + + await asyncio.sleep(0.15) + gc.collect() + await asyncio.sleep(0) + await asyncio.to_thread(server.stop) + finally: + loop.set_exception_handler(previous_handler) + + assert received == [b"chunk1"] + assert stream_closed is True + assert unhandled == [] + + @pytest.mark.asyncio + async def test_stream_websocket_cancels_sender_on_early_close(self): + unhandled = [] + loop = asyncio.get_running_loop() + previous_handler = loop.get_exception_handler() + loop.set_exception_handler(lambda _loop, ctx: unhandled.append(ctx)) + + def streaming_script(conn): + start = conn.recv() + assert start["event"] == "start" + conn.send({"event": "audio", "audio": b"chunk1"}) + conn.send({"event": "audio", "audio": b"chunk2"}) + conn.wait_gone() + + server = RealtimeServer(streaming_script) + stream_closed = False + + async def slow_text_stream(): + nonlocal stream_closed + try: + for i in range(10): + yield f"word {i}" + await asyncio.sleep(0.05) + finally: + stream_closed = True + + try: + async with AsyncFishAudio(api_key="test", base_url=server.url) as client: + gen = client.tts.stream_websocket(slow_text_stream()) + try: + received = [] + async for chunk in gen: + received.append(chunk) + break + finally: + await gen.aclose() + + await asyncio.sleep(0.15) + gc.collect() + await asyncio.sleep(0) + await asyncio.to_thread(server.stop) + finally: + loop.set_exception_handler(previous_handler) + + assert received == [b"chunk1"] + assert stream_closed is True + assert unhandled == [] + + @pytest.mark.asyncio + async def test_stream_websocket_propagates_sender_error_without_hanging(self): + unhandled = [] + loop = asyncio.get_running_loop() + previous_handler = loop.get_exception_handler() + loop.set_exception_handler(lambda _loop, ctx: unhandled.append(ctx)) + + def wait_for_stop(conn): + start = conn.recv() + assert start["event"] == "start" + while True: + msg = conn.recv() + if msg["event"] == "stop": + conn.send({"event": "finish", "reason": "stop"}) + break + conn.send({"event": "audio", "audio": b"chunk1"}) + + server = RealtimeServer(wait_for_stop) + + async def failing_text_stream(): + yield "hello" + await asyncio.sleep(0.02) + raise ValueError("text stream failed") + + try: + async with AsyncFishAudio(api_key="test", base_url=server.url) as client: + + async def consume(): + chunks = [] + async for chunk in client.tts.stream_websocket( + failing_text_stream() + ): + chunks.append(chunk) + return chunks + + with pytest.raises(ValueError, match="text stream failed"): + await asyncio.wait_for(consume(), timeout=2.0) + + await asyncio.sleep(0.05) + gc.collect() + await asyncio.sleep(0) + await asyncio.to_thread(server.stop) + finally: + loop.set_exception_handler(previous_handler) + + assert unhandled == []