The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui-gateway): answer gateway.ping while a WS handler blocks dispatch
Austin Pickett7154128fe19f
diff --git a/tests/tui_gateway/test_tui_gateway_ws.py b/tests/tui_gateway/test_tui_gateway_ws.pyindex 9301b1fda2a..adc2a890601 100644--- a/tests/tui_gateway/test_tui_gateway_ws.py+++ b/tests/tui_gateway/test_tui_gateway_ws.py@@ -167,6 +167,127 @@ def test_ws_ready_advertises_heartbeat_and_ping_is_inline(monkeypatch):}+def _slow_dispatch_harness(monkeypatch):+ """handle_ws over a scripted FakeWS whose ``slow`` RPC blocks inside dispatch() until released.++ Returns (inbound queue, sent frames, event log, release Event). Push ``None`` to disconnect."""+ monkeypatch.setattr(server, "_WS_ORPHAN_REAP_GRACE_S", 0)+ sent, log, release = [], [], threading.Event()++ def fake_dispatch(req, transport):+ method = req.get("method")+ log.append(f"dispatch:{method}")+ if method == "slow":+ release.wait(5)+ log.append(f"done:{method}")+ return {"jsonrpc": "2.0", "id": req.get("id"), "result": {"method": method}}++ def fake_close_sessions(transport, end_reason):+ log.append("teardown")+ return 0, 0++ monkeypatch.setattr(server, "dispatch", fake_dispatch)+ monkeypatch.setattr(server, "_close_sessions_for_transport", fake_close_sessions)+ inbound: asyncio.Queue = asyncio.Queue()++ class FakeWS:+ async def accept(self):+ pass++ async def send_text(self, line):+ sent.append(json.loads(line))++ async def receive_text(self):+ frame = await inbound.get()+ if frame is None:+ raise ws_mod._WebSocketDisconnect()+ return json.dumps(frame)++ async def close(self):+ pass++ return FakeWS(), inbound, sent, log, release+++async def _wait_for(predicate, timeout=2.0):+ deadline = asyncio.get_running_loop().time() + timeout+ while not predicate():+ if asyncio.get_running_loop().time() > deadline:+ return False+ await asyncio.sleep(0.01)+ return True+++def _rpc(req_id, method):+ return {"jsonrpc": "2.0", "id": req_id, "method": method, "params": {}}+++def test_ws_ping_is_answered_while_an_earlier_rpc_blocks_dispatch(monkeypatch):+ """#108325: a handler blocked for minutes (lock wait behind a long compaction, GIL-heavy turn) must not+ starve gateway.ping — the client's 45s heartbeat deadline would otherwise tear down a busy but healthy+ backend. Non-ping RPCs keep their serial arrival order."""+ ws, inbound, sent, log, release = _slow_dispatch_harness(monkeypatch)+ ids = lambda: [f.get("id") for f in sent if "id" in f] # noqa: E731++ async def scenario():+ task = asyncio.create_task(ws_mod.handle_ws(ws))+ try:+ for frame in (_rpc("r1", "slow"), _rpc("r2", "fast"), _rpc("heartbeat-1", "gateway.ping")):+ inbound.put_nowait(frame)+ ping_answered = await _wait_for(lambda: "heartbeat-1" in ids(), timeout=1.0)+ assert ping_answered, f"gateway.ping went unanswered while dispatch was busy; sent ids={ids()}"+ assert "done:slow" not in log and "dispatch:fast" not in log+ finally:+ release.set()+ assert await _wait_for(lambda: {"r1", "r2"} <= set(ids()))+ inbound.put_nowait(None)+ await asyncio.wait_for(task, 5)++ asyncio.run(scenario())+ assert log.index("done:slow") < log.index("dispatch:fast")+ assert ids().index("r1") < ids().index("r2")+++def test_ws_disconnect_teardown_waits_for_in_flight_dispatch(monkeypatch):+ """A client that drops while a handler runs must not have its sessions torn down under that handler, and+ frames it sent before dropping are still dispatched (as the serial read loop did)."""+ ws, inbound, sent, log, release = _slow_dispatch_harness(monkeypatch)++ async def scenario():+ task = asyncio.create_task(ws_mod.handle_ws(ws))+ inbound.put_nowait(_rpc("r1", "slow"))+ assert await _wait_for(lambda: "dispatch:slow" in log)+ inbound.put_nowait(_rpc("r2", "queued"))+ inbound.put_nowait(None)+ await asyncio.sleep(0.1)+ assert "teardown" not in log+ release.set()+ await asyncio.wait_for(task, 5)++ asyncio.run(scenario())+ assert log == ["dispatch:slow", "done:slow", "dispatch:queued", "done:queued", "teardown"]+++def test_ws_failed_reply_from_dispatcher_ends_the_connection(monkeypatch):+ """A response the dispatcher cannot send ends the connection even while the reader waits on the socket."""+ ws, inbound, sent, log, release = _slow_dispatch_harness(monkeypatch)+ real_send = type(ws).send_text++ async def send_text(self, line):+ if json.loads(line).get("id") == "r1":+ raise RuntimeError("peer gone")+ await real_send(self, line)++ monkeypatch.setattr(type(ws), "send_text", send_text)++ async def scenario():+ inbound.put_nowait(_rpc("r1", "fast"))+ await asyncio.wait_for(ws_mod.handle_ws(ws), 5)++ asyncio.run(scenario())+ assert log == ["dispatch:fast", "done:fast", "teardown"]++def test_ws_transport_serializes_concurrent_sends():active_sends = 0max_active_sends = 0diff --git a/tui_gateway/ws.py b/tui_gateway/ws.pyindex f21dfb24abc..653c1c3b6a9 100644--- a/tui_gateway/ws.py+++ b/tui_gateway/ws.py@@ -68,6 +68,11 @@ _WS_WRITE_TIMEOUT_S = 10.0# later frame and RPC reply parked behind the writer lock (#106369)._WS_SEND_DEADLINE_S = 30.0_WS_LOG_PAYLOAD_PREVIEW = 240+# Frames read ahead of a busy dispatcher. RPCs still dispatch one at a time in arrival order, but on a+# per-connection task so the read loop keeps answering gateway.ping while a handler blocks (a lock held+# by a long compaction, a GIL-heavy turn): the client's heartbeat deadline measures the transport, not+# handler latency (#108325). A full queue parks the reader — the old serial behaviour.+_WS_DISPATCH_QUEUE_MAX = 256# Per-token streaming frames are coalesced: buffered and flushed as a batch on a short timer instead# of waking the loop once per token (each wakeup competes with the agent turn for the GIL). Keep this@@ -307,6 +312,43 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:def _error(code: int, message: str, req_id: Any) -> dict:return {"jsonrpc": "2.0", "error": {"code": code, "message": message}, "id": req_id}+ pending: asyncio.Queue = asyncio.Queue(maxsize=_WS_DISPATCH_QUEUE_MAX)+ dispatcher: asyncio.Task | None = None+ stop = object() # queue sentinel; a JSON ``null`` frame parses to None, so None can't be it++ async def _dispatch_loop() -> None:+ """Dispatch queued requests one at a time in arrival order until the ``stop`` sentinel."""+ nonlocal dispatch_crashes+ while (req := await pending.get()) is not stop:+ req_id = req.get("id") if isinstance(req, dict) else None+ req_method = req.get("method") if isinstance(req, dict) else None+ # dispatch() may schedule long handlers on the pool; it returns None then and the worker+ # writes the response itself via transport.write (a separate thread, so that is the safe+ # path). Inline handlers return the response dict, written here from the loop.+ try:+ resp = await asyncio.to_thread(server.dispatch, req, transport)+ except Exception:+ dispatch_crashes += 1+ _log.exception("ws dispatch crash peer=%s id=%s method=%s", peer, req_id, req_method)+ await _reply(_error(-32603, "internal error", req_id), "send_failed_after_dispatch_crash",+ "ws dispatch-crash reply send failed peer=%s id=%s method=%s", peer, req_id, req_method)+ continue+ if resp is not None:+ await _reply(resp, "send_failed_after_response",+ "ws response send failed peer=%s id=%s method=%s", peer, req_id, req_method)++ async def _unless_dispatch_failed(aw: Any) -> Any:+ """Await *aw*, or raise _SendFailed once the dispatcher has ended on a reply it could not send."""+ assert dispatcher is not None+ step = asyncio.ensure_future(aw)+ try:+ await asyncio.wait({step, dispatcher}, return_when=asyncio.FIRST_COMPLETED)+ if step.done():+ return step.result()+ raise _SendFailed+ finally:+ step.cancel() # no-op once done+try:await (ws.accept(subprotocol=subprotocol) if subprotocol else ws.accept())disconnect_reason = "connected"@@ -349,10 +391,13 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:_log.error("ws ready frame send failed peer=%s", peer)return+ dispatcher = asyncio.create_task(_dispatch_loop())while True:try:- raw = await ws.receive_text()+ raw = await _unless_dispatch_failed(ws.receive_text())_note_dashboard_client_activity()+ except _SendFailed:+ raiseexcept _WebSocketDisconnect as exc:disconnect_reason = f"client_disconnect(code={getattr(exc, 'code', None)},reason={getattr(exc, 'reason', None)})"break@@ -372,29 +417,29 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:await _reply(_error(-32700, "parse error", None), "send_failed_after_parse_error","ws parse-error reply send failed peer=%s", peer)continue- req_id = req.get("id") if isinstance(req, dict) else None- req_method = req.get("method") if isinstance(req, dict) else None- if req_method == "gateway.ping":+ if isinstance(req, dict) and req.get("method") == "gateway.ping":+ req_id = req.get("id")await _reply({"jsonrpc": "2.0", "result": {"ok": True}, "id": req_id}, "send_failed_after_heartbeat","ws heartbeat reply send failed peer=%s id=%s", peer, req_id)continue- # dispatch() may schedule long handlers on the pool; it returns None then and the worker- # writes the response itself via transport.write (a separate thread, so that is the safe- # path). Inline handlers return the response dict, written here from the loop.- try:- resp = await asyncio.to_thread(server.dispatch, req, transport)- except Exception:- dispatch_crashes += 1- _log.exception("ws dispatch crash peer=%s id=%s method=%s", peer, req_id, req_method)- await _reply(_error(-32603, "internal error", req_id), "send_failed_after_dispatch_crash",- "ws dispatch-crash reply send failed peer=%s id=%s method=%s", peer, req_id, req_method)- continue- if resp is not None:- await _reply(resp, "send_failed_after_response",- "ws response send failed peer=%s id=%s method=%s", peer, req_id, req_method)+ await _unless_dispatch_failed(pending.put(req))except _SendFailed:passfinally:+ if dispatcher is not None:+ # Finish the in-flight handler and the frames read before the disconnect (as the serial read loop+ # did) before the teardown below parks this transport's sessions. A cancelled connection (server+ # shutdown) stops at once instead, as the read loop's cancelled await did.+ task = asyncio.current_task()+ if task is not None and task.cancelling():+ dispatcher.cancel()+ else:+ with contextlib.suppress(_SendFailed):+ await _unless_dispatch_failed(pending.put(stop))+ await asyncio.wait({dispatcher})+ failure = None if dispatcher.cancelled() else dispatcher.exception()+ if failure is not None and not isinstance(failure, _SendFailed):+ _log.error("ws dispatcher failed peer=%s", peer, exc_info=failure)reaped_sessions = detached_sessions = 0if transport is not None:server.unregister_live_transport(transport)