diff --git a/core/tests/test_reply_funnel_off_loop.py b/core/tests/test_reply_funnel_off_loop.py index ae1e5006..fdbd3433 100644 --- a/core/tests/test_reply_funnel_off_loop.py +++ b/core/tests/test_reply_funnel_off_loop.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +import contextlib import json import threading import time @@ -11,10 +12,12 @@ from typing import Any import pytest +import websockets from tstd import daemon as daemon_module from tstd.code_feed import FeedWatcher from tstd.daemon import SCRUB_OFF_LOOP_CHARS, Daemon +from tstd.desktop.mock import MockDesktopDriver from tstd.logging import REDACTED from tstd.peer_policy import PeerView @@ -374,3 +377,195 @@ async def test_a_large_get_code_feed_reply_still_goes_through_the_funnel( assert len(reply) >= SCRUB_OFF_LOOP_CHARS assert len(threads) == 1 assert json.loads(reply)["type"] == "code_feed" + + +# ── Every connection at once (TD-5452) ────────────────────────────────── +# The session and machine list updates, cu_permissions and send_to_device sent +# to one connection after another: the second waited out the first's drain +# (1.005 s behind a reader draining 1.0 s). + + +def _first_is_slow(conns: list[Any]) -> tuple[_Conn, _Conn]: + slow, fast = conns + slow.drain = 1.0 # a phone that stopped reading, reached first + return slow, fast + + +def _two_viewers(daemon: Daemon) -> tuple[_Conn, _Conn]: + for conn in (_Conn(), _Conn()): + _viewer(daemon, conn) + return _first_is_slow(daemon.ws_server.viewer_connections()) + + +def _two_attached(daemon: Daemon) -> tuple[_Conn, _Conn]: + daemon.desktop_driver = MockDesktopDriver(permission_denied=True) + daemon._attached_clients["sess-1"] = {_Conn(), _Conn()} # type: ignore[arg-type] + return _first_is_slow(list(daemon._attached_clients["sess-1"])) + + +def _two_of_a_device(daemon: Daemon) -> tuple[_Conn, _Conn]: + for conn in (_Conn(), _Conn()): + daemon.ws_server._device_of[conn] = "dev-1" # type: ignore[index] + return _first_is_slow(daemon.ws_server.connections_of("dev-1")) + + +FAN_OUTS = { + "session list": (_two_viewers, lambda daemon: daemon.hub._on_rows(True, None)), + "machine list": (_two_viewers, lambda daemon: daemon.hub._on_machines()), + "cu_permissions": ( + _two_attached, + lambda daemon: daemon._emit_cu_permissions("sess-1", first_run=True), + ), + "send_to_device": ( + _two_of_a_device, + lambda daemon: daemon.ws_server.send_to_device("dev-1", lambda conn: "FRAME"), + ), +} + + +@pytest.mark.parametrize("path", list(FAN_OUTS)) +async def test_a_slow_reader_never_holds_up_the_next_connection(daemon: Daemon, path: str) -> None: + make, send = FAN_OUTS[path] + slow, fast = make(daemon) + sending = asyncio.create_task(send(daemon)) + await asyncio.sleep(0.1) + assert len(fast.sent) == 1 # on main: only once the slow reader's 1 s drain ended + assert len(slow.sent) == 1 + await sending + + +async def test_a_delivery_keeps_its_place_behind_older_frames(daemon: Daemon) -> None: + slow, fast = _Conn(drain=0.3), _Conn() + older = asyncio.create_task(daemon.ws_server.push(slow, "OLDER")) + await asyncio.sleep(0) + delivering = asyncio.create_task(daemon.ws_server.deliver([(slow, "NEW"), (fast, "NEW")])) + newer = asyncio.create_task(daemon.ws_server.push(slow, "NEWER")) + await asyncio.sleep(0.05) + assert fast.sent == ["NEW"] + await asyncio.gather(older, delivering, newer) + assert slow.sent == ["OLDER", "NEW", "NEWER"] + assert delivering.result() == 2 + + +async def test_a_cancelled_delivery_leaves_no_place_behind(daemon: Daemon) -> None: + slow, fast = _Conn(drain=5.0), _Conn() + delivering = asyncio.create_task(daemon.ws_server.deliver([(slow, "A"), (fast, "A")])) + await asyncio.sleep(0.05) + delivering.cancel() + with pytest.raises(asyncio.CancelledError): + await delivering + await asyncio.wait_for(daemon.ws_server.push(fast, "LATER"), 1) + assert fast.sent == ["A", "LATER"] + assert not daemon.ws_server._send_lines + + +async def test_send_to_device_skips_a_connection_that_closed(daemon: Daemon) -> None: + class _Closed(_Conn): + async def send(self, payload: str) -> None: + raise websockets.exceptions.ConnectionClosedOK(None, None) + + open_conn, closed = _Conn(), _Closed() + for conn in (open_conn, closed): + daemon.ws_server._device_of[conn] = "dev-1" # type: ignore[index] + assert await daemon.ws_server.send_to_device("dev-1", lambda conn: "FRAME") == 1 + assert open_conn.sent == ["FRAME"] + + +async def test_a_delivery_waits_behind_a_reply_being_scrubbed( + daemon: Daemon, monkeypatch: pytest.MonkeyPatch +) -> None: + _record_scrubs(monkeypatch, delay=0.2) + busy, other = _Conn(), _Conn() + big = _frame("old " + "x" * SCRUB_OFF_LOOP_CHARS) + + async def answer() -> None: + await busy.send(await daemon._scrub_reply(big, busy)) + + replying = asyncio.create_task(answer()) + await asyncio.sleep(0.05) # the scrub is under way + delivering = asyncio.create_task(daemon.ws_server.deliver([(busy, "NEW"), (other, "NEW")])) + await asyncio.sleep(0.05) + assert other.sent == ["NEW"] # not held up by the other connection's reply + await asyncio.gather(replying, delivering) + assert [frame[:20] for frame in busy.sent] == [big[:20], "NEW"] + + +async def test_a_frame_that_cannot_be_built_leaves_no_place_behind(daemon: Daemon) -> None: + # Review: places were taken while the frames were built, so one that + # raised left the connections before it a place never sent from. + first, second = _Conn(), _Conn() + for conn in (first, second): + daemon.ws_server._device_of[conn] = "dev-1" # type: ignore[index] + + def frame_for(conn: Any) -> str: + if conn is daemon.ws_server.connections_of("dev-1")[1]: + raise ValueError("no frame") + return "FRAME" + + with pytest.raises(ValueError, match="no frame"): + await daemon.ws_server.send_to_device("dev-1", frame_for) + assert not daemon.ws_server._send_lines + await asyncio.wait_for(daemon.ws_server.push(first, "LATER"), 1) + assert first.sent == ["LATER"] + + +@pytest.mark.parametrize("conns", [1, 2]) +async def test_a_delivery_cancelled_before_it_sends_leaves_no_place( + daemon: Daemon, monkeypatch: pytest.MonkeyPatch, conns: int +) -> None: + # Cancelled while every frame still waits behind a reply being scrubbed: + # on one connection the frame is sent in place, on more from tasks. + _record_scrubs(monkeypatch, delay=0.2) + targets = [_Conn() for _ in range(conns)] + big = _frame("x" * SCRUB_OFF_LOOP_CHARS) + + async def answer(conn: _Conn) -> None: + await conn.send(await daemon._scrub_reply(big, conn)) + + replying = [asyncio.create_task(answer(conn)) for conn in targets] + await asyncio.sleep(0.05) + delivering = asyncio.create_task(daemon.ws_server.deliver([(c, "NEW") for c in targets])) + await asyncio.sleep(0.01) + delivering.cancel() + with pytest.raises(asyncio.CancelledError): + await delivering + await asyncio.gather(*replying) + for conn in targets: + await asyncio.wait_for(daemon.ws_server.push(conn, "LATER"), 1) + assert [frame[:5] for frame in conn.sent] == [big[:5], "LATER"] + assert not daemon.ws_server._send_lines + + +async def test_a_delivery_cancelled_before_its_tasks_start_leaves_no_place( + daemon: Daemon, +) -> None: + # Re-review: cancelled before the gather's tasks ran, the places they + # would have left stayed in the lines. + first, second = _Conn(), _Conn() + delivering = asyncio.create_task(daemon.ws_server.deliver([(first, "X"), (second, "X")])) + await asyncio.sleep(0) # the delivery took its places and made its tasks + delivering.cancel() + with pytest.raises(asyncio.CancelledError): + await delivering + assert not daemon.ws_server._send_lines + assert first.sent == second.sent == [] + + +async def test_a_reader_that_stopped_reading_never_holds_up_anothers_pings( + daemon: Daemon, +) -> None: + # Review: the ping loop sent to one client after another, so a stuck + # reader held every other client's ping up by its drain. + slow, fast = _Conn(drain=1.0), _Conn() + for conn in (slow, fast): + daemon.ws_server._handshaken.add(conn) # type: ignore[arg-type] + daemon.ws_server._ping_interval = 0.05 + pinging = asyncio.create_task(daemon.ws_server._ping_loop()) + try: + await asyncio.sleep(0.4) + finally: + pinging.cancel() + with contextlib.suppress(asyncio.CancelledError): + await pinging + assert len(fast.sent) >= 4 # on main: 1 (the next only after the slow drain) + assert len(slow.sent) == 1 # no pings piled up behind its drain diff --git a/core/tstd/daemon.py b/core/tstd/daemon.py index bb7adf4c..6c30b022 100644 --- a/core/tstd/daemon.py +++ b/core/tstd/daemon.py @@ -2596,9 +2596,10 @@ async def _emit_cu_permissions(self, session_id: str, *, first_run: bool) -> Non """Push ``cu_permissions`` to clients attached to *session_id*.""" event = await self._cu_permissions_event(first_run=first_run) payload = event.model_dump_json() - for conn in list(self._attached_clients.get(session_id, set())): - with contextlib.suppress(websockets.exceptions.ConnectionClosed): - await self.ws_server.push(conn, payload) + # Every attached client at once (TD-5452): one that stopped reading + # never holds up the next. + attached = list(self._attached_clients.get(session_id, set())) + await self.ws_server.deliver((conn, payload) for conn in attached) async def _provider_probe( self, diff --git a/core/tstd/hub.py b/core/tstd/hub.py index a8cc1b9a..71a585ce 100644 --- a/core/tstd/hub.py +++ b/core/tstd/hub.py @@ -257,10 +257,17 @@ async def _on_rows(self, changed: bool, requester: Any) -> None: targets = self._ws.viewer_connections() if changed else [] if requester is not None and requester not in targets: targets.append(requester) - for connection in targets: - await self._send(connection, payload) + # Every viewer at once (TD-5452): one that stopped reading never holds + # up the next. + await self._deliver([(connection, payload) for connection in targets]) async def _on_machines(self) -> None: + frames = [] for connection in self._ws.viewer_connections(): peer = self._ws.peer_view(connection) - await self._send(connection, self.bridge.machine_list(include_address=peer.loopback)) + frames.append((connection, self.bridge.machine_list(include_address=peer.loopback))) + await self._deliver(frames) + + async def _deliver(self, frames: list[tuple[Any, str]]) -> None: + with contextlib.suppress(Exception): + await self._ws.deliver(frames) diff --git a/core/tstd/ws.py b/core/tstd/ws.py index 512b63e3..e83e4f7f 100644 --- a/core/tstd/ws.py +++ b/core/tstd/ws.py @@ -33,7 +33,7 @@ import json import secrets from collections import deque -from collections.abc import AsyncIterator, Awaitable, Callable +from collections.abc import AsyncIterator, Awaitable, Callable, Iterable from pathlib import Path from typing import Any, Literal @@ -393,14 +393,50 @@ async def send_to_device( A connection that closed meanwhile is skipped. Returns how many got it. """ - sent = 0 - for conn in self.connections_of(device_id): + return await self.deliver( + (conn, frame_for(conn)) for conn in self.connections_of(device_id) + ) + + async def deliver(self, frames: Iterable[tuple[Any, str]]) -> int: + """Send each connection its own frame, every connection at once (TD-5452). + + Sent one after another, a connection waited on each before it: on a + reader that stopped reading, the next one waited out its drain. Every + place is taken in one pass before any send, as a broadcast's are, and + each connection is sent to in its own task. A connection that closed + meanwhile is skipped. Returns how many got theirs. + """ + # Every frame first: a frame that can't be built leaves no place + # behind to hold up that connection's later frames. + built = list(frames) + return await self._send_all( + [(conn, self._take_place(conn), frame) for conn, frame in built] + ) + + async def _send_all(self, places: list[tuple[Any, _Place, str]]) -> int: + """Send each frame from its place, each connection in its own task.""" + + async def send_one(conn: Any, place: _Place, frame: str) -> bool: + place.sent = True try: - await self.push(conn, frame_for(conn)) + await self._await_turn(conn, place) + await conn.send(frame) except (websockets.exceptions.ConnectionClosed, OSError, RuntimeError): - continue - sent += 1 - return sent + return False + return True + + if len(places) == 1: + # One connection: sent in place, as a push is, with nothing to + # wait on but its own line. + return int(await send_one(*places[0])) + try: + results = await asyncio.gather(*(send_one(*entry) for entry in places)) + finally: + # A task cancelled before it started never left its place. + for conn, place, _frame in places: + if not place.sent: + self._leave(conn, place) + return sum(results) def device_kind_of(self, websocket: ServerConnection) -> DeviceKind | None: """The kind of the device record this connection authenticated with, if any. @@ -550,11 +586,33 @@ async def _ping_loop(self) -> None: resume. """ frame = build_ping() - while True: - await asyncio.sleep(self._ping_interval) - for conn in list(self._handshaken): - with contextlib.suppress(websockets.exceptions.ConnectionClosed): - await conn.send(frame) + # Each client is pinged in its own task (TD-5452): sent one after + # another, a reader that stopped reading held every later client's + # ping up by its drain, long enough for those clients to call the + # silence a zombie. A client still draining its last ping is skipped, + # so pings never pile up behind it. + pinging: dict[Any, asyncio.Task[None]] = {} + try: + while True: + await asyncio.sleep(self._ping_interval) + pinging = {conn: task for conn, task in pinging.items() if not task.done()} + for conn in list(self._handshaken): + if conn not in pinging: + pinging[conn] = asyncio.create_task(self._ping(conn, frame)) + finally: + for task in pinging.values(): + task.cancel() + + @staticmethod + async def _ping(conn: Any, frame: str) -> None: + try: + await conn.send(frame) + except (websockets.exceptions.ConnectionClosed, OSError, RuntimeError): + pass # closed meanwhile: it re-reads its state when it reconnects + except Exception: + # One client's failed ping never stops the others' (it ended the + # loop on main). + log.exception("app ping failed") async def broadcast( self, @@ -604,24 +662,7 @@ async def broadcast( if remote_payload is not None: frame = remote_payload places.append((conn, self._take_place(conn), frame)) - - async def send_one(conn: ServerConnection, place: _Place, frame: str) -> bool: - place.sent = True - try: - await self._await_turn(conn, place) - await conn.send(frame) - except (websockets.exceptions.ConnectionClosed, OSError, RuntimeError): - return False - return True - - try: - results = await asyncio.gather(*(send_one(*entry) for entry in places)) - finally: - # A task cancelled before it started never left its place. - for conn, place, _frame in places: - if not place.sent: - self._leave(conn, place) - return sum(results) + return await self._send_all(places) async def stop(self) -> None: """Stop the WebSocket server and close all connections. diff --git a/docs/tst-desk-backlog.md b/docs/tst-desk-backlog.md index 90870e44..a1a41b37 100644 --- a/docs/tst-desk-backlog.md +++ b/docs/tst-desk-backlog.md @@ -16231,6 +16231,14 @@ Cost: redacting at read time makes a read about ten times slower (a 352 KB feed **Size:** 1 · **Status:** Done +### TD-5452 — Server: one slow reader never holds up the next connection + +- [x] Session list and machine list updates, `cu_permissions` and a device's own frames (`send_to_device`) went to one connection after another, so each waited out the drain of the one before it: a viewer whose phone stopped reading held the next viewer's session list up by its whole drain (1.005 s behind a 1.0 s drain). They now go through `deliver`, which builds every frame, then takes every connection's place in its line in one pass, before any send, as a broadcast does (TD-5446), and sends to each connection in its own task. One connection is sent to in place, as a push is. +- [x] The app-level ping (TD-1716) went to one client after another too, so a reader that stopped reading held every other client's ping up by its drain, long enough for them to call the silence a zombie. Each client is now pinged in its own task, and one still draining its last ping is skipped, so pings never pile up behind it. +- [ ] A broadcast or delivery still returns once its slowest connection has its frame, so a producer that sends two in a row (two broadcasts, two session-list updates) waits out a slow reader between them, and the second reaches the other connections that much later. Returning sooner takes away the only thing that slows a producer to its slowest reader, so a reader that is alive but slow would collect frames without a bound. Open question (below in the pull request). + +**Size:** 1 · **Status:** In progress + ### TD-5453 — Shell: cookie 0.18.3 (GHSA-8wcq-xq25-7fhm) - [x] `cookie` moves from 0.18.2 to 0.18.3 in `shell/Cargo.lock`, which closes the Dependabot alert. Only Tauri uses the crate, and Tauri builds it without the `private` feature, so private cookie jars, which the advisory is about, were never compiled into the app.