Skip to content

Fix concurrent async websocket use: single reader, per-request queues - #249

Merged
adamlogan73 merged 3 commits into
mainfrom
fix/async-reader-dispatch
Dec 3, 2026
Merged

adamlogan73 merged 3 commits into
mainfrom
fix/async-reader-dispatch

Conversation

@adamlogan73

@adamlogan73 adamlogan73 commented Sep 16, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Alternative to #248. Fixes concurrent use of AsyncWebsocketClient: several listeners, pings and one-shot commands on one connection.

  • Single reader task. A background task is the only thing that reads the socket. recv() calls no longer race each other's _async_recv(), so they can't split a fragmented message or starve each other.
  • Per-request queues. Each pending request id gets its own asyncio.Queue, created in send() before the payload goes out. Results, events and errors go only to their owner's queue, in arrival order. A subscription's result therefore always comes before its events, and a message wakes only the task waiting for it. This replaces a shared Condition that woke every waiter on every message.
  • Error routing. A failed result raises only in its own caller. A malformed event raises once and the subscription keeps running. A dead connection (or closing the client) fails every pending and later recv(), and the reader stops after a protocol error.
  • No leaks. One-shot requests are released once answered, timed out or cancelled. Subscriptions are released on unsubscribe, or if a listen_* body raises. Late events for a cancelled subscription are dropped.
  • Shared parsing, split storage. basewebsocket.py still parses messages by type, then hands them to _store_result / _store_event / _store_pong. The sync WebsocketClient implements those with its existing dicts, so its behavior is unchanged.

No public API changes. One edge case behaves differently: recv(msg_id) for an id with no pending request now raises ReceivingError instead of waiting forever.

Related

Test plan

  • New unit tests: a reply arriving before send() returns, routing by id, error isolation, fatal error fan-out, closing with pending waiters, cancellation and timeout cleanup, a malformed event on a subscription, a failed send
  • New cassette test recorded against a live HA: two listeners and a ping on one connection, each listener gets only its own events
  • Live run against the repo's HA container: two idle listeners for 45s with pings every 5s (past the 30s read timeout). All pings answered in under 1 ms, then each listener received its own event
  • uv run pytest: 191 passed, plus ty, ruff and pre-commit

🤖 Generated with Claude Code

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.
@adamlogan73
adamlogan73 force-pushed the fix/async-reader-dispatch branch from 2dae682 to 4f6d406 Compare December 3, 2026 05:47
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.
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.
@adamlogan73 adamlogan73 changed the title Fix async websocket reader starvation and dispatch races Fix concurrent async websocket use: single reader, per-request queues Dec 3, 2026
@adamlogan73
adamlogan73 merged commit 32c3e75 into main Dec 3, 2026
5 checks passed
@adamlogan73
adamlogan73 deleted the fix/async-reader-dispatch branch December 3, 2026 06:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant