The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui): revoke queued fanout frames when viewers detach
helix4uc8b0c544ee70
diff --git a/tests/tui_gateway/test_fanout_send_membership.py b/tests/tui_gateway/test_fanout_send_membership.pynew file mode 100644index 00000000000..66cb04346f9--- /dev/null+++ b/tests/tui_gateway/test_fanout_send_membership.py@@ -0,0 +1,202 @@+"""Session detach revokes queued fanout frames without closing a shared socket."""++import asyncio+import io+import json+import threading++import pytest++from tests.waiting import async_wait_until+from tui_gateway.transport import FanoutTransport, StdioTransport+from tui_gateway.ws import WSTransport+++def _event(text, session_id="session"):+ return {+ "jsonrpc": "2.0",+ "method": "event",+ "params": {+ "type": "message.delta",+ "session_id": session_id,+ "payload": {"text": text},+ },+ }+++class _Socket:+ def __init__(self, *held):+ self.frames = []+ self.entered = {text: asyncio.Event() for text in held}+ self.released = {text: asyncio.Event() for text in held}++ async def send_text(self, text):+ frame = json.loads(text)+ label = frame.get("params", {}).get("payload", {}).get("text")+ if label in self.entered:+ self.entered[label].set()+ await self.released[label].wait()+ self.frames.append(frame)+++def _idle(fanout):+ with fanout._lock:+ return not any(peer.writing for peer in fanout._peers)+++ "action",+ ["detach", "reattach", "close", "overflow", "overflow-reattach", "overflow-detach"],+)+async def test_detach_discards_batch_waiting_for_send_lock(monkeypatch, action):+ socket = _Socket()+ transport = WSTransport(socket, asyncio.get_running_loop())+ fanout = FanoutTransport(transport)+ other_session = FanoutTransport(transport)+ entered = asyncio.Event()+ send_many = transport._safe_send_many++ async def observed_send(lines, **kwargs):+ entered.set()+ await send_many(lines, **kwargs)++ monkeypatch.setattr(transport, "_safe_send_many", observed_send)+ # Keep another producer's buffered token in this exact captured send batch.+ monkeypatch.setattr(transport, "_arm_token_flush", lambda: None)+ buffered = _event("buffered", "other-session")+ reply = {"jsonrpc": "2.0", "id": "private-reply", "result": {"ok": True}}+ notice = _event("resume-required")+ await transport._send_lock.acquire()+ try:+ assert transport.write(buffered)+ assert fanout.write(_event("stale"))+ await asyncio.wait_for(entered.wait(), timeout=10)+ if action.startswith("overflow"):+ monkeypatch.setattr(fanout, "_MAX_PENDING_FRAMES", 2)+ for index in range(3):+ fanout.write(_event(str(index)), overflow=lambda _peer: notice)+ assert not fanout.contains(transport)+ if action == "overflow-reattach":+ assert fanout.attach(transport)+ assert fanout.write(_event("fresh"))+ elif action == "overflow-detach":+ assert not fanout.detach(transport)+ elif action == "close":+ fanout.close()+ else:+ assert fanout.detach(transport)+ if action == "reattach":+ assert fanout.attach(transport)+ assert fanout.write(_event("fresh"))+ assert other_session.write(_event("other", "other-session"))+ response = asyncio.create_task(transport.write_async(reply))+ transport._send_lock.release()+ assert await asyncio.wait_for(response, timeout=10)+ await async_wait_until(+ lambda: _idle(fanout) and _idle(other_session),+ what="both fanout writers drained",+ )+ expected = [buffered, reply, _event("other", "other-session")]+ if action in {"reattach", "overflow-reattach"}:+ expected.append(_event("fresh"))+ if action == "overflow":+ expected.append(notice)+ assert sorted(map(json.dumps, socket.frames)) == sorted(+ map(json.dumps, expected)+ )+ assert not transport.closed+ finally:+ fanout.close()+ other_session.close()+ if transport._send_lock.locked():+ transport._send_lock.release()+ transport.close()+ await async_wait_until(+ lambda: _idle(fanout) and _idle(other_session), what="fanout cleanup"+ )++[email protected]("reattach", [False, True])+async def test_detach_discards_unsent_tail_of_captured_batch(reattach):+ socket = _Socket("seed", "first")+ transport = WSTransport(socket, asyncio.get_running_loop())+ fanout = FanoutTransport(transport)+ reply = {"jsonrpc": "2.0", "id": "reply", "result": {"ok": True}}+ try:+ assert fanout.write(_event("seed"))+ await asyncio.wait_for(socket.entered["seed"].wait(), timeout=10)+ assert fanout.write(_event("first"))+ assert fanout.write(_event("stale-tail"))+ socket.released["seed"].set()+ await asyncio.wait_for(socket.entered["first"].wait(), timeout=10)+ assert fanout.detach(transport)+ if reattach:+ assert fanout.attach(transport)+ assert fanout.write(_event("fresh"))+ response = asyncio.create_task(transport.write_async(reply))+ socket.released["first"].set()+ assert await asyncio.wait_for(response, timeout=10)+ await async_wait_until(+ lambda: _idle(fanout), what="captured fanout batch drained"+ )+ # A send already handed to the socket can finish, but its unsent sibling cannot.+ expected = [_event("seed"), _event("first"), reply]+ if reattach:+ expected.append(_event("fresh"))+ assert sorted(map(json.dumps, socket.frames)) == sorted(+ map(json.dumps, expected)+ )+ assert not transport.closed+ finally:+ fanout.close()+ for released in socket.released.values():+ released.set()+ transport.close()+ await async_wait_until(lambda: _idle(fanout), what="fanout cleanup")++[email protected]("reattach", [False, True])+async def test_sync_peer_discards_unsent_tail_of_captured_batch(reattach):+ entered = {text: threading.Event() for text in ("seed", "first")}+ released = {text: threading.Event() for text in entered}++ class GatedStream(io.StringIO):+ def write(self, text):+ label = json.loads(text)["params"]["payload"]["text"]+ if label in entered:+ entered[label].set()+ assert released[label].wait(timeout=10), (+ "test did not release the stream"+ )+ return super().write(text)++ stream = GatedStream()+ transport = StdioTransport(lambda: stream, threading.Lock())+ fanout = FanoutTransport(transport)+ try:+ assert fanout.write(_event("seed"))+ await async_wait_until(entered["seed"].is_set, what="first stdio send")+ assert fanout.write(_event("first"))+ assert fanout.write(_event("stale-tail"))+ released["seed"].set()+ await async_wait_until(entered["first"].is_set, what="captured stdio batch")+ assert fanout.detach(transport)+ if reattach:+ assert fanout.attach(transport)+ assert fanout.write(_event("fresh"))+ released["first"].set()+ await async_wait_until(lambda: _idle(fanout), what="stdio fanout drained")+ expected = [_event("seed"), _event("first")]+ if reattach:+ expected.append(_event("fresh"))+ assert list(map(json.loads, stream.getvalue().splitlines())) == expected+ assert not stream.closed+ finally:+ fanout.close()+ for gate in released.values():+ gate.set()+ await async_wait_until(lambda: _idle(fanout), what="stdio fanout cleanup")+ stream.close()diff --git a/tui_gateway/transport.py b/tui_gateway/transport.pyindex 5791cd210aa..6abcb8f4ab9 100644--- a/tui_gateway/transport.py+++ b/tui_gateway/transport.py@@ -171,6 +171,8 @@ class FanoutTransport:return False# Reuse the in-flight writer: reconnect cannot spawn more# threads or overtake a write already inside this socket.+ peer.pending.clear()+ peer.pending_bytes = 0peer.attached = Truepeer.generation += 1return True@@ -178,9 +180,10 @@ class FanoutTransport:return Truedef _remove(self, peer: _FanoutPeer) -> None:- # Membership lock held; identity fences a stale writer from removing- # a later attachment of the same transport.+ # Revoke captured batches as well as the queue. Failure cleanup must not+ # remove a later attachment of this same transport.peer.attached = False+ peer.generation += 1peer.pending.clear()peer.pending_bytes = 0if not peer.writing and peer in self._peers:@@ -189,9 +192,10 @@ class FanoutTransport:def detach(self, transport: Transport) -> bool:with self._lock:for peer in self._peers:- if peer.attached and peer.transport is transport:+ if peer.transport is transport:+ attached = peer.attachedself._remove(peer)- return True+ return attachedreturn Falsedef contains(self, transport: Transport) -> bool:@@ -205,6 +209,11 @@ class FanoutTransport:def has_transports(self, *, excluding: Transport | None = None) -> bool:return any(peer is not excluding for peer in self.transports())+ def _is_current(self, peer: _FanoutPeer, generation: int) -> bool:+ # Overflow notices may send while detached, but only for their own generation.+ with self._lock:+ return peer.generation == generation+def _drain(self, peer: _FanoutPeer) -> None:while True:with self._lock:@@ -227,17 +236,26 @@ class FanoutTransport:# 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_many = getattr(peer.transport, "write_many_async", None)+ write_current = getattr(peer.transport, "write_many_if_current_async", None)+ write_many = write_current or getattr(peer.transport, "write_many_async", None)loop = getattr(peer.transport, "_loop", 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_many([frame for frame, _size in batch]), loop)+ frames = [frame for frame, _size in batch]+ if write_current is not None:+ send = write_current(frames, lambda generation=generation: self._is_current(peer, generation))+ elif self._is_current(peer, generation):+ send = write_many(frames)+ else:+ continue+ future = safe_schedule_threadsafe(send, loop)ok = future is not None and future.result()else:- ok = all(peer.transport.write(frame) for frame, _size in batch)+ ok = all(not self._is_current(peer, generation) or peer.transport.write(frame)+ for frame, _size in batch)except Exception:logger.debug("fanout write failed; pruning peer", exc_info=True)ok = Falsediff --git a/tui_gateway/ws.py b/tui_gateway/ws.pyindex 4036a5fabe0..f6dd6118311 100644--- a/tui_gateway/ws.py+++ b/tui_gateway/ws.py@@ -13,7 +13,7 @@ import loggingimport socketimport threadingimport time-from typing import Any+from typing import Any, Callablefrom tui_gateway import serverfrom agent.message_sanitization import _sanitize_surrogates@@ -219,22 +219,30 @@ class WSTransport:async def write_many_async(self, frames: list[dict]) -> bool:"""``write_async`` for an ordered batch: buffered tokens, then *frames*, in one send batch."""+ return await self.write_many_if_current_async(frames, None)++ async def write_many_if_current_async(self, frames: list[dict], is_current: Callable[[], bool] | None) -> bool:+ """Recheck the batch's owner at each send without gating other producers' buffered tokens."""if self._closed:return Falsewith self._token_lock:batch, self._pending_tokens = self._pending_tokens, []+ unguarded_prefix = len(batch)batch.extend(serialize_frame(frame, self._peer, _log) for frame in frames)- await self._safe_send_many(batch)+ await self._safe_send_many(batch, is_current=is_current, unguarded_prefix=unguarded_prefix)return not self._closed- async def _safe_send_many(self, lines: list[str]) -> None:+ async def _safe_send_many(self, lines: list[str], *, is_current: Callable[[], bool] | None = None,+ unguarded_prefix: int = 0) -> None:"""Send one indivisible batch of pre-serialized frames in wire order."""async with self._send_lock:if self._closed:return- for line in lines:+ for index, line in enumerate(lines):if self._closed:return+ if is_current is not None and index >= unguarded_prefix and not is_current():+ returnpayload = _sanitize_ws_text(line)try:await asyncio.wait_for(self._ws.send_text(payload), timeout=_WS_SEND_DEADLINE_S)