The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): stdio transport shares the JSON-RPC serialization guard with WS (#92506 follow-up)
teknium11ccd1b3e4155
diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.pyindex cf41edb3c29..4774f97125c 100644--- a/tests/tui_gateway/test_tui_gateway_server.py+++ b/tests/tui_gateway/test_tui_gateway_server.py@@ -1178,6 +1178,24 @@ def test_write_json_returns_false_on_broken_pipe(monkeypatch):assert server.write_json({"ok": True}) is False+def test_write_json_unserializable_payload_becomes_error_frame(monkeypatch, caplog):+ """The stdio twin of the WS guard (#92506): an unserializable result must reach the Ink TUI /+ stdio bridge as a JSON-RPC error frame with the original id plus a log line, not kill the pool+ worker silently while the client waits forever."""+ import datetime+ import logging++ out = _ChunkyStdout()+ monkeypatch.setattr(server, "_real_stdout", out)+ with caplog.at_level(logging.ERROR, logger="tui_gateway.transport"):+ assert server.write_json({"jsonrpc": "2.0", "id": "profiles",+ "result": {"created": datetime.datetime(2026, 8, 22)}}) is True+ frame = json.loads("".join(out.parts))+ assert frame["id"] == "profiles" and frame["error"]["code"] == -32603+ assert "datetime" in frame["error"]["message"]+ assert "frame serialization failed" in caplog.text++def test_write_json_drops_detached_ws_frames(monkeypatch):out = _ChunkyStdout()monkeypatch.setattr(server, "_real_stdout", out)diff --git a/tests/tui_gateway/test_tui_gateway_ws.py b/tests/tui_gateway/test_tui_gateway_ws.pyindex e6be864696c..42d3159695a 100644--- a/tests/tui_gateway/test_tui_gateway_ws.py+++ b/tests/tui_gateway/test_tui_gateway_ws.py@@ -268,7 +268,7 @@ def test_ws_transport_replies_with_error_for_unserializable_response(caplog):assert frame["error"]["message"].startswith("response serialization error")assert "datetime" in frame["error"]["message"]assert sent[1] == {"jsonrpc": "2.0", "id": "next", "result": {}}- assert caplog.text.count("ws frame serialization failed") == 2+ assert caplog.text.count("frame serialization failed") == 2def test_ws_transport_preserves_cross_batch_order():diff --git a/tui_gateway/transport.py b/tui_gateway/transport.pyindex 00c23bbb848..5b3820e5cd3 100644--- a/tui_gateway/transport.py+++ b/tui_gateway/transport.py@@ -80,6 +80,21 @@ def _raise_unless_peer_gone(exc: Exception, what: str) -> None:logger.debug("StdioTransport %s peer gone: %s", what, exc)+def serialize_frame(obj: dict, peer: str, log: logging.Logger) -> str:+ """``json.dumps`` the frame; an unserializable payload becomes a JSON-RPC error frame carrying+ the original id. Shared by every transport: without it the TypeError escaped from a pool+ worker (the executor swallows it), so the client waited forever with no log line (#92506)."""+ try:+ return json.dumps(obj, ensure_ascii=False)+ except (TypeError, ValueError) as exc:+ rid = obj.get("id") if isinstance(obj, dict) else None+ log.error("frame serialization failed peer=%s id=%s error_type=%s error=%s",+ peer, rid, type(exc).__name__, exc)+ fallback = {"jsonrpc": "2.0", "id": rid,+ "error": {"code": -32603, "message": f"response serialization error: {exc}"}}+ return json.dumps(fallback, ensure_ascii=False)++class StdioTransport:"""Writes JSON frames to a stream (usually ``sys.stdout``) resolved via a callable, so runtimemonkey-patches of the stream keep working."""@@ -92,9 +107,8 @@ class StdioTransport:def write(self, obj: dict) -> bool:"""Return ``True`` on success, ``False`` ONLY when the peer is gone (see :func:`_raise_unless_peer_gone`)."""- # Serialization is OUTSIDE the lock so a large payload can't block other threads' frames. A- # non-JSON-safe payload is a programming error: re-raise.- line = json.dumps(obj, ensure_ascii=False) + "\n"+ # Serialization is OUTSIDE the lock so a large payload can't block other threads' frames.+ line = serialize_frame(obj, "stdio", logger) + "\n"with self._lock:stream = self._stream_getter()try:diff --git a/tui_gateway/ws.py b/tui_gateway/ws.pyindex 40d946f1dc9..72c983fb82b 100644--- a/tui_gateway/ws.py+++ b/tui_gateway/ws.py@@ -17,6 +17,7 @@ from typing import Anyfrom tui_gateway import serverfrom agent.message_sanitization import _sanitize_surrogatesfrom tui_gateway.event_replay import replay_epoch+from tui_gateway.transport import serialize_frame_log = logging.getLogger(__name__)@@ -106,24 +107,10 @@ class WSTransport:# Socket writes need an async boundary: several batches can queue on the loop during a stall.self._send_lock = asyncio.Lock()- def _serialize_frame(self, obj: dict) -> str:- """``json.dumps`` the frame; an unserializable payload becomes a JSON-RPC error frame- carrying the original id. Without this the TypeError escaped from a pool worker (the- executor swallows it), so the client waited forever with no log line (#92506)."""- try:- return json.dumps(obj, ensure_ascii=False)- except (TypeError, ValueError) as exc:- rid = obj.get("id") if isinstance(obj, dict) else None- _log.error("ws frame serialization failed peer=%s id=%s error_type=%s error=%s",- self._peer, rid, type(exc).__name__, exc)- fallback = {"jsonrpc": "2.0", "id": rid,- "error": {"code": -32603, "message": f"response serialization error: {exc}"}}- return json.dumps(fallback, ensure_ascii=False)-def write(self, obj: dict) -> bool:if self._closed:return False- line = self._serialize_frame(obj)+ line = serialize_frame(obj, self._peer, _log)try:on_loop = asyncio.get_running_loop() is self._loopexcept RuntimeError:@@ -191,7 +178,7 @@ class WSTransport:return Falsewith self._token_lock:batch, self._pending_tokens = self._pending_tokens, []- batch.append(self._serialize_frame(obj))+ batch.append(serialize_frame(obj, self._peer, _log))await self._safe_send_many(batch)return not self._closed