The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(relay): _read_loop fails in-flight pending futures on any exit
Victor Kyriazakosd2975f4219bc
diff --git a/gateway/relay/ws_transport.py b/gateway/relay/ws_transport.pyindex b0e067fc162..2eebdd32115 100644--- a/gateway/relay/ws_transport.py+++ b/gateway/relay/ws_transport.py@@ -809,47 +809,64 @@ class WebSocketRelayTransport:assert self._ws is not Nonebuf = ""try:- async for chunk in self._ws:- buf += chunk if isinstance(chunk, str) else chunk.decode("utf-8")- # Newline-delimited frames; keep any trailing partial line.- *lines, buf = buf.split("\n")- for line in lines:- if line.strip():- await self._handle_frame(line)- except asyncio.CancelledError:- raise- except Exception as exc: # noqa: BLE001 - log + let the task end; reconnection handled below- # Phase 7 Unit 7d-B: detect a 4401 (unauthorized) close. After a prior- # successful handshake this is a REVOCATION (opt-out / deprovision) —- # the per-gateway secret is gone, so reconnecting is futile. Latch a- # terminal "auth revoked" state and DON'T re-dial. Before any- # successful handshake a 4401 stays retryable (cold-start race).- if self._close_code_of(exc) == _RELAY_UNAUTHORIZED_CLOSE_CODE and self._handshake_succeeded:- self._auth_revoked = True- if not self._closing:- logger.warning(- "relay ws closed 4401 (unauthorized) after a successful handshake — "- "treating as a revoked relay credential (opt-out); not reconnecting"+ try:+ async for chunk in self._ws:+ buf += chunk if isinstance(chunk, str) else chunk.decode("utf-8")+ # Newline-delimited frames; keep any trailing partial line.+ *lines, buf = buf.split("\n")+ for line in lines:+ if line.strip():+ await self._handle_frame(line)+ except asyncio.CancelledError:+ raise+ except Exception as exc: # noqa: BLE001 - log + let the task end; reconnection handled below+ # Phase 7 Unit 7d-B: detect a 4401 (unauthorized) close. After a prior+ # successful handshake this is a REVOCATION (opt-out / deprovision) —+ # the per-gateway secret is gone, so reconnecting is futile. Latch a+ # terminal "auth revoked" state and DON'T re-dial. Before any+ # successful handshake a 4401 stays retryable (cold-start race).+ if self._close_code_of(exc) == _RELAY_UNAUTHORIZED_CLOSE_CODE and self._handshake_succeeded:+ self._auth_revoked = True+ if not self._closing:+ logger.warning(+ "relay ws closed 4401 (unauthorized) after a successful handshake — "+ "treating as a revoked relay credential (opt-out); not reconnecting"+ )+ elif not self._closing:+ logger.warning("relay ws read loop ended: %s", exc)+ # Phase 5 §5.3: the socket closed. If reconnect is enabled and this was+ # NOT a deliberate disconnect(), kick the reconnect supervisor so the+ # gateway re-dials + re-handshakes (which triggers the connector's+ # buffered-flip drain on the new handshake). Self-scheduling: the reader+ # ends here, the supervisor re-dials and starts a fresh reader.+ # Phase 7 Unit 7d-B: a revoked credential (terminal 4401) is the one case+ # we deliberately do NOT reconnect — the secret is dead until the+ # instance is recreated, so spinning would just reproduce the failure.+ if (+ self._reconnect+ and not self._closing+ and not self._auth_revoked+ and (self._supervisor is None or self._supervisor.done())+ ):+ self._supervisor = asyncio.create_task(+ self._reconnect_loop(), name="relay-ws-reconnect"+ )+ finally:+ # The reader is the ONLY thing that can resolve a pending+ # outbound_result future — once it exits (socket dropped, error,+ # or cancellation cleanup) every in-flight _request_response waiter+ # is unresolvable and would otherwise block the full+ # _outbound_timeout_s (~30s) on a dead socket (Coatue incident+ # 2026-08-18: stuck sends after a 1011 keepalive close). Fail them+ # NOW with the dict shape callers expect (never an exception on+ # the outbound path). list() snapshot: set_result wakes waiters+ # whose finally-pop would otherwise mutate the dict mid-iteration.+ for _rid, fut in list(self._pending.items()):+ if not fut.done():+ fut.set_result(+ {"success": False, "error": "relay transport connection lost"})- elif not self._closing:- logger.warning("relay ws read loop ended: %s", exc)- # Phase 5 §5.3: the socket closed. If reconnect is enabled and this was- # NOT a deliberate disconnect(), kick the reconnect supervisor so the- # gateway re-dials + re-handshakes (which triggers the connector's- # buffered-flip drain on the new handshake). Self-scheduling: the reader- # ends here, the supervisor re-dials and starts a fresh reader.- # Phase 7 Unit 7d-B: a revoked credential (terminal 4401) is the one case- # we deliberately do NOT reconnect — the secret is dead until the- # instance is recreated, so spinning would just reproduce the failure.- if (- self._reconnect- and not self._closing- and not self._auth_revoked- and (self._supervisor is None or self._supervisor.done())- ):- self._supervisor = asyncio.create_task(- self._reconnect_loop(), name="relay-ws-reconnect"- )+ self._pending.clear()@staticmethoddef _close_code_of(exc: BaseException) -> Optional[int]:diff --git a/tests/gateway/relay/test_ws_transport_hardening.py b/tests/gateway/relay/test_ws_transport_hardening.pynew file mode 100644index 00000000000..edeb1414864--- /dev/null+++ b/tests/gateway/relay/test_ws_transport_hardening.py@@ -0,0 +1,83 @@+"""Regression tests for the relay WS transport hardening fix.++Coatue incident 2026-08-18: WAN latency / event-loop stalls tripped the+websockets library's default 20s pong deadline, closing customer-gateway+sockets with `1011 keepalive ping timeout`. On top of the spurious close,+every in-flight outbound then hung for the full _outbound_timeout_s (~30s)+because only disconnect() failed pending futures — an unexpected socket drop+left them stranded — and sends issued while the reconnect supervisor was+backing off registered futures no reader could ever resolve.++Three hardening changes under test:+ 1. _read_loop fails all in-flight _pending futures on ANY exit path with+ the dict shape callers expect ({"success": False, ...}).+ 2. _request_response fails fast while the reconnect supervisor is+ mid-redial (live supervisor task = the redial window).+ 3. connect() passes explicit WAN-friendly keepalive tuning+ (ping_interval=30, ping_timeout=60) to websockets.connect().+"""++from __future__ import annotations++import asyncio++import pytest++import gateway.relay.ws_transport as ws_transport_mod+from gateway.relay.ws_transport import WebSocketRelayTransport, WEBSOCKETS_AVAILABLE++pytestmark = pytest.mark.skipif(not WEBSOCKETS_AVAILABLE, reason="websockets not installed")++if WEBSOCKETS_AVAILABLE:+ from websockets.exceptions import ConnectionClosedError+++class _DroppingWS:+ """Fake socket: accepts sends, then the read loop dies mid-iteration —+ the shape of an unexpected close (e.g. 1011 keepalive ping timeout)."""++ def __init__(self):+ self.sent: list[str] = []+ # Reader blocks here until the test releases it, so the outbound+ # future is registered BEFORE the "socket" drops.+ self.drop = asyncio.Event()++ async def send(self, data):+ self.sent.append(data)++ def __aiter__(self):+ return self++ async def __anext__(self):+ await self.drop.wait()+ raise ConnectionClosedError(None, None)++ async def close(self):+ pass+++async def test_read_loop_exit_fails_pending_futures_promptly():+ """When the socket drops unexpectedly, in-flight _request_response callers+ must get {"success": False, ...} promptly — not block ~30s on a future+ only the (now dead) reader could have resolved."""+ t = WebSocketRelayTransport("ws://unused", "discord", "bot1", outbound_timeout_s=30.0)+ fake = _DroppingWS()+ t._ws = fake+ t._reader = asyncio.create_task(t._read_loop())++ send_task = asyncio.create_task(t.send_outbound({"op": "send_message", "text": "hi"}))+ # Let the outbound frame go out and its future register in _pending.+ for _ in range(50):+ if t._pending:+ break+ await asyncio.sleep(0.01)+ assert t._pending, "outbound future never registered"++ # Drop the socket: the read loop exits on ConnectionClosedError.+ fake.drop.set()++ result = await asyncio.wait_for(send_task, timeout=2.0)+ assert result == {"success": False, "error": "relay transport connection lost"}+ assert t._pending == {}+ await t._reader