diff --git a/CLAUDE.md b/CLAUDE.md index f739d6f..e2a28b9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -465,6 +465,7 @@ async with AsyncRealTimeTranscriber(RealTimeTranscriberOptions(token=token_from_ - Don't feed `AsyncRealTimeTranscriber.stream()` from a sync generator that blocks (e.g. `time.sleep` pacing) — it starves the read task. Use an `async def` generator with `await asyncio.sleep(...)` instead. - `format_turns=True` enables punctuation/casing on end-of-turns. Set it at connect: the server ignores `format_turns` and `filter_profanity` in a mid-session `UpdateConfiguration`, and `set_params` logs a warning when either is set. - `AsyncRealTimeTranscriber` used as `async with` calls `disconnect(terminate=True)` on normal block exit and `disconnect(terminate=False)` on exception — no explicit `disconnect()` needed inside the block. +- A server message the client cannot read (not JSON, not an object, or failing validation) is logged at warning level and skipped; the session goes on. The warning names the message type and the failing fields, never the contents. An `Error` or `Termination` message that fails validation still ends the session: it is delivered with the fields that could be read (`code` / durations `None` otherwise). ## Text-to-Speech diff --git a/assemblyai/__version__.py b/assemblyai/__version__.py index d6a282f..b775394 100644 --- a/assemblyai/__version__.py +++ b/assemblyai/__version__.py @@ -1 +1 @@ -__version__ = "1.10.12" +__version__ = "1.10.13" diff --git a/assemblyai/streaming/v3/_base.py b/assemblyai/streaming/v3/_base.py index b0f71d5..295b916 100644 --- a/assemblyai/streaming/v3/_base.py +++ b/assemblyai/streaming/v3/_base.py @@ -5,7 +5,8 @@ - Wire-format helpers (``_dump_model``, ``_parse_model``, ``_build_uri``, ``_build_headers``, parameter normalization, user-agent construction). -- Inbound message parsing (``_parse_message`` + ``_parse_event_type``). +- Inbound message parsing (``_read_event``, ``_parse_message``, + ``_parse_event_type``). - Connection-closed error mapping (``_build_connection_closed_error``). - The ``_BaseStreamingClient`` base class with shared init state and the ``on(...)`` handler-registration entrypoint. @@ -24,7 +25,7 @@ from urllib.parse import urlencode import websockets -from pydantic import BaseModel +from pydantic import BaseModel, ValidationError from assemblyai import __version__ @@ -71,6 +72,30 @@ def _parse_model(model_class: Type[_M], data: Dict[str, Any]) -> _M: return model_class.parse_obj(data) +def _int_or_none(value: Any) -> Optional[int]: + """Returns ``value`` when it is an integer, else ``None``.""" + if isinstance(value, int) and not isinstance(value, bool): + return value + return None + + +def _describe_parse_failure(exc: Exception) -> str: + """Names what failed to parse, for a log line. + + Leaves out the exception's own text. pydantic v2 puts the rejected input + in it, and for a ``Turn`` that input is the transcript. + """ + if isinstance(exc, ValidationError): + try: + return "; ".join( + f"{'.'.join(str(part) for part in error['loc'])}: {error['type']}" + for error in exc.errors() + ) + except Exception: + pass + return type(exc).__name__ + + def _normalize_min_turn_silence(params_dict: dict) -> dict: """Collapse `min_end_of_turn_silence_when_confident` into `min_turn_silence` so only one wire key is ever sent. Emits deprecation warnings.""" @@ -319,6 +344,91 @@ def _parse_message(cls, data: Dict[str, Any]) -> Optional[EventMessage]: return _parse_model(ErrorEvent, data) return None + @classmethod + def _read_event(cls, message_data: Any) -> Optional[EventMessage]: + """Decode and parse one inbound frame. No frame content makes it raise. + + Both read loops call this. An exception that left a read loop would + end the read thread or task without an ``Error`` event, and the + session would deliver nothing more while audio was still being sent. + + Returns ``None``, after logging a warning, for a frame to skip: one + that is not JSON, is not a JSON object, has an unsupported type, or + fails to parse. An ``Error`` or ``Termination`` message that fails to + parse is not skipped; see ``_terminal_event_from_unreadable``. + """ + try: + data = json.loads(message_data) + except Exception as exc: + # ``JSONDecodeError``; ``UnicodeDecodeError`` for a binary frame + # that is not UTF-8; ``RecursionError`` for JSON nested too deep. + logger.warning(f"Failed to decode message: {exc}") + return None + + if not isinstance(data, dict): + logger.warning( + "Ignoring message that is not a JSON object: %s", + type(data).__name__, + ) + return None + + # Logged only when it is a string: any other value is message content. + message_type = data.get("type") + if not isinstance(message_type, str): + message_type = None + + try: + message = cls._parse_message(data) + except Exception as exc: + # pydantic ``ValidationError``; pydantic v1 also lets some + # conversion errors through, such as ``OverflowError``. + logger.warning( + "Failed to parse %s message (%s)", + message_type, + _describe_parse_failure(exc), + ) + return cls._terminal_event_from_unreadable(data) + + if message is None: + logger.warning("Unsupported event type: %s", message_type) + + return message + + @classmethod + def _terminal_event_from_unreadable( + cls, data: Dict[str, Any] + ) -> Optional[EventMessage]: + """Rebuild an ``Error`` or ``Termination`` message that failed to parse. + + Both end the session. Skipping one would hide the failure, or the + end, that the server reported, so each is rebuilt from the fields + that can be read. Returns ``None`` for any other message. + """ + event_type = cls._parse_event_type(data.get("type")) + + if event_type == RealTimeEvents.Termination: + return TerminationEvent( + audio_duration_seconds=_int_or_none(data.get("audio_duration_seconds")), + session_duration_seconds=_int_or_none( + data.get("session_duration_seconds") + ), + ) + + if event_type == RealTimeEvents.Error or ( + "type" not in data and "error" in data + ): + error = data.get("error") + return ErrorEvent( + error=( + error + if isinstance(error, str) and error + else "The server reported an error the client could not read" + ), + error_code=_int_or_none(data.get("error_code")), + ) + + return None + @staticmethod def _build_connection_closed_error( error: Union[ diff --git a/assemblyai/streaming/v3/async_client.py b/assemblyai/streaming/v3/async_client.py index 5e089f0..3704c8e 100644 --- a/assemblyai/streaming/v3/async_client.py +++ b/assemblyai/streaming/v3/async_client.py @@ -1,7 +1,6 @@ import asyncio import collections.abc import inspect -import json import logging from typing import Any, AsyncIterable, Callable, Dict, Iterable, Optional, Union @@ -408,13 +407,7 @@ async def _read_loop(self) -> None: await self._report_connection_closed(exc) return - try: - message_json = json.loads(message_data) - except json.JSONDecodeError as exc: - logger.warning(f"Failed to decode message: {exc}") - continue - - message = self._parse_message(message_json) + message = self._read_event(message_data) if isinstance(message, ErrorEvent): await self._report_server_error(message) @@ -422,8 +415,6 @@ async def _read_loop(self) -> None: await self._handle_warning(message) elif message: await self._handle_message(message) - else: - logger.warning(f"Unsupported event type: {message_json.get('type')}") async def _handle_message(self, message: EventMessage) -> None: # ``_handle_message`` is only reached from ``_read_loop``, which only diff --git a/assemblyai/streaming/v3/client.py b/assemblyai/streaming/v3/client.py index 1b47f0c..405fde7 100644 --- a/assemblyai/streaming/v3/client.py +++ b/assemblyai/streaming/v3/client.py @@ -1,5 +1,4 @@ import inspect -import json import logging import queue import threading @@ -313,13 +312,7 @@ def _read_message(self) -> None: self._report_connection_closed(exc) return - try: - message_json = json.loads(message_data) - except json.JSONDecodeError as exc: - logger.warning(f"Failed to decode message: {exc}") - continue - - message = self._parse_message(message_json) + message = self._read_event(message_data) if isinstance(message, ErrorEvent): self._report_server_error(message) @@ -327,8 +320,6 @@ def _read_message(self) -> None: self._handle_warning(message) elif message: self._handle_message(message) - else: - logger.warning(f"Unsupported event type: {message_json.get('type')}") def _handle_message(self, message: EventMessage) -> None: if isinstance(message, TerminationEvent): diff --git a/tests/unit/test_streaming.py b/tests/unit/test_streaming.py index 6e3bc0b..6bf7432 100644 --- a/tests/unit/test_streaming.py +++ b/tests/unit/test_streaming.py @@ -32,10 +32,12 @@ ) from assemblyai.streaming.v3._base import _build_uri, _dump_model_json from assemblyai.streaming.v3.models import ( + ErrorEvent, HeartbeatEvent, KeepAlive, SilenceEvent, TerminateSession, + TerminationEvent, UpdateConfiguration, ) @@ -2245,6 +2247,233 @@ def bad_warning_handler(self_, w): client.disconnect() +_VALID_TURN = { + "type": "Turn", + "turn_order": 2, + "turn_is_formatted": True, + "end_of_turn": True, + "transcript": "after", + "end_of_turn_confidence": 0.9, + "words": [], +} +_TERMINATION = { + "type": "Termination", + "audio_duration_seconds": 1, + "session_duration_seconds": 1, +} +_BASE_LOGGER = "assemblyai.streaming.v3._base" + +# Frames the client cannot read. Each one used to raise out of the read loop. +_UNREADABLE_FRAMES = { + # A Turn the model rejects: null where a number is required. + "turn-null-field": json.dumps( + {**_VALID_TURN, "turn_order": 1, "end_of_turn_confidence": None} + ), + # A Begin without its required fields. + "begin-missing-fields": json.dumps({"type": "Begin"}), + # Valid JSON that is not an object. + "json-array": "[]", + "json-string": '"text"', + "json-number": "42", + "json-null": "null", + # A binary frame that is not UTF-8. + "binary-not-utf8": b"\x80\x81", + # JSON nested deeper than the decoder allows (RecursionError). + "json-nested-too-deep": "[" * 100_000 + "0" + "]" * 100_000, +} + + +@pytest.mark.parametrize( + "frame", _UNREADABLE_FRAMES.values(), ids=_UNREADABLE_FRAMES.keys() +) +def test_read_event_skips_unreadable_frame(caplog: pytest.LogCaptureFixture, frame): + # When: the shared reader gets a frame it cannot read + with caplog.at_level(logging.WARNING, logger=_BASE_LOGGER): + message = StreamingClient._read_event(frame) + + # Then: it returns nothing to dispatch and logs one warning, without raising + assert message is None + assert [record.levelno for record in caplog.records] == [logging.WARNING] + + +def test_read_event_skips_message_when_parser_raises_another_error( + mocker: MockFixture, caplog: pytest.LogCaptureFixture +): + # Given: a parser failure that is not a ValidationError. pydantic v1 lets + # some conversion errors through, e.g. OverflowError for a float field. + mocker.patch.object( + StreamingClient, + "_parse_message", + side_effect=OverflowError("int too large to convert to float"), + ) + + # When + with caplog.at_level(logging.WARNING, logger=_BASE_LOGGER): + message = StreamingClient._read_event(json.dumps(_VALID_TURN)) + + # Then: the message is skipped with a warning that names the error + assert message is None + assert "OverflowError" in caplog.text + + +def test_read_event_warning_leaves_out_message_contents( + caplog: pytest.LogCaptureFixture, +): + # Given: a Turn with fields missing. pydantic v2 puts the rejected input, + # here the transcript, in the text of its ValidationError. + frame = json.dumps({"type": "Turn", "transcript": "PRIVATE-TRANSCRIPT-TEXT"}) + + # When + with caplog.at_level(logging.WARNING, logger=_BASE_LOGGER): + message = StreamingClient._read_event(frame) + + # Then: the warning names the message type and the fields, not the contents + assert message is None + assert "Failed to parse Turn message" in caplog.text + assert "turn_order" in caplog.text + assert "PRIVATE-TRANSCRIPT-TEXT" not in caplog.text + + +@pytest.mark.parametrize( + "payload, expected_error, expected_code", + [ + # The auxiliary code is unreadable; the message itself is kept. + ( + {"type": "Error", "error": "quota exceeded", "error_code": "unknown"}, + "quota exceeded", + None, + ), + # The message is unreadable; the code is kept. + ( + {"type": "Error", "error": {"detail": "x"}, "error_code": 4002}, + "The server reported an error the client could not read", + 4002, + ), + # Nothing readable but the type. + ( + {"type": "Error"}, + "The server reported an error the client could not read", + None, + ), + # The untyped error envelope. + ( + {"error": ["x"]}, + "The server reported an error the client could not read", + None, + ), + ], + ids=["bad-code", "bad-message", "type-only", "untyped-envelope"], +) +def test_read_event_keeps_error_message_that_fails_to_parse( + payload, expected_error, expected_code +): + # When: an Error message fails validation + message = StreamingClient._read_event(json.dumps(payload)) + + # Then: it still comes back as an ErrorEvent, so the session ends with it + assert isinstance(message, ErrorEvent) + assert message.error == expected_error + assert message.error_code == expected_code + + +def test_read_event_keeps_termination_message_that_fails_to_parse(): + # When: a Termination message fails validation on one of its durations + message = StreamingClient._read_event( + json.dumps( + { + "type": "Termination", + "audio_duration_seconds": "invalid", + "session_duration_seconds": 13, + } + ) + ) + + # Then: it still comes back as a TerminationEvent, with the duration that + # could be read and without the one that could not + assert isinstance(message, TerminationEvent) + assert message.audio_duration_seconds is None + assert message.session_duration_seconds == 13 + + +@pytest.mark.parametrize( + "frame", + [ + _UNREADABLE_FRAMES["turn-null-field"], + _UNREADABLE_FRAMES["json-array"], + _UNREADABLE_FRAMES["binary-not-utf8"], + ], + ids=["turn-null-field", "json-array", "binary-not-utf8"], +) +def test_unreadable_message_does_not_kill_read_thread(mocker: MockFixture, frame): + # Given: one message the client cannot read, followed by a valid Turn and + # a Termination event. If the failure escapes the read loop, the read + # thread dies before the later messages and nothing reports it. + fake_ws = _FakeWebSocket( + recv_script=[frame, json.dumps(_VALID_TURN), json.dumps(_TERMINATION)] + ) + mocker.patch( + "assemblyai.streaming.v3.client.websocket_connect", + return_value=fake_ws, + ) + turns = [] + terminations = [] + errors = [] + + client = StreamingClient( + StreamingClientOptions(api_key="test", api_host="api.example.com") + ) + client.on(StreamingEvents.Turn, lambda c, e: turns.append(e.transcript)) + client.on(StreamingEvents.Termination, lambda c, e: terminations.append(e)) + client.on(StreamingEvents.Error, lambda c, e: errors.append(e)) + + # When: connect; the read thread meets the unreadable message first + _connect_and_wait(client, _default_params()) + + # Then: the read thread skipped it and delivered the Turn and the + # Termination that followed. + assert turns == ["after"] + assert len(terminations) == 1 + assert errors == [] + assert client._stop_event.is_set() + assert not client._read_thread.is_alive() + + client.disconnect() + + +def test_error_message_that_fails_to_parse_still_ends_session(mocker: MockFixture): + # Given: an Error message with an unreadable code, and a server that does + # not close the socket after it. Skipping the message would leave the + # session open with the failure unreported. + fake_ws = _FakeWebSocket( + recv_script=[ + json.dumps( + {"type": "Error", "error": "quota exceeded", "error_code": "unknown"} + ) + ] + ) + mocker.patch( + "assemblyai.streaming.v3.client.websocket_connect", + return_value=fake_ws, + ) + errors = [] + + client = StreamingClient( + StreamingClientOptions(api_key="test", api_host="api.example.com") + ) + client.on(StreamingEvents.Error, lambda c, e: errors.append(e)) + + # When + _connect_and_wait(client, _default_params()) + + # Then: the error reached the handler and the session was torn down + assert [(str(e), e.code) for e in errors] == [("quota exceeded", None)] + assert client._stop_event.is_set() + assert not client._read_thread.is_alive() + assert fake_ws.close_call_count >= 1 + + client.disconnect() + + def test_client_connect_uses_configured_timeout(mocker: MockFixture): # Given: a client configured with a custom connect_timeout. actual_open_timeout = None diff --git a/tests/unit/test_streaming_async.py b/tests/unit/test_streaming_async.py index a98b50e..3f221fd 100644 --- a/tests/unit/test_streaming_async.py +++ b/tests/unit/test_streaming_async.py @@ -653,6 +653,91 @@ def good_handler(_client, warning): await client.disconnect() +_VALID_TURN = { + "type": "Turn", + "turn_order": 2, + "turn_is_formatted": True, + "end_of_turn": True, + "transcript": "after", + "end_of_turn_confidence": 0.9, + "words": [], +} + + +@pytest.mark.parametrize( + "frame", + [ + # A Turn the model rejects: null where a number is required. + json.dumps({**_VALID_TURN, "turn_order": 1, "end_of_turn_confidence": None}), + # Valid JSON that is not an object. + "[]", + # A binary frame that is not UTF-8. + b"\x80\x81", + ], + ids=["turn-null-field", "json-array", "binary-not-utf8"], +) +async def test_unreadable_message_does_not_kill_read_task(mocker: MockFixture, frame): + """A message the client cannot read must not propagate out of the read + task; it is skipped and the next message is delivered.""" + fake_ws = _FakeAsyncWebSocket() + _patch_connect(mocker, fake_ws) + + turns = [] + errors = [] + + client = AsyncStreamingClient( + StreamingClientOptions(api_key="test", api_host="api.example.com") + ) + client.on(StreamingEvents.Turn, lambda c, e: turns.append(e.transcript)) + client.on(StreamingEvents.Error, lambda c, e: errors.append(e)) + await client.connect(_default_params()) + + fake_ws.push_message(frame) + fake_ws.push_message(json.dumps(_VALID_TURN)) + + for _ in range(100): + if turns or client._read_task.done(): + break + await asyncio.sleep(0.01) + + assert turns == ["after"] + assert errors == [] + assert not client._read_task.done() + + await client.disconnect() + + +async def test_error_message_that_fails_to_parse_still_ends_session( + mocker: MockFixture, +): + """An Error message with an unreadable code must still reach the handler + and end the session, even when the server leaves the socket open.""" + fake_ws = _FakeAsyncWebSocket() + _patch_connect(mocker, fake_ws) + + errors = [] + + client = AsyncStreamingClient( + StreamingClientOptions(api_key="test", api_host="api.example.com") + ) + client.on(StreamingEvents.Error, lambda c, e: errors.append(e)) + await client.connect(_default_params()) + + fake_ws.push_message( + json.dumps( + {"type": "Error", "error": "quota exceeded", "error_code": "unknown"} + ) + ) + + await _wait_for_tasks(client) + + assert [(str(e), e.code) for e in errors] == [("quota exceeded", None)] + assert client._stop_event.is_set() + assert fake_ws.close_call_count >= 1 + + await client.disconnect() + + async def test_stream_before_connect_raises_runtime_error(): """``stream()`` called before ``connect()`` must raise RuntimeError rather than silently dropping data. Silent drop would diverge from the sync client