From 4f6d406de1163d4a4c8a0ce52c68b5618358e136 Mon Sep 17 00:00:00 2001 From: Adam Logan Date: Tue, 15 Sep 2026 18:11:02 -0700 Subject: [PATCH 1/3] Fix async websocket reader starvation and dispatch races Replace the racing-recv() polling loop with a single background reader task that is the only thing allowed to touch the socket. recv() calls now wait on a shared Condition and get notified per dispatched message, instead of each concurrently calling _async_recv() and starving each other. Errors are routed to the specific msg_id they belong to when attributable, and broadcast to all waiters only when the connection itself is dead. Enable nimax id-aware WebSocket replay gating so test cassettes correctly model concurrent, out-of-order request/response correlation instead of relying on positional ordering. --- homeassistant_api/asyncwebsocket.py | 82 ++++++++++++++++++++++++----- pyproject.toml | 1 + 2 files changed, 69 insertions(+), 14 deletions(-) diff --git a/homeassistant_api/asyncwebsocket.py b/homeassistant_api/asyncwebsocket.py index d82f0fe..e0f6caa 100644 --- a/homeassistant_api/asyncwebsocket.py +++ b/homeassistant_api/asyncwebsocket.py @@ -1,5 +1,6 @@ from __future__ import annotations +import asyncio import contextlib import json import logging @@ -54,6 +55,7 @@ class AsyncWebsocketClient(BaseWebsocketClient): _session: AsyncSession _ws: AsyncExtensionFromHTTP + _reader_task: asyncio.Task[None] def __init__( self, @@ -65,6 +67,9 @@ def __init__( ) -> None: super().__init__(api_url, token, max_size=max_size) self._session = session if session is not None else AsyncSession() + self._new_message = asyncio.Condition() + self._fatal_error: BaseException | None = None + self._id_errors: dict[int, BaseException] = {} async def __aenter__(self) -> Self: await self._session.__aenter__() @@ -74,8 +79,11 @@ async def __aenter__(self) -> Self: msg = "Server did not upgrade to WebSocket" raise ReceivingError(msg) self._ws = resp.extension + # Authenticate before starting the reader task: these messages have no "id" + # and aren't dispatched through it, so nothing else may read the socket yet. okay = await self.authentication_phase() logger.info("Authenticated with Home Assistant (%s)", okay.ha_version) + self._reader_task = asyncio.create_task(self._reader_loop()) await self.supported_features_phase() return self @@ -85,10 +93,50 @@ async def __aexit__( exc_value: BaseException | None, traceback: TracebackType | None, ) -> None: + self._reader_task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await self._reader_task await self._ws.close() del self._ws await self._session.__aexit__(exc_type, exc_value, traceback) + async def _reader_loop(self) -> None: + """ + Continuously read messages off the socket and dispatch them by id. + + This is the only task allowed to touch the socket directly, so reads can + never interleave or starve a waiting `recv()` call. + """ + while True: + try: + data = await self._async_recv() + except Exception as e: # noqa: BLE001 + # No message id is available yet, so there's no single owner to + # blame this on: the connection is dead for every pending recv(). + async with self._new_message: + self._fatal_error = e + self._new_message.notify_all() + return + await self._dispatch(data) + + async def _dispatch(self, data: dict[str, Any]) -> None: + """Hand a received message to `handle_recv`, routing any failure to its owner.""" + try: + self.handle_recv(data) + except Exception as e: # noqa: BLE001 + data_id = data.get("id") + async with self._new_message: + if isinstance(data_id, int): + # The message carried its own id, so only the caller waiting + # on that id needs to see the failure. + self._id_errors[data_id] = e + else: + self._fatal_error = e + self._new_message.notify_all() + return + async with self._new_message: + self._new_message.notify_all() + async def _async_send(self, data: dict[str, Any]) -> None: """Send a message to the websocket server.""" if data.get("type") != "auth": @@ -147,20 +195,26 @@ async def recv( msg_id: int, ) -> EventResponse | ResultResponse | PingResponse | None: """Receive a response to a message from the websocket server.""" - while True: - ## have we received a message with the id we're looking for? - if self._result_responses.get(msg_id) is not None: - return self._result_responses.pop(msg_id) - if self._event_responses.get(msg_id, []): - return self._event_responses[msg_id].pop(0) - if ( - self._ping_responses.get(msg_id) is not None - and self._ping_responses[msg_id].end is not None - ): - return self._ping_responses.pop(msg_id) - - ## if not, keep receiving messages until we do - self.handle_recv(await self._async_recv()) + async with self._new_message: + while True: + ## have we received a message with the id we're looking for? + if self._result_responses.get(msg_id) is not None: + return self._result_responses.pop(msg_id) + if self._event_responses.get(msg_id, []): + return self._event_responses[msg_id].pop(0) + if ( + self._ping_responses.get(msg_id) is not None + and self._ping_responses[msg_id].end is not None + ): + return self._ping_responses.pop(msg_id) + ## did our own request fail, or did the connection die outright? + if msg_id in self._id_errors: + raise self._id_errors.pop(msg_id) + if self._fatal_error is not None: + raise self._fatal_error + + ## if not, wait for the reader task to dispatch another message + await self._new_message.wait() async def recv_result(self, msg_id: int) -> ResultResponse: """Receive a ResultResponse, raising TypeError if the response is not a ResultResponse.""" diff --git a/pyproject.toml b/pyproject.toml index 74032a6..ee8acc5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -50,6 +50,7 @@ dev = [ [tool.nimax] cassette_library_dir = "tests/cassettes" match_on = ["method", "uri"] +ws_id_extractor = "id" [tool.pytest.ini_options] asyncio_mode = "auto" From 34b318c22327f89ba1f073d08c67bc38fab48176 Mon Sep 17 00:00:00 2001 From: Adam Logan Date: Wed, 2 Dec 2026 21:53:40 -0800 Subject: [PATCH 2/3] Route async websocket responses through per-request queues Replace the shared Condition (which woke every waiter on every message) with one asyncio.Queue per pending request id. Responses, events and errors land only in their owner's queue, in arrival order. Storage moves behind _store_result/_store_event/_store_pong hooks so the sync client keeps its dicts. Also fixes: replies arriving before send() returned were lost; per-request state leaked; recv() hung after the client closed or after a cancelled listen_* body; the reader kept reading after a protocol error. --- homeassistant_api/asyncwebsocket.py | 216 +++++++++++++++++++-------- homeassistant_api/basewebsocket.py | 26 ++-- homeassistant_api/websocket.py | 12 ++ tests/test_websocket.py | 220 ++++++++++++++++++++++++++++ 4 files changed, 403 insertions(+), 71 deletions(-) diff --git a/homeassistant_api/asyncwebsocket.py b/homeassistant_api/asyncwebsocket.py index e0f6caa..f2d9bb0 100644 --- a/homeassistant_api/asyncwebsocket.py +++ b/homeassistant_api/asyncwebsocket.py @@ -44,6 +44,7 @@ if TYPE_CHECKING: from collections.abc import AsyncGenerator + from collections.abc import Generator from datetime import datetime from types import TracebackType @@ -51,6 +52,19 @@ logger = logging.getLogger(__name__) +# What the reader task can hand to a waiting recv(): a response, or the error to raise. +_Inbound = ResultResponse | EventResponse | PingResponse | BaseException + +# Commands whose id keeps receiving events after its result, until unsubscribed. +_STREAMING_COMMANDS = frozenset( + { + "config_entries/subscribe", + "render_template", + "subscribe_events", + "subscribe_trigger", + }, +) + class AsyncWebsocketClient(BaseWebsocketClient): _session: AsyncSession @@ -67,11 +81,20 @@ def __init__( ) -> None: super().__init__(api_url, token, max_size=max_size) self._session = session if session is not None else AsyncSession() - self._new_message = asyncio.Condition() + # One inbox per pending request id. The reader task puts each response + # (or the error for it) in its owner's inbox, so a message only wakes + # the task waiting on that id. + self._inboxes: dict[int, asyncio.Queue[_Inbound]] = {} + self._streaming_ids: set[int] = set() + self._ping_starts: dict[int, int] = {} self._fatal_error: BaseException | None = None - self._id_errors: dict[int, BaseException] = {} async def __aenter__(self) -> Self: + # Start clean if this instance is re-entered after an earlier connection. + self._inboxes.clear() + self._streaming_ids.clear() + self._ping_starts.clear() + self._fatal_error = None await self._session.__aenter__() resp = await self._session.get(self.api_url) resp.raise_for_status() @@ -96,6 +119,10 @@ async def __aexit__( self._reader_task.cancel() with contextlib.suppress(asyncio.CancelledError): await self._reader_task + if self._fatal_error is None: + # Nothing will be read any more: wake every pending recv() instead of + # leaving it waiting forever. + self._fail_all(ReceivingError("WebSocket client closed")) await self._ws.close() del self._ws await self._session.__aexit__(exc_type, exc_value, traceback) @@ -113,29 +140,81 @@ async def _reader_loop(self) -> None: except Exception as e: # noqa: BLE001 # No message id is available yet, so there's no single owner to # blame this on: the connection is dead for every pending recv(). - async with self._new_message: - self._fatal_error = e - self._new_message.notify_all() + self._fail_all(e) return - await self._dispatch(data) + self._dispatch(data) + if self._fatal_error is not None: + return # a protocol error in that message: the connection is unusable - async def _dispatch(self, data: dict[str, Any]) -> None: + def _dispatch(self, data: dict[str, Any]) -> None: """Hand a received message to `handle_recv`, routing any failure to its owner.""" try: self.handle_recv(data) except Exception as e: # noqa: BLE001 data_id = data.get("id") - async with self._new_message: - if isinstance(data_id, int): - # The message carried its own id, so only the caller waiting - # on that id needs to see the failure. - self._id_errors[data_id] = e - else: - self._fatal_error = e - self._new_message.notify_all() + if not isinstance(data_id, int): + self._fail_all(e) + elif (inbox := self._inboxes.get(data_id)) is not None: + # The message carried its own id, so only the caller waiting + # on that id needs to see the failure. + inbox.put_nowait(e) + else: + logger.warning( + "Dropping error for unknown message id %s: %s", + data_id, + e, + ) + + def _fail_all(self, error: BaseException) -> None: + """Fail every pending recv(), and every later one, with a connection-level error.""" + self._fatal_error = error + for inbox in self._inboxes.values(): + inbox.put_nowait(error) + + def _deliver(self, msg_id: int, item: _Inbound) -> None: + """Put a response in the inbox of the request it answers.""" + inbox = self._inboxes.get(msg_id) + if inbox is None: + # e.g. an event still in flight when its subscription was cancelled + logger.debug("Dropping message for id %s with no pending request", msg_id) + return + inbox.put_nowait(item) + + def _forget(self, msg_id: int) -> None: + """Release everything held for a request that will get no more responses.""" + self._inboxes.pop(msg_id, None) + self._streaming_ids.discard(msg_id) + self._ping_starts.pop(msg_id, None) + + @contextlib.contextmanager + def _released_on_error(self, subscription_id: int) -> Generator[None, None, None]: + """ + Release a subscription's state if the ``listen_*`` body raises or is cancelled. + + Unsubscribing is skipped then, since the connection may be the problem; + events still in flight for the id are dropped. + """ + try: + yield + except BaseException: + self._forget(subscription_id) + raise + + def _store_result(self, msg_id: int, response: ResultResponse) -> None: + self._deliver(msg_id, response) + + def _store_event(self, msg_id: int, response: EventResponse) -> None: + self._deliver(msg_id, response) + + def _store_pong(self, msg_id: int, end_ns: int) -> None: + start = self._ping_starts.pop(msg_id, None) + if start is None: + logger.debug("Dropping pong for unknown ping id %s", msg_id) return - async with self._new_message: - self._new_message.notify_all() + self._deliver( + msg_id, + PingResponse(start=start, end=end_ns, id=msg_id, type="pong"), + ) async def _async_send(self, data: dict[str, Any]) -> None: """Send a message to the websocket server.""" @@ -172,49 +251,61 @@ async def send(self, msg_type: str, *, include_id: bool = True, **data: Any) -> data["id"] = self._request_id() data["type"] = msg_type - await self._async_send(data) + if "id" not in data: + await self._async_send(data) + return -1 # non-command messages don't have an id - if "id" in data: - if not isinstance(data["id"], int): - msg = f"Expected int for message id, got {type(data['id'])}" - raise TypeError(msg) - if data["type"] == "ping": - self._ping_responses[data["id"]] = PingResponse( - start=time.perf_counter_ns(), - id=data["id"], - type="pong", - ) - else: - self._event_responses[data["id"]] = [] - self._result_responses[data["id"]] = None - return data["id"] - return -1 # non-command messages don't have an id + msg_id = data["id"] + if not isinstance(msg_id, int): + msg = f"Expected int for message id, got {type(msg_id)}" + raise TypeError(msg) + # Register before sending: the reader task can dispatch the reply + # before send_payload() returns. + self._inboxes[msg_id] = asyncio.Queue() + if msg_type in _STREAMING_COMMANDS: + self._streaming_ids.add(msg_id) + if msg_type == "ping": + self._ping_starts[msg_id] = time.perf_counter_ns() + try: + await self._async_send(data) + except BaseException: + self._forget(msg_id) + raise + return msg_id async def recv( self, msg_id: int, ) -> EventResponse | ResultResponse | PingResponse | None: """Receive a response to a message from the websocket server.""" - async with self._new_message: - while True: - ## have we received a message with the id we're looking for? - if self._result_responses.get(msg_id) is not None: - return self._result_responses.pop(msg_id) - if self._event_responses.get(msg_id, []): - return self._event_responses[msg_id].pop(0) - if ( - self._ping_responses.get(msg_id) is not None - and self._ping_responses[msg_id].end is not None - ): - return self._ping_responses.pop(msg_id) - ## did our own request fail, or did the connection die outright? - if msg_id in self._id_errors: - raise self._id_errors.pop(msg_id) - if self._fatal_error is not None: - raise self._fatal_error - - ## if not, wait for the reader task to dispatch another message - await self._new_message.wait() + inbox = self._inboxes.get(msg_id) + if inbox is None: + if self._fatal_error is not None: + raise self._fatal_error + msg = f"No pending request with id {msg_id}" + raise ReceivingError(msg) + if inbox.empty() and self._fatal_error is not None: + raise self._fatal_error + + try: + item = await inbox.get() + except asyncio.CancelledError: + # e.g. a timeout around ping_latency(): nobody will read this reply. + # Subscriptions are released by unsubscribing instead. + if msg_id not in self._streaming_ids: + self._forget(msg_id) + raise + streaming = msg_id in self._streaming_ids + if isinstance(item, BaseException): + # A failed result ends the request; a bad event doesn't end a subscription. + if item is not self._fatal_error and ( + not streaming or isinstance(item, ResponseError) + ): + self._forget(msg_id) + raise item + if not streaming and isinstance(item, ResultResponse | PingResponse): + self._forget(msg_id) # single-shot request: nothing else will arrive + return item async def recv_result(self, msg_id: int) -> ResultResponse: """Receive a ResultResponse, raising TypeError if the response is not a ResultResponse.""" @@ -535,7 +626,8 @@ async def listen_events( print(event) """ subscription = await self._async_subscribe_events(event_type) - yield self._async_wait_for(subscription) + with self._released_on_error(subscription): + yield self._async_wait_for(subscription) await self._async_unsubscribe(subscription) async def _async_subscribe_events(self, event_type: str | None) -> int: @@ -585,11 +677,12 @@ async def listen_trigger( Woohoo! We can now listen to triggers in Python code! """ subscription = await self._async_subscribe_trigger(trigger, **trigger_fields) - yield ( - fired_trigger.variables - async for fired_trigger in self._async_wait_for(subscription) - if isinstance(fired_trigger, FiredTrigger) - ) + with self._released_on_error(subscription): + yield ( + fired_trigger.variables + async for fired_trigger in self._async_wait_for(subscription) + if isinstance(fired_trigger, FiredTrigger) + ) await self._async_unsubscribe(subscription) async def _async_subscribe_trigger( @@ -638,7 +731,7 @@ async def _async_unsubscribe(self, subcription_id: int) -> None: msg = "Expected None result for unsubscribe" raise ValueError(msg) finally: - self._event_responses.pop(subcription_id, None) + self._forget(subcription_id) async def get_config_entries(self) -> tuple[ConfigEntry, ...]: """ @@ -805,7 +898,8 @@ async def listen_config_entries( subscription = ( await self.recv_result(await self.send("config_entries/subscribe")) ).id - yield self._async_wait_for_config_entries(subscription) + with self._released_on_error(subscription): + yield self._async_wait_for_config_entries(subscription) await self._async_unsubscribe(subscription) async def _async_wait_for_config_entries( diff --git a/homeassistant_api/basewebsocket.py b/homeassistant_api/basewebsocket.py index 732a67c..94f7f35 100644 --- a/homeassistant_api/basewebsocket.py +++ b/homeassistant_api/basewebsocket.py @@ -8,7 +8,6 @@ from homeassistant_api.errors import ResponseError from homeassistant_api.models.websocket import ErrorResponse from homeassistant_api.models.websocket import EventResponse -from homeassistant_api.models.websocket import PingResponse from homeassistant_api.models.websocket import ResultResponse logger = logging.getLogger(__name__) @@ -21,9 +20,6 @@ class BaseWebsocketClient: token: str max_size: int _id_counter: int - _result_responses: dict[int, ResultResponse | None] - _event_responses: dict[int, list[EventResponse]] - _ping_responses: dict[int, PingResponse] def __init__(self, api_url: str, token: str, *, max_size: int = 2**24) -> None: parsed = urlparse.urlparse(api_url) @@ -38,9 +34,6 @@ def __init__(self, api_url: str, token: str, *, max_size: int = 2**24) -> None: self.max_size = max_size self._id_counter = 0 - self._result_responses = {} # id -> response - self._event_responses = {} # id -> [response, ...] - self._ping_responses = {} # id -> (sent, received) def __repr__(self) -> str: return f"{self.__class__.__name__}({self.api_url!r})" @@ -58,21 +51,34 @@ def handle_recv(self, data: dict[str, Any]) -> None: self.parse_response(data) def parse_response(self, data: dict[str, Any]) -> None: + """Parse a received message by type and hand it to the matching storage hook.""" data_id = cast("int", data["id"]) if data.get("type") == "pong": logger.info("Received pong message") - self._ping_responses[data_id].end = time.perf_counter_ns() + self._store_pong(data_id, time.perf_counter_ns()) elif data.get("type") == "result": logger.info("Received result message") if data.get("success"): - self._result_responses[data_id] = ResultResponse.model_validate(data) + self._store_result(data_id, ResultResponse.model_validate(data)) else: error_resp = ErrorResponse.model_validate(data) msg = f"[{error_resp.error.code}] {error_resp.error.message}" raise ResponseError(msg) elif data.get("type") == "event": logger.info("Received event message %s", data["event"]) - self._event_responses[data_id].append(EventResponse.model_validate(data)) + self._store_event(data_id, EventResponse.model_validate(data)) else: msg = f"Received unexpected message type: {data}" raise ReceivingError(msg) + + def _store_result(self, msg_id: int, response: ResultResponse) -> None: + """Make a successful result available to whoever waits on ``msg_id``.""" + raise NotImplementedError + + def _store_event(self, msg_id: int, response: EventResponse) -> None: + """Make an event available to whoever waits on subscription ``msg_id``.""" + raise NotImplementedError + + def _store_pong(self, msg_id: int, end_ns: int) -> None: + """Complete the ping ``msg_id``, which the pong arrived for at ``end_ns``.""" + raise NotImplementedError diff --git a/homeassistant_api/websocket.py b/homeassistant_api/websocket.py index f4ea894..e41ff8c 100644 --- a/homeassistant_api/websocket.py +++ b/homeassistant_api/websocket.py @@ -65,6 +65,18 @@ def __init__( ) -> None: super().__init__(api_url, token, max_size=max_size) self._session = session if session is not None else Session() + self._result_responses: dict[int, ResultResponse | None] = {} + self._event_responses: dict[int, list[EventResponse]] = {} + self._ping_responses: dict[int, PingResponse] = {} + + def _store_result(self, msg_id: int, response: ResultResponse) -> None: + self._result_responses[msg_id] = response + + def _store_event(self, msg_id: int, response: EventResponse) -> None: + self._event_responses[msg_id].append(response) + + def _store_pong(self, msg_id: int, end_ns: int) -> None: + self._ping_responses[msg_id].end = end_ns def __repr__(self) -> str: return f"{self.__class__.__name__}({self.api_url!r})" diff --git a/tests/test_websocket.py b/tests/test_websocket.py index da96302..3a4e9dc 100644 --- a/tests/test_websocket.py +++ b/tests/test_websocket.py @@ -1,5 +1,6 @@ """Unit tests for WebsocketClient, AsyncWebsocketClient error paths.""" +import asyncio from typing import Any import pytest @@ -185,3 +186,222 @@ def raise_runtime_error(*args: Any, **kwargs: Any) -> None: # noqa: ARG001 match="Unexpected response during authentication", ): await client.authentication_phase() + + +# ── AsyncWebsocketClient dispatch: per-request inboxes ────────────────────── + + +def make_async_client_with_replies( + monkeypatch: MonkeyPatch, + replies: dict[str, list[dict[str, Any]]], +) -> AsyncWebsocketClient: + """ + Create an AsyncWebsocketClient whose sends are answered immediately. + + Each sent message of a type in ``replies`` gets those messages dispatched, + with its id filled in, before ``_async_send`` returns: the fastest a reply + can possibly arrive from the reader task. + """ + client = make_async_client() + + async def fake_send(data: dict[str, Any]) -> None: + for reply in replies.get(data["type"], []): + client._dispatch({**reply, "id": data["id"]}) + + monkeypatch.setattr(client, "_async_send", fake_send) + return client + + +RESULT_OK = {"type": "result", "success": True, "result": None} +TEMPLATE_EVENT = {"type": "event", "event": {"result": "on", "listeners": {}}} + + +async def test_async_reply_before_send_returns(monkeypatch: MonkeyPatch) -> None: + """A reply dispatched before send() returns still reaches its caller.""" + client = make_async_client_with_replies(monkeypatch, {"get_config": [RESULT_OK]}) + msg_id = await client.send("get_config") + resp = await client.recv_result(msg_id) + assert resp.id == msg_id + assert msg_id not in client._inboxes # single-shot request is released + + +async def test_async_ping_reply_before_send_returns(monkeypatch: MonkeyPatch) -> None: + """A pong dispatched before send() returns completes the ping.""" + client = make_async_client_with_replies(monkeypatch, {"ping": [{"type": "pong"}]}) + pong = await client.recv_ping(await client.send("ping")) + assert pong.end is not None + assert pong.end >= pong.start + assert not client._inboxes + assert not client._ping_starts + + +async def test_async_streaming_keeps_inbox_until_unsubscribe( + monkeypatch: MonkeyPatch, +) -> None: + """A subscription receives its result, then events, until unsubscribed.""" + client = make_async_client_with_replies( + monkeypatch, + { + "render_template": [RESULT_OK, TEMPLATE_EVENT], + "unsubscribe_events": [RESULT_OK], + }, + ) + msg_id = await client.send("render_template", template="{{ 1 }}") + await client.recv_result(msg_id) + event = await client.recv_event(msg_id) + assert event.id == msg_id + assert msg_id in client._inboxes + await client._async_unsubscribe(msg_id) + assert not client._inboxes + assert not client._streaming_ids + + +async def test_async_responses_route_by_id(monkeypatch: MonkeyPatch) -> None: + """Each waiter gets only its own response, whatever order they arrive in.""" + client = make_async_client_with_replies(monkeypatch, {}) + first = await client.send("get_config") + second = await client.send("get_states") + waiters = [asyncio.create_task(client.recv_result(i)) for i in (first, second)] + await asyncio.sleep(0) + client._dispatch({**RESULT_OK, "id": second, "result": "second"}) + client._dispatch({**RESULT_OK, "id": first, "result": "first"}) + results = [r.result for r in await asyncio.gather(*waiters)] + assert results == ["first", "second"] + + +async def test_async_failed_result_raises_for_its_owner_only( + monkeypatch: MonkeyPatch, +) -> None: + """A failed result raises in its own waiter and leaves other waiters alone.""" + client = make_async_client_with_replies(monkeypatch, {}) + failing = await client.send("get_config") + other = await client.send("get_states") + client._dispatch( + { + "id": failing, + "type": "result", + "success": False, + "error": {"code": "not_found", "message": "nope"}, + }, + ) + with pytest.raises(ResponseError, match="not_found"): + await client.recv(failing) + assert failing not in client._inboxes + assert other in client._inboxes + assert client._fatal_error is None + + +async def test_async_fatal_error_reaches_every_waiter( + monkeypatch: MonkeyPatch, +) -> None: + """A connection-level error fails pending and later recv() calls.""" + client = make_async_client_with_replies(monkeypatch, {}) + ids = [await client.send("get_config"), await client.send("get_states")] + waiters = [asyncio.create_task(client.recv(i)) for i in ids] + await asyncio.sleep(0) + client._dispatch({"type": "result", "success": True}) # no id: protocol error + for waiter in waiters: + with pytest.raises(ReceivingError, match="without an id"): + await waiter + with pytest.raises(ReceivingError, match="without an id"): + await client.recv(ids[0]) + + +async def test_async_message_for_unknown_id_is_dropped( + monkeypatch: MonkeyPatch, +) -> None: + """A late event for a cancelled subscription is dropped, not stored.""" + client = make_async_client_with_replies(monkeypatch, {}) + client._dispatch({**TEMPLATE_EVENT, "id": 99}) + assert not client._inboxes + assert client._fatal_error is None + + +async def test_async_recv_unknown_id_raises() -> None: + """recv() for an id with no pending request raises instead of hanging.""" + client = make_async_client() + with pytest.raises(ReceivingError, match="No pending request"): + await client.recv(42) + + +async def test_async_cancelled_recv_releases_request(monkeypatch: MonkeyPatch) -> None: + """A recv() cancelled by a timeout releases its request's state.""" + client = make_async_client_with_replies(monkeypatch, {}) + msg_id = await client.send("ping") + with pytest.raises(TimeoutError): + async with asyncio.timeout(0.01): + await client.recv_ping(msg_id) + assert not client._inboxes + assert not client._ping_starts + + +async def test_async_cancelled_recv_keeps_subscription( + monkeypatch: MonkeyPatch, +) -> None: + """A cancelled recv() on a subscription leaves it for unsubscribe to release.""" + client = make_async_client_with_replies(monkeypatch, {}) + msg_id = await client.send("subscribe_events") + with pytest.raises(TimeoutError): + async with asyncio.timeout(0.01): + await client.recv(msg_id) + assert msg_id in client._inboxes + + +async def test_async_aexit_fails_pending_recv(monkeypatch: MonkeyPatch) -> None: + """Closing the client wakes pending recv() calls instead of leaving them hanging.""" + + class FakeWs: + async def next_payload(self) -> None: + await asyncio.Event().wait() # no message ever arrives + + async def close(self) -> None: + pass + + class FakeSession: + async def __aexit__(self, *args: object) -> None: + pass + + client = make_async_client_with_replies(monkeypatch, {}) + client._ws = FakeWs() # type: ignore[assignment] + client._session = FakeSession() # type: ignore[assignment] + client._reader_task = asyncio.create_task(client._reader_loop()) + msg_id = await client.send("get_config") + waiter = asyncio.create_task(client.recv(msg_id)) + await asyncio.sleep(0) + await client.__aexit__(None, None, None) + with pytest.raises(ReceivingError, match="client closed"): + await waiter + + +async def test_async_reader_stops_after_fatal_message(monkeypatch: MonkeyPatch) -> None: + """The reader stops at a connection-fatal message instead of reading on.""" + messages = [{"type": "result", "success": True}, {**RESULT_OK, "id": 1}] + client = make_async_client() + + async def fake_recv() -> dict[str, Any]: + return messages.pop(0) + + monkeypatch.setattr(client, "_async_recv", fake_recv) + await client._reader_loop() + assert isinstance(client._fatal_error, ReceivingError) + assert len(messages) == 1 # the message after the fatal one was never read + + +async def test_async_listen_body_error_releases_subscription( + monkeypatch: MonkeyPatch, +) -> None: + """If a listen_events body raises, the subscription's state is released.""" + client = make_async_client_with_replies( + monkeypatch, + {"subscribe_events": [RESULT_OK]}, + ) + + async def listen_and_fail() -> None: + async with client.listen_events("test_event"): + msg = "boom" + raise RuntimeError(msg) + + with pytest.raises(RuntimeError, match="boom"): + await listen_and_fail() + assert not client._inboxes + assert not client._streaming_ids From a10aa11b7e0f8734633652d958cbba2211fdcd53 Mon Sep 17 00:00:00 2001 From: Adam Logan Date: Wed, 2 Dec 2026 21:59:52 -0800 Subject: [PATCH 3/3] Add concurrency tests for async websocket dispatch Record the PR #248 scenario against a live Home Assistant: two event listeners and a ping share one connection, and each listener receives only its own events, in order. Also cover a malformed event leaving its subscription alive, and a failed send releasing its request state. --- ...t_async_concurrent_listeners_and_ping.json | 146 ++++++++++++++++++ tests/test_events.py | 36 +++++ tests/test_websocket.py | 29 ++++ 3 files changed, 211 insertions(+) create mode 100644 tests/cassettes/test_events/test_async_concurrent_listeners_and_ping.json diff --git a/tests/cassettes/test_events/test_async_concurrent_listeners_and_ping.json b/tests/cassettes/test_events/test_async_concurrent_listeners_and_ping.json new file mode 100644 index 0000000..c8a0592 --- /dev/null +++ b/tests/cassettes/test_events/test_async_concurrent_listeners_and_ping.json @@ -0,0 +1,146 @@ +{ + "http_interactions": [], + "websocket_sessions": [ + { + "uri": "ws://localhost:8123/api/websocket", + "protocol": null, + "frames": [ + { + "direction": "recv", + "type": "text", + "payload": "{\"type\":\"auth_required\",\"ha_version\":\"2026.4.3\"}" + }, + { + "direction": "send", + "type": "text", + "payload": "{\"access_token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJkMDE4YjQ4YzMyZTE0ODNhYjY2ZWQzOTZmYzg3ZDAyNiIsImlhdCI6MTY3ODU3NDUwMSwiZXhwIjoxOTkzOTM0NTAxfQ.fyhnfwpont4uE0gn46_Ut_pPmyn4QWv0MDaVAei2PPk\", \"type\": \"auth\"}" + }, + { + "direction": "recv", + "type": "text", + "payload": "{\"type\":\"auth_ok\",\"ha_version\":\"2026.4.3\"}" + }, + { + "direction": "send", + "type": "text", + "payload": "{\"features\": {}, \"id\": 1, \"type\": \"supported_features\"}" + }, + { + "direction": "recv", + "type": "text", + "payload": "{\"id\":1,\"type\":\"result\",\"success\":true,\"result\":null}" + }, + { + "direction": "send", + "type": "text", + "payload": "{\"event_type\": \"concurrent_a\", \"id\": 2, \"type\": \"subscribe_events\"}" + }, + { + "direction": "send", + "type": "text", + "payload": "{\"event_type\": \"concurrent_b\", \"id\": 3, \"type\": \"subscribe_events\"}" + }, + { + "direction": "recv", + "type": "text", + "payload": "{\"id\":2,\"type\":\"result\",\"success\":true,\"result\":null}" + }, + { + "direction": "recv", + "type": "text", + "payload": "{\"id\":3,\"type\":\"result\",\"success\":true,\"result\":null}" + }, + { + "direction": "send", + "type": "text", + "payload": "{\"id\": 4, \"type\": \"ping\"}" + }, + { + "direction": "recv", + "type": "text", + "payload": "{\"id\":4,\"type\":\"pong\"}" + }, + { + "direction": "send", + "type": "text", + "payload": "{\"event_type\": \"concurrent_b\", \"event_data\": {\"n\": 1}, \"id\": 5, \"type\": \"fire_event\"}" + }, + { + "direction": "recv", + "type": "text", + "payload": "{\"type\":\"event\",\"event\":{\"event_type\":\"concurrent_b\",\"data\":{\"n\":1},\"origin\":\"LOCAL\",\"time_fired\":\"2026-12-03T05:58:34.524053+00:00\",\"context\":{\"id\":\"01M8X7QC8WM269Z1J33V0HNN47\",\"parent_id\":null,\"user_id\":\"e85fc7b7b8924dc9b024ce90ad23799e\"}},\"id\":3}" + }, + { + "direction": "recv", + "type": "text", + "payload": "{\"id\":5,\"type\":\"result\",\"success\":true,\"result\":{\"context\":{\"id\":\"01M8X7QC8WM269Z1J33V0HNN47\",\"parent_id\":null,\"user_id\":\"e85fc7b7b8924dc9b024ce90ad23799e\"}}}" + }, + { + "direction": "send", + "type": "text", + "payload": "{\"event_type\": \"concurrent_a\", \"event_data\": {\"n\": 1}, \"id\": 6, \"type\": \"fire_event\"}" + }, + { + "direction": "recv", + "type": "text", + "payload": "{\"type\":\"event\",\"event\":{\"event_type\":\"concurrent_a\",\"data\":{\"n\":1},\"origin\":\"LOCAL\",\"time_fired\":\"2026-12-03T05:58:34.525167+00:00\",\"context\":{\"id\":\"01M8X7QC8XMXMTB7Q7BJ6DATD3\",\"parent_id\":null,\"user_id\":\"e85fc7b7b8924dc9b024ce90ad23799e\"}},\"id\":2}" + }, + { + "direction": "recv", + "type": "text", + "payload": "{\"id\":6,\"type\":\"result\",\"success\":true,\"result\":{\"context\":{\"id\":\"01M8X7QC8XMXMTB7Q7BJ6DATD3\",\"parent_id\":null,\"user_id\":\"e85fc7b7b8924dc9b024ce90ad23799e\"}}}" + }, + { + "direction": "send", + "type": "text", + "payload": "{\"event_type\": \"concurrent_b\", \"event_data\": {\"n\": 2}, \"id\": 7, \"type\": \"fire_event\"}" + }, + { + "direction": "recv", + "type": "text", + "payload": "{\"type\":\"event\",\"event\":{\"event_type\":\"concurrent_b\",\"data\":{\"n\":2},\"origin\":\"LOCAL\",\"time_fired\":\"2026-12-03T05:58:34.525523+00:00\",\"context\":{\"id\":\"01M8X7QC8XAKZP1800RGWQFB10\",\"parent_id\":null,\"user_id\":\"e85fc7b7b8924dc9b024ce90ad23799e\"}},\"id\":3}" + }, + { + "direction": "send", + "type": "text", + "payload": "{\"subscription\": 3, \"id\": 8, \"type\": \"unsubscribe_events\"}" + }, + { + "direction": "recv", + "type": "text", + "payload": "{\"id\":7,\"type\":\"result\",\"success\":true,\"result\":{\"context\":{\"id\":\"01M8X7QC8XAKZP1800RGWQFB10\",\"parent_id\":null,\"user_id\":\"e85fc7b7b8924dc9b024ce90ad23799e\"}}}" + }, + { + "direction": "send", + "type": "text", + "payload": "{\"event_type\": \"concurrent_a\", \"event_data\": {\"n\": 2}, \"id\": 9, \"type\": \"fire_event\"}" + }, + { + "direction": "recv", + "type": "text", + "payload": "{\"id\":8,\"type\":\"result\",\"success\":true,\"result\":null}" + }, + { + "direction": "recv", + "type": "text", + "payload": "{\"type\":\"event\",\"event\":{\"event_type\":\"concurrent_a\",\"data\":{\"n\":2},\"origin\":\"LOCAL\",\"time_fired\":\"2026-12-03T05:58:34.526302+00:00\",\"context\":{\"id\":\"01M8X7QC8YKDTHVVHVCVAFSKKK\",\"parent_id\":null,\"user_id\":\"e85fc7b7b8924dc9b024ce90ad23799e\"}},\"id\":2}" + }, + { + "direction": "send", + "type": "text", + "payload": "{\"subscription\": 2, \"id\": 10, \"type\": \"unsubscribe_events\"}" + }, + { + "direction": "recv", + "type": "text", + "payload": "{\"id\":9,\"type\":\"result\",\"success\":true,\"result\":{\"context\":{\"id\":\"01M8X7QC8YKDTHVVHVCVAFSKKK\",\"parent_id\":null,\"user_id\":\"e85fc7b7b8924dc9b024ce90ad23799e\"}}}" + }, + { + "direction": "recv", + "type": "text", + "payload": "{\"id\":10,\"type\":\"result\",\"success\":true,\"result\":null}" + } + ] + } + ] +} \ No newline at end of file diff --git a/tests/test_events.py b/tests/test_events.py index b7fbf23..6be5fa0 100644 --- a/tests/test_events.py +++ b/tests/test_events.py @@ -1,3 +1,4 @@ +import asyncio from datetime import datetime import pytest @@ -158,3 +159,38 @@ async def test_async_listen_trigger( trigger["trigger"]["now"], ).timestamp() == pytest.approx(future.timestamp(), abs=1) break + + +async def test_async_concurrent_listeners_and_ping( + async_websocket_client: AsyncWebsocketClient, +) -> None: + """ + Two listeners and a ping share one connection (the PR #248 scenario). + + Each listener gets only its own events, in order, and the ping completes + while both listeners are blocked waiting. + """ + client = async_websocket_client + received: dict[str, list[int]] = {"concurrent_a": [], "concurrent_b": []} + ready = {event_type: asyncio.Event() for event_type in received} + + async def listen(event_type: str) -> None: + async with client.listen_events(event_type) as events: + ready[event_type].set() + async for event in events: + assert isinstance(event, FiredEvent) + assert event.event_type == event_type + received[event_type].append(event.data["n"]) + if len(received[event_type]) == 2: + break + + listeners = [asyncio.create_task(listen(t)) for t in received] + await asyncio.gather(*(e.wait() for e in ready.values())) + + assert await asyncio.wait_for(client.ping_latency(), timeout=5) >= 0 + + for n in (1, 2): + for event_type in reversed(list(received)): + await client.fire_event(event_type, n=n) + await asyncio.wait_for(asyncio.gather(*listeners), timeout=5) + assert received == {"concurrent_a": [1, 2], "concurrent_b": [1, 2]} diff --git a/tests/test_websocket.py b/tests/test_websocket.py index 3a4e9dc..43c3f7f 100644 --- a/tests/test_websocket.py +++ b/tests/test_websocket.py @@ -5,6 +5,7 @@ import pytest from _pytest.monkeypatch import MonkeyPatch +from pydantic import ValidationError from homeassistant_api.asyncwebsocket import AsyncWebsocketClient from homeassistant_api.errors import ReceivingError @@ -405,3 +406,31 @@ async def listen_and_fail() -> None: await listen_and_fail() assert not client._inboxes assert not client._streaming_ids + + +async def test_async_bad_event_keeps_subscription(monkeypatch: MonkeyPatch) -> None: + """A malformed event raises once; the subscription keeps receiving.""" + client = make_async_client_with_replies(monkeypatch, {"subscribe_trigger": []}) + msg_id = await client.send("subscribe_trigger") + client._dispatch({"id": msg_id, "type": "event", "event": "not an event"}) + client._dispatch({**TEMPLATE_EVENT, "id": msg_id}) + with pytest.raises(ValidationError): + await client.recv(msg_id) + event = await client.recv_event(msg_id) + assert event.id == msg_id + assert msg_id in client._inboxes + + +async def test_async_failed_send_releases_request(monkeypatch: MonkeyPatch) -> None: + """If sending the payload fails, no state is kept for the request.""" + client = make_async_client() + + async def failing_send(data: dict[str, Any]) -> None: # noqa: ARG001 + msg = "socket gone" + raise ConnectionError(msg) + + monkeypatch.setattr(client, "_async_send", failing_send) + with pytest.raises(ConnectionError, match="socket gone"): + await client.send("ping") + assert not client._inboxes + assert not client._ping_starts