Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -628,6 +628,15 @@ async def recv_task(ws: aiohttp.ClientWebSocketResponse) -> None:
body=f"{msg.data=} {msg.extra=}",
)

if msg.type == aiohttp.WSMsgType.ERROR:
if closing_ws or self._session.closed:
return

# the heartbeat closes the socket when a ping goes unanswered,
# and that surfaces here rather than as a close frame.
# ws.exception() is the only place the reason survives.
raise APIConnectionError("ElevenLabs STT connection lost") from ws.exception()

if msg.type != aiohttp.WSMsgType.TEXT:
logger.warning("unexpected ElevenLabs STT message type %s", msg.type)
continue
Expand Down Expand Up @@ -743,6 +752,11 @@ async def _connect_ws(self) -> aiohttp.ClientWebSocketResponse:
self._session.ws_connect(
ws_url,
headers={AUTHORIZATION_HEADER: self._opts.api_key},
# without heartbeat, a silently dropped socket (a half-open TCP
# connection, no FIN/RST) is never noticed: recv_task parks on
# ws.receive() forever and the reconnect loop, which is
# exception-driven, never runs.
heartbeat=30.0,
),
self._conn_options.timeout,
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,11 @@ async def _connect_ws(self) -> aiohttp.ClientWebSocketResponse:
self._ensure_session().ws_connect(
ws_url,
headers={"Authorization": self._stt._authorization},
# without heartbeat, a silently dropped socket (a half-open TCP
# connection, no FIN/RST) is never noticed: the receive loop parks
# on ws.receive() forever and the reconnect loop, which is
# exception-driven, never runs.
heartbeat=30.0,
),
timeout=self._conn_options.timeout,
)
Expand Down Expand Up @@ -394,8 +399,12 @@ async def _recv_messages_task(self) -> None:
):
return
elif msg.type == aiohttp.WSMsgType.ERROR:
logger.error(f"Inworld STT WebSocket error: {self._ws.exception()}")
return
# the heartbeat closes the socket when a ping goes unanswered,
# and that surfaces here rather than as a close frame.
# ws.exception() is the only place the reason survives.
raise APIConnectionError(
"Inworld STT connection lost"
) from self._ws.exception()
except aiohttp.ClientError as e:
logger.error(f"WebSocket error while receiving: {e}")
raise
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -590,7 +590,13 @@ async def _connect_ws(self, timeout: float) -> aiohttp.ClientWebSocketResponse:
session = self._ensure_session()
# the config is sent once the stream acquires the connection, since the pool also
# hands back sockets it opened earlier
return await asyncio.wait_for(session.ws_connect(url, headers=headers), timeout)
# without heartbeat, a silently dropped socket (a half-open TCP
# connection, no FIN/RST) is never noticed: recv_task parks on
# ws.receive() forever and the reconnect loop, which is exception-driven,
# never runs.
return await asyncio.wait_for(
session.ws_connect(url, headers=headers, heartbeat=30.0), timeout
)

async def _close_ws(self, ws: aiohttp.ClientWebSocketResponse) -> None:
await ws.close()
Expand Down Expand Up @@ -844,6 +850,17 @@ async def recv_task(ws: aiohttp.ClientWebSocketResponse) -> None:
body=f"{msg.data=} {msg.extra=}",
)

if msg.type == aiohttp.WSMsgType.ERROR:
if closing_ws:
return

# the heartbeat closes the socket when a ping goes unanswered,
# and that surfaces here rather than as a close frame.
# ws.exception() is the only place the reason survives.
raise APIConnectionError(
"OpenAI Realtime STT connection lost"
) from ws.exception()

if msg.type != aiohttp.WSMsgType.TEXT:
logger.warning("unexpected OpenAI message type %s", msg.type)
continue
Expand Down
115 changes: 115 additions & 0 deletions tests/fake_ws.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
"""Fake aiohttp websockets for exercising STT plugins' connection handling.

`ParkedSocket` is the half-open case (#7900): writes succeed and nothing is ever
delivered. `HeartbeatTimeoutSocket` is the state aiohttp leaves a socket in when a
heartbeat ping goes unanswered. `FakeWSSession` stands in for the aiohttp session.
"""

from __future__ import annotations

import asyncio
import time
from collections.abc import AsyncIterator, Callable
from typing import Any

import aiohttp


async def wait_until(predicate: Callable[[], bool], *, timeout: float = 5.0) -> None:
deadline = time.monotonic() + timeout
while not predicate():
assert time.monotonic() < deadline, "timed out waiting for the stream"
await asyncio.sleep(0.01)


class _FakeSocket:
def __init__(self) -> None:
self.closed = False
self._response = type("obj", (object,), {"headers": {}})()

async def send_json(self, data: Any) -> None:
pass

async def send_str(self, data: str) -> None:
pass

async def receive(self) -> aiohttp.WSMessage:
raise NotImplementedError

async def __aiter__(self) -> AsyncIterator[aiohttp.WSMessage]:
# mirrors aiohttp: iteration stops once the socket reports a closing message
while True:
msg = await self.receive()
if msg.type in (
aiohttp.WSMsgType.CLOSE,
aiohttp.WSMsgType.CLOSING,
aiohttp.WSMsgType.CLOSED,
):
break
yield msg

async def close(self) -> None:
self.closed = True


class ParkedSocket(_FakeSocket):
"""Accepts writes and never delivers anything: the half-open case from the
client's point of view. `receive()` only returns once the socket is closed, and
the tests never let that happen."""

def __init__(self) -> None:
super().__init__()
self._closed = asyncio.Event()

async def receive(self) -> aiohttp.WSMessage:
await self._closed.wait()
raise AssertionError("the test should never let recv_task resume")

async def close(self) -> None:
await super().close()
self._closed.set()


class HeartbeatTimeoutSocket(_FakeSocket):
"""A socket whose heartbeat ping went unanswered.

aiohttp closes the connection itself, so this arrives as WSMsgType.ERROR rather
than as a close frame, and the reason lives only on `exception()`. After a few
ERROR frames it reports CLOSED, which is what aiohttp does on the next pass; a
recv loop that steps over the ERROR only recovers because of that.
"""

def __init__(self) -> None:
super().__init__()
self.receives = 0

def exception(self) -> BaseException:
return aiohttp.ServerTimeoutError("No PONG received after 15.0 seconds")

async def receive(self) -> aiohttp.WSMessage:
self.receives += 1
# yield, so a recv loop that steps over the error instead of ending fails the
# receive-count assertion rather than starving the event loop
await asyncio.sleep(0)
if self.receives > 3:
return aiohttp.WSMessage(aiohttp.WSMsgType.CLOSED, None, None)
return aiohttp.WSMessage(aiohttp.WSMsgType.ERROR, self.exception(), None)


class FakeWSSession:
"""Records `ws_connect` kwargs and hands out sockets from `make_socket`."""

def __init__(self, make_socket: Callable[[], _FakeSocket]) -> None:
self.closed = False
self.kwargs: list[dict[str, Any]] = []
self.sockets: list[_FakeSocket] = []
self._make_socket = make_socket

async def ws_connect(self, url: str, **kwargs: Any) -> _FakeSocket:
self.kwargs.append(kwargs)
ws = self._make_socket()
self.sockets.append(ws)
return ws

async def close(self) -> None:
self.closed = True
41 changes: 41 additions & 0 deletions tests/test_plugin_elevenlabs_stt.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
from livekit.plugins.elevenlabs import stt as elevenlabs_stt
from livekit.plugins.elevenlabs._utils import trace_id_from_headers

from .fake_ws import FakeWSSession, HeartbeatTimeoutSocket, ParkedSocket, wait_until

pytestmark = pytest.mark.plugin("elevenlabs")


Expand Down Expand Up @@ -763,3 +765,42 @@ async def handler(request: web.Request) -> web.Response:
assert exc_info.value.message == message
assert exc_info.value.body == parsed
assert requests == 1


def _halfopen_stream(session: FakeWSSession) -> elevenlabs_stt.SpeechStream:
stt_ = elevenlabs_stt.STT(
api_key="sk_test",
base_url="http://localhost:8000/v1",
http_session=session, # type: ignore[arg-type]
)
return stt_.stream(conn_options=DEFAULT_API_CONNECT_OPTIONS)


# -- half-open socket detection (#7900) --


@pytest.mark.asyncio
async def test_socket_is_opened_with_a_heartbeat() -> None:
"""aiohttp defaults `heartbeat` to None, so without it the read side of a
half-open socket parks forever and the reconnect, which only fires when
`recv_task` ends, never gets a turn."""
session = FakeWSSession(ParkedSocket)
stream = _halfopen_stream(session)
try:
await wait_until(lambda: len(session.kwargs) == 1)
assert session.kwargs[0].get("heartbeat") == 30.0
finally:
await stream.aclose()


@pytest.mark.asyncio
async def test_heartbeat_timeout_reconnects_without_spinning() -> None:
"""The ERROR frame a missed heartbeat produces has to end the recv loop and
request a reconnect, instead of being stepped over until aiohttp reports CLOSED."""
session = FakeWSSession(HeartbeatTimeoutSocket)
stream = _halfopen_stream(session)
try:
await wait_until(lambda: len(session.sockets) > 1)
assert session.sockets[0].receives == 1
finally:
await stream.aclose()
51 changes: 51 additions & 0 deletions tests/test_plugin_inworld_stt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""Unit tests for the Inworld STT plugin."""

from __future__ import annotations

import pytest

from livekit.agents import DEFAULT_API_CONNECT_OPTIONS
from livekit.plugins.inworld import stt as inworld_stt

from .fake_ws import FakeWSSession, HeartbeatTimeoutSocket, ParkedSocket, wait_until

pytestmark = pytest.mark.unit


def _halfopen_stream(session: FakeWSSession) -> inworld_stt.SpeechStream:
stt_ = inworld_stt.STT(
api_key="sk_test",
base_url="http://localhost:8000/",
http_session=session, # type: ignore[arg-type]
)
return stt_.stream(conn_options=DEFAULT_API_CONNECT_OPTIONS)


# -- half-open socket detection (#7900) --


@pytest.mark.asyncio
async def test_socket_is_opened_with_a_heartbeat() -> None:
"""aiohttp defaults `heartbeat` to None, so without it the read side of a
half-open socket parks forever and the reconnect, which only fires when
`recv_task` ends, never gets a turn."""
session = FakeWSSession(ParkedSocket)
stream = _halfopen_stream(session)
try:
await wait_until(lambda: len(session.kwargs) == 1)
assert session.kwargs[0].get("heartbeat") == 30.0
finally:
await stream.aclose()


@pytest.mark.asyncio
async def test_heartbeat_timeout_reconnects_without_spinning() -> None:
"""The ERROR frame a missed heartbeat produces has to end the recv loop and
request a reconnect, instead of being stepped over until aiohttp reports CLOSED."""
session = FakeWSSession(HeartbeatTimeoutSocket)
stream = _halfopen_stream(session)
try:
await wait_until(lambda: len(session.sockets) > 1)
assert session.sockets[0].receives == 1
finally:
await stream.aclose()
42 changes: 42 additions & 0 deletions tests/test_plugin_openai_stt_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
from livekit.agents.stt import SpeechEvent, SpeechEventType
from livekit.plugins.openai import stt

from .fake_ws import FakeWSSession, HeartbeatTimeoutSocket, ParkedSocket, wait_until

pytestmark = pytest.mark.unit


Expand Down Expand Up @@ -811,3 +813,43 @@ async def test_file_transcription_earlier_model_keeps_singular_language() -> Non

assert 'name="language"\r\n\r\nen' in body
assert 'name="languages[]"' not in body


def _halfopen_stream(session: FakeWSSession) -> stt.SpeechStream:
stt_ = stt.STT(
api_key="sk-test",
base_url="http://localhost:8000/v1",
client=openai.AsyncClient(api_key="sk-test", base_url="http://localhost:8000/v1"),
)
stt_._session = session # type: ignore[assignment]
return stt_.stream(conn_options=DEFAULT_API_CONNECT_OPTIONS)


# -- half-open socket detection (#7900) --


@pytest.mark.asyncio
async def test_socket_is_opened_with_a_heartbeat() -> None:
"""aiohttp defaults `heartbeat` to None, so without it the read side of a
half-open socket parks forever and the reconnect, which only fires when
`recv_task` ends, never gets a turn."""
session = FakeWSSession(ParkedSocket)
stream = _halfopen_stream(session)
try:
await wait_until(lambda: len(session.kwargs) == 1)
assert session.kwargs[0].get("heartbeat") == 30.0
finally:
await stream.aclose()


@pytest.mark.asyncio
async def test_heartbeat_timeout_reconnects_without_spinning() -> None:
"""The ERROR frame a missed heartbeat produces has to end the recv loop and
request a reconnect, instead of being stepped over until aiohttp reports CLOSED."""
session = FakeWSSession(HeartbeatTimeoutSocket)
stream = _halfopen_stream(session)
try:
await wait_until(lambda: len(session.sockets) > 1)
assert session.sockets[0].receives == 1
finally:
await stream.aclose()