Skip to content

The agent that grows with you

fix(tui): the fanout drain sends a peer's queued backlog as one batch

Teknium324d57b03cc4
diff --git a/tests/tui_gateway/test_fanout_burst_batching.py b/tests/tui_gateway/test_fanout_burst_batching.py
new file mode 100644
index 00000000000..5a99ab58a42
--- /dev/null
+++ b/tests/tui_gateway/test_fanout_burst_batching.py
@@ -0,0 +1,74 @@
+"""The per-peer fanout drain sends what is queued as ONE batch on the socket's loop, not one
+cross-thread round trip per frame: a producer with no per-frame I/O (an in-process turn streaming
+tokens) otherwise outruns a healthy WebSocket and overflows its bounded mailbox
+(``session.replay_gap`` mid-turn). Real asyncio loop thread, real FanoutTransport; the socket
+only records frames and holds its first send until the test has queued a backlog."""
+import asyncio
+import threading
+
+from tests.waiting import wait_until
+from tui_gateway.transport import FanoutTransport
+
+
+class _LoopSocket:
+ """Duck-typed like WSTransport: its async sends complete on ``_loop``."""
+
+ def __init__(self, loop):
+ self._loop = loop
+ self.frames = []
+ self.sends = 0
+ self.first_send_started = threading.Event()
+ self.release = asyncio.Event()
+ self.closed = False
+
+ async def _send(self, frames):
+ self.sends += 1
+ self.first_send_started.set()
+ await self.release.wait()
+ self.frames.extend(frames)
+ return True
+
+ async def write_async(self, frame):
+ return await self._send([frame])
+
+ async def write_many_async(self, frames):
+ return await self._send(list(frames))
+
+ def write(self, frame):
+ raise AssertionError('a loop-bound socket is written from its loop, not the drain thread')
+
+ def abort(self):
+ self.closed = True
+
+ close = abort
+
+
+def _delta(index):
+ return {'jsonrpc': '2.0', 'method': 'event', 'params': {
+ 'type': 'message.delta', 'session_id': 's', 'payload': {'text': str(index)}}}
+
+
+def test_the_drain_sends_a_queued_backlog_as_one_batch():
+ loop = asyncio.new_event_loop()
+ runner = threading.Thread(target=loop.run_forever, daemon=True)
+ runner.start()
+ try:
+ socket = _LoopSocket(loop)
+ fanout = FanoutTransport(socket)
+ gaps = []
+ fanout.write(_delta(0), overflow=lambda transport: gaps.append(transport) or None)
+ assert socket.first_send_started.wait(10), 'the drain never reached the socket'
+ backlog = FanoutTransport._MAX_PENDING_FRAMES - 1
+ for index in range(1, backlog + 1):
+ fanout.write(_delta(index), overflow=lambda transport: gaps.append(transport) or None)
+ loop.call_soon_threadsafe(socket.release.set)
+ wait_until(lambda: len(socket.frames) == backlog + 1, timeout=30, what='the backlog delivered')
+ assert not gaps and not socket.closed
+ assert [f['params']['payload']['text'] for f in socket.frames] == [str(i) for i in range(backlog + 1)]
+ # One send in flight when the backlog formed, then the whole backlog in one batch (a
+ # per-frame drain makes ``backlog + 1`` sends, one loop round trip each).
+ assert socket.sends <= 2, f'{socket.sends} socket round trips for {backlog + 1} frames'
+ finally:
+ loop.call_soon_threadsafe(loop.stop)
+ runner.join(5)
+ loop.close()
diff --git a/tests/tui_gateway/test_protocol.py b/tests/tui_gateway/test_protocol.py
index 41697ed77d6..8bbf936ae57 100644
--- a/tests/tui_gateway/test_protocol.py
+++ b/tests/tui_gateway/test_protocol.py
@@ -410,14 +410,14 @@ def _two_window_session(server, sid):
from tui_gateway import server_requests
from tui_gateway.transport import FanoutTransport
- # The fanout awaits a WS peer's write_async on its loop; a peer without one is pruned on first write.
+ # The fanout awaits a WS peer's batched send (write_many_async) on its loop.
loop = asyncio.new_event_loop()
threading.Thread(target=loop.run_forever, daemon=True).start()
windows = (_silent_ws(), _silent_ws())
for window in windows:
- async def _write_async(obj, window=window):
- return window.write(obj)
- window._loop, window.write_async = loop, _write_async
+ async def _write_many_async(frames, window=window):
+ return all([window.write(frame) for frame in frames])
+ window._loop, window.write_many_async = loop, _write_many_async
server_requests.advertise(window, True)
_ws_session(server, sid, FanoutTransport(*windows))
return windows
diff --git a/tui_gateway/transport.py b/tui_gateway/transport.py
index 397c6ad17cb..5791cd210aa 100644
--- a/tui_gateway/transport.py
+++ b/tui_gateway/transport.py
@@ -216,23 +216,28 @@ class FanoutTransport:
self._remove(peer)
return
generation = peer.generation
- frame, size = peer.pending.popleft()
- peer.pending_bytes -= size
+ # Everything queued so far goes out as ONE batch: a producer with no per-frame I/O
+ # (an in-process turn streaming tokens) otherwise outruns one cross-thread round trip
+ # per frame and overflows a healthy socket's mailbox. In flight stays bounded: the
+ # next batch is taken only after this one is on the wire.
+ batch = list(peer.pending)
+ peer.pending.clear()
+ peer.pending_bytes = 0
try:
# Duck-typed on purpose: importing ``tui_gateway.ws`` here would pull
# ``tui_gateway.server`` in on this drain thread, racing any concurrent
# importer with a partially initialized module.
- write_async = getattr(peer.transport, "write_async", None)
+ write_many = getattr(peer.transport, "write_many_async", None)
loop = getattr(peer.transport, "_loop", None)
- if write_async is not None and loop is not None:
+ if write_many is not None and loop is not None:
# write() acknowledges buffered tokens/timeouts, not socket
# progress. Await the real send so WS cannot move an
# unbounded backlog underneath this bounded mailbox.
from agent.async_utils import safe_schedule_threadsafe
- future = safe_schedule_threadsafe(write_async(frame), loop)
+ future = safe_schedule_threadsafe(write_many([frame for frame, _size in batch]), loop)
ok = future is not None and future.result()
else:
- ok = peer.transport.write(frame)
+ ok = all(peer.transport.write(frame) for frame, _size in batch)
except Exception:
logger.debug("fanout write failed; pruning peer", exc_info=True)
ok = False
diff --git a/tui_gateway/ws.py b/tui_gateway/ws.py
index 45f30c574f5..18ac19e370e 100644
--- a/tui_gateway/ws.py
+++ b/tui_gateway/ws.py
@@ -193,6 +193,16 @@ class WSTransport:
await self._safe_send_many(batch)
return not self._closed
+ async def write_many_async(self, frames: list[dict]) -> bool:
+ """``write_async`` for an ordered batch: buffered tokens, then *frames*, in one send batch."""
+ if self._closed:
+ return False
+ with self._token_lock:
+ batch, self._pending_tokens = self._pending_tokens, []
+ batch.extend(serialize_frame(frame, self._peer, _log) for frame in frames)
+ await self._safe_send_many(batch)
+ return not self._closed
+
async def _safe_send_many(self, lines: list[str]) -> None:
"""Send one indivisible batch of pre-serialized frames in wire order."""
async with self._send_lock: