The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(buzz): a dead socket ends the WebSocket connection from either side and publishes retrying
teknium1f529986abf3c
diff --git a/plugins/platforms/buzz/adapter.py b/plugins/platforms/buzz/adapter.pyindex 6e2b16ff345..a803add75bc 100644--- a/plugins/platforms/buzz/adapter.py+++ b/plugins/platforms/buzz/adapter.py@@ -1071,7 +1071,8 @@ class BuzzAdapter(BasePlatformAdapter):async def _ws_discovery_loop(self, websocket, subscriptions: Dict[str, Optional[str]]) -> None:"""Periodic discovery on the poll cadence: relays don't guarantee a kind-44100 event for every new- conversation. Failures retry next tick; the read loop alone owns connection health.+ conversation. Failures retry next tick, except a closed socket: that is the same dead connection the+ read loop may still be parked on, so it propagates and tears the connection down (#112049).The kind-44100 membership subscription is the fast path, but relays do not guarantee a membershipevent for every conversation that materializes mid-session (#93557) — some emit none at all for new@@ -1079,12 +1080,14 @@ class BuzzAdapter(BasePlatformAdapter):``_DM_DISCOVERY_EVERY`` sweeps; this loop gives the WS transport the same guarantee on the samecadence."""+ from websockets.exceptions import ConnectionClosed+interval = max(self.poll_interval * _DM_DISCOVERY_EVERY, _MIN_POLL_INTERVAL)while True:await asyncio.sleep(interval)try:await self._rediscover_and_subscribe(websocket, subscriptions)- except asyncio.CancelledError:+ except (asyncio.CancelledError, ConnectionClosed):raiseexcept Exception:logger.warning("Buzz: WebSocket discovery sweep failed", exc_info=True)@@ -1093,6 +1096,7 @@ class BuzzAdapter(BasePlatformAdapter):"""Persistent authenticated subscription with bounded reconnect backoff; `since` filters resume on reconnect."""import websocketsbackoff = 1.0+ reconnecting = Falsewhile True:try:async with websockets.connect(@@ -1103,19 +1107,32 @@ class BuzzAdapter(BasePlatformAdapter):subscriptions = await self._subscribe_websocket(websocket)if self._ws_ready is not None:self._ws_ready.set()+ if reconnecting:+ # connect() published "connected" once; a recovered socket has to say so again.+ reconnecting = False+ self._mark_connected()backoff = 1.0- discovery_task = asyncio.create_task(self._ws_discovery_loop(websocket, subscriptions))+ # Whichever side notices the dead socket first ends the connection: the read loop's idle+ # bound, or a discovery send() raising ConnectionClosed while the read is still parked.+ tasks = {+ asyncio.create_task(self._ws_read_loop(websocket, subscriptions)),+ asyncio.create_task(self._ws_discovery_loop(websocket, subscriptions)),+ }try:- await self._ws_read_loop(websocket, subscriptions)+ done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)+ for finished in done:+ finished.result()finally:- discovery_task.cancel()- try:- await discovery_task- except (asyncio.CancelledError, Exception):- pass+ for task in tasks:+ task.cancel()+ await asyncio.gather(*tasks, return_exceptions=True)except asyncio.CancelledError:raiseexcept Exception as e:+ # The health map only ever saw "connected"; say "retrying" until the socket is back (#112049).+ if not reconnecting:+ reconnecting = True+ self._mark_degraded()logger.warning("Buzz: WebSocket disconnected; retrying in %.1fs: %s", backoff, e)await asyncio.sleep(backoff)backoff = min(backoff * 2, 30.0)@@ -1133,11 +1150,6 @@ class BuzzAdapter(BasePlatformAdapter):# wait_for() cancels and then waits for its awaitable to acknowledge the cancellation.# A transport receive stuck below asyncio can ignore that cancellation forever, leaving the# adapter healthy-looking. Detach the read instead so the outer loop can close and reconnect.- self._mark_degraded()- logger.warning(- "Buzz: WebSocket read watchdog expired after %.0fs; receive task remained parked; reconnecting",- _WS_READ_IDLE_TIMEOUT,- )raise ConnectionError(f"no WebSocket frame for {_WS_READ_IDLE_TIMEOUT:.0f}s; assuming the connection went silent")diff --git a/tests/gateway/test_buzz_websocket.py b/tests/gateway/test_buzz_websocket.pyindex 320d4d050fa..54b9b124091 100644--- a/tests/gateway/test_buzz_websocket.py+++ b/tests/gateway/test_buzz_websocket.py@@ -140,15 +140,17 @@ async def test_websocket_loop_reconnects_when_read_goes_silent(monkeypatch, caplReproduces the #98097 shape: a socket stuck in CLOSE_WAIT yields noframe and no error, so without a read-side bound the loop would wait- forever while the gateway keeps reporting "connected".+ forever while the gateway keeps reporting "connected". The receive here+ also ignores cancellation (#112049), which held the bound hostage as long+ as it was an ``asyncio.wait_for``."""import loggingadapter = _make_adapter()monkeypatch.setattr(_buzz_mod, "_WS_READ_IDLE_TIMEOUT", 0.05)caplog.set_level(logging.WARNING)- degraded = []- monkeypatch.setattr(adapter, "_mark_degraded", lambda: degraded.append(True))+ states = []+ monkeypatch.setattr(adapter, "_write_runtime_status_safe", lambda status, **kw: states.append(kw["platform_state"]))sockets = []release_parked_receive = asyncio.Event()@@ -188,8 +190,68 @@ async def test_websocket_loop_reconnects_when_read_goes_silent(monkeypatch, caplassert len(sockets) >= 2, "idle read watchdog did not force a reconnect"assert sockets[0].exited, "the silent connection was not closed before reconnecting"assert any("went silent" in record.message for record in caplog.records)- assert any("receive task remained parked" in record.message for record in caplog.records)- assert degraded, "a parked receive must publish degraded health"+ assert states[:2] == ["retrying", "connected"], f"health must flip to retrying and back, got {states}"+++async def test_websocket_loop_reconnects_when_discovery_send_sees_closed_socket(monkeypatch):+ """A send-side ConnectionClosed proves the socket is dead even while the read is parked.++ #112049: the discovery sweep logged ``ConnectionClosedError`` for hours while+ ``_ws_read_loop`` sat on a receive that never returned; the sweep must end the+ connection so the reconnect path runs instead of retrying next tick forever.+ """+ from websockets.exceptions import ConnectionClosedError++ adapter = _make_adapter()+ adapter.poll_interval = 0.02+ monkeypatch.setattr(_buzz_mod, "_MIN_POLL_INTERVAL", 0.02)+ monkeypatch.setattr(_buzz_mod, "_DM_DISCOVERY_EVERY", 1)+ monkeypatch.setattr(_buzz_mod, "_WS_READ_IDLE_TIMEOUT", 30.0) # far away: only the send side can end this++ sockets = []++ async def silent_anext():+ sockets[-1].dead = True # the read loop is now parked; the relay side is gone+ await asyncio.Event().wait()++ async def rediscover(websocket, subscriptions):+ await websocket.send(json.dumps(["REQ", "hermes-buzz-dm-1", {}]))++ monkeypatch.setattr(adapter, "_rediscover_and_subscribe", rediscover)++ def fake_connect(*args, **kwargs):+ ws = _ScriptedWebSocket(silent_anext)+ ws.dead = False+ real_send = ws.send++ async def send(raw):+ if ws.dead:+ raise ConnectionClosedError(None, None)+ await real_send(raw)++ ws.send = send+ sockets.append(ws)+ return ws++ import websockets as _ws_mod++ monkeypatch.setattr(_ws_mod, "connect", fake_connect)++ task = asyncio.create_task(adapter._websocket_loop())+ try:+ deadline = time.monotonic() + 5.0+ while len(sockets) < 2 and time.monotonic() < deadline:+ await asyncio.sleep(0.02)+ finally:+ task.cancel()+ try:+ await asyncio.wait_for(task, 5.0)+ except (asyncio.CancelledError, asyncio.TimeoutError):+ pass++ assert len(sockets) >= 2, "a closed socket seen by the discovery sweep did not force a reconnect"+ assert sockets[0].exited, "the dead connection was not closed before reconnecting"@pytest.mark.asynciodiff --git a/website/docs/user-guide/messaging/buzz.md b/website/docs/user-guide/messaging/buzz.mdindex 44c0cf732d4..0d030b72664 100644--- a/website/docs/user-guide/messaging/buzz.md+++ b/website/docs/user-guide/messaging/buzz.md@@ -156,7 +156,7 @@ Check status with `hermes gateway status` — Buzz connection state is reported## Notes and limitations- **`BUZZ_*` env vars are available in terminal tool children for Buzz sessions** — the agent can invoke the `buzz` CLI directly (e.g. `buzz messages send ...`) because `BUZZ_PRIVATE_KEY`, `BUZZ_AUTH_TAG`, `BUZZ_RELAY_URL`, and the other `BUZZ_*` variables are passed through to terminal subprocesses when the session's platform is `buzz` or the process is a Buzz Desktop managed agent (`BUZZ_MANAGED_AGENT`). Non-Buzz sessions on the same host, `execute_code`, and other non-terminal spawns remain sealed.-- **Inbound is polled, not streamed.** The `buzz` CLI is request/response, so the adapter polls `buzz messages get` per watched channel every `poll_interval` seconds (default 4). Expect up to one interval of latency on inbound messages. A future optimization is a websocket transport (the Buzz repo ships `buzz-ws-client` for true streaming).+- **Inbound streaming has a watchdog.** On the WebSocket transport a connection that goes quiet for five minutes, or whose socket the relay closed underneath us, is torn down and reconnected with backoff; while that happens the gateway health (`/health/detailed`, dashboard status) reports Buzz as `retrying`, not `connected`. On the `poll` transport the adapter polls `buzz messages get` per watched channel every `poll_interval` seconds (default 4), so expect up to one interval of latency.- On (re)connect the adapter seeds its high-water mark from the newest events, so channel history is never replayed into the agent.- New DM conversations are discovered automatically (every few poll sweeps).- The private key is passed to the CLI via the subprocess environment — it never appears in argv or logs.