From 9fb0ba2990f9c3b37cc224276cf16aed5d4de8d9 Mon Sep 17 00:00:00 2001 From: Ben Davis <45952064+bmdavis419@users.noreply.github.com> Date: Sat, 25 Jul 2026 00:20:09 -0700 Subject: [PATCH] fix: stop the liveness probe from killing healthy Hermes connections MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The ping loop was tearing down working connections every ~60s: the plugin would reconnect, get replaced, and the thread would die with "replaced by a newer connection" on the next message. The plugin read its socket with `await self._on_message(...)` inline, so a frame was only read once the previous handler finished. `turn.start` blocks for an entire Hermes turn, which meant a ping sent mid-turn was not merely answered late — it was never read off the socket at all. The server counted the misses and closed a perfectly healthy connection. Dispatch command handlers as tasks so the read loop keeps draining, and answer pings inline since they never touch Hermes. Handler tasks are held in a set (asyncio keeps only a weak reference) and their failures logged. Server side, `Effect.forever` kept probing after a connection was retired, so a dead connection logged further misses against a socket nobody was using; the probe now interrupts itself once it has torn the connection down. Ping tolerance is also widened — a Python event loop under a heavy turn can be slow to schedule even when healthy, and killing a working connection is far worse than noticing a dead one a few seconds later. Worst-case detection stays inside REQUEST_TIMEOUT (10 + 6*3 = 28s against 30s) so an in-flight request over a dead socket still fails with the liveness reason rather than a generic timeout. The regression test drives the real `_supervise` loop rather than a copy of it: an earlier version reimplemented the loop in the test and passed against the very bug it was meant to catch. Co-Authored-By: Claude Opus 5 (1M context) --- .../provider/Layers/HermesGatewayBroker.ts | 28 +++++- integrations/hermes-t3-gateway/connection.py | 59 ++++++++++++- .../tests/test_connection.py | 85 +++++++++++++++++++ 3 files changed, 165 insertions(+), 7 deletions(-) diff --git a/apps/server/src/provider/Layers/HermesGatewayBroker.ts b/apps/server/src/provider/Layers/HermesGatewayBroker.ts index 0b43bf906c..37b936fb50 100644 --- a/apps/server/src/provider/Layers/HermesGatewayBroker.ts +++ b/apps/server/src/provider/Layers/HermesGatewayBroker.ts @@ -109,10 +109,26 @@ const SWEEP_INTERVAL = Duration.minutes(1); * "the connection stopped responding" rather than sit out a generic timeout. */ const PING_INTERVAL = Duration.seconds(10); -/** How long a single ping may go unanswered before it counts as missed. */ -const PING_TIMEOUT = Duration.seconds(4); -/** Consecutive missed pings tolerated before the connection is torn down. */ -const PING_MAX_MISSED = 2; +/** + * How long a single ping may go unanswered before it counts as missed. + * + * Generous on purpose. The plugin answers pings from its socket read loop + * without touching Hermes, so a slow reply means the process is genuinely + * starved rather than merely busy — but a Python event loop under a heavy + * turn can still be slow to schedule, and killing a working connection is far + * worse than noticing a dead one a few seconds later. + */ +const PING_TIMEOUT = Duration.seconds(6); +/** + * Consecutive missed pings tolerated before the connection is torn down. + * + * Worst case detection is `PING_INTERVAL` (the wait before the first probe) + * plus `PING_TIMEOUT * PING_MAX_MISSED`, since a miss re-probes immediately. + * That total must stay under `REQUEST_TIMEOUT` so an in-flight request over a + * dead socket fails with the liveness reason rather than a generic timeout: + * 10 + 6*3 = 28s against a 30s request timeout. + */ +const PING_MAX_MISSED = 3; const CREDENTIAL_BYTES = 32; @@ -773,6 +789,10 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { "The Hermes gateway connection stopped responding.", ); } + // This connection is gone either way — retired here, or already + // replaced. Stop probing rather than interrogating a dead socket and + // logging another miss for a connection nobody is using. + return yield* Effect.interrupt; }); // First probe runs after one interval — long enough that a plugin which diff --git a/integrations/hermes-t3-gateway/connection.py b/integrations/hermes-t3-gateway/connection.py index 95ee41cf44..04d35cd043 100644 --- a/integrations/hermes-t3-gateway/connection.py +++ b/integrations/hermes-t3-gateway/connection.py @@ -10,7 +10,7 @@ from contextlib import suppress from typing import Any from urllib.parse import urlsplit, urlunsplit -from .protocol import PROTOCOL_VERSION, WEBSOCKET_PATH, connection_hello +from .protocol import PROTOCOL_VERSION, WEBSOCKET_PATH, connection_hello, iso_now logger = logging.getLogger(__name__) @@ -144,6 +144,7 @@ class T3GatewayConnection: self._send_lock = asyncio.Lock() self._connected = asyncio.Event() self._first_result: asyncio.Future[bool] | None = None + self._handlers: set[asyncio.Task[None]] = set() self._stopping = False @property @@ -185,6 +186,46 @@ class T3GatewayConnection: async with self._send_lock: await self._socket.send(encoded) + def _spawn_handler(self, message: dict[str, Any]) -> None: + """Run one command handler off the read loop. + + asyncio only holds a weak reference to tasks, so the handle is kept + until completion — otherwise a long turn can be garbage collected + mid-flight. Failures are logged rather than surfacing as bare + "task exception was never retrieved" warnings. + """ + task = asyncio.create_task(self._on_message(message)) + self._handlers.add(task) + + def _finished(completed: asyncio.Task[None]) -> None: + self._handlers.discard(completed) + if completed.cancelled(): + return + error = completed.exception() + if error is not None: + logger.warning( + "T3 gateway command handler failed: %s", error, exc_info=error + ) + + task.add_done_callback(_finished) + + async def _send_pong(self, ping: dict[str, Any]) -> None: + """Answer a liveness probe without going through command dispatch.""" + request_id = ping.get("requestId") + if not request_id: + return + try: + await self.send( + { + "type": "pong", + "protocolVersion": PROTOCOL_VERSION, + "requestId": request_id, + "sentAt": ping.get("sentAt") or iso_now(), + } + ) + except Exception: # noqa: BLE001 - a failed pong must not kill the read loop + logger.debug("Failed to answer a T3 liveness ping", exc_info=True) + async def _supervise(self) -> None: delay = 1.0 while not self._stopping: @@ -208,8 +249,20 @@ class T3GatewayConnection: delay = 1.0 async for raw in socket: message = json.loads(raw) - if isinstance(message, dict): - await self._on_message(message) + if not isinstance(message, dict): + continue + # Liveness is answered inline; it never touches Hermes. + if message.get("type") == "ping": + await self._send_pong(message) + continue + # Commands are dispatched WITHOUT awaiting them. A handler + # awaits Hermes — `turn.start` blocks for the whole agent + # turn — and awaiting it here would stop reading the + # socket, so a ping sent mid-turn would not even be read, + # let alone answered, and T3 would close a healthy + # connection as half-open. Ordering within a session is + # still preserved by the plugin's own per-thread state. + self._spawn_handler(message) except asyncio.CancelledError: raise except ConnectionRejected as exc: diff --git a/integrations/hermes-t3-gateway/tests/test_connection.py b/integrations/hermes-t3-gateway/tests/test_connection.py index 59e802c791..5dc10f078f 100644 --- a/integrations/hermes-t3-gateway/tests/test_connection.py +++ b/integrations/hermes-t3-gateway/tests/test_connection.py @@ -1,6 +1,7 @@ from __future__ import annotations import importlib.util +import contextlib import json import pathlib import sys @@ -26,6 +27,10 @@ for name in ("protocol", "connection"): connection = sys.modules[f"{PACKAGE}.connection"] +async def _immediate(value): + return value + + class FakeSocket: def __init__(self, response): self.response = response @@ -118,6 +123,86 @@ class ConnectionTests(unittest.IsolatedAsyncioTestCase): ) self.assertEqual(raised.exception.code, "version-incompatible") + async def test_ping_is_answered_while_a_command_handler_is_blocked(self): + """A ping must not queue behind command dispatch. + + `_on_message` awaits Hermes: `turn.start` blocks for the whole agent + turn. If the real read loop awaited that before reading the next + frame, a ping arriving mid-turn would go unanswered for minutes and + T3 would close a healthy socket as half-open — which is what happened + in practice. This drives `_supervise` itself so the loop under test is + the one that ships. + """ + import asyncio + + blocked = asyncio.Event() + released = asyncio.Event() + + class BlockingSocket: + def __init__(self): + self.sent = [] + + async def send(self, value): + self.sent.append(json.loads(value)) + + async def recv(self): + return json.dumps( + { + "type": "connection.accepted", + "protocolVersion": 2, + "requestId": self.sent[0]["requestId"], + "instanceId": "provider-instance", + "nickname": "Hermes", + } + ) + + async def close(self): + return None + + def __aiter__(self): + async def frames(): + yield json.dumps({"type": "turn.start", "requestId": "turn-1"}) + yield json.dumps( + {"type": "ping", "protocolVersion": 2, "requestId": "ping-1"} + ) + await released.wait() + + return frames() + + socket = BlockingSocket() + + async def on_message(message): + # Stands in for Hermes running a turn: does not return while the + # test checks whether the pong went out regardless. + blocked.set() + await released.wait() + + conn = connection.T3GatewayConnection( + url="ws://t3.example/api/hermes-gateway/ws", + instance_id="provider-instance", + credential="secret", + hermes_version="0.19.0", + on_message=on_message, + ) + + original_open = connection._open_socket + connection._open_socket = lambda url: _immediate(socket) + try: + self.assertTrue(await conn.connect(timeout=2)) + await asyncio.wait_for(blocked.wait(), timeout=2) + # Let the read loop reach the queued ping while on_message is stuck. + for _ in range(10): + await asyncio.sleep(0) + pongs = [f for f in socket.sent if f.get("type") == "pong"] + self.assertEqual( + len(pongs), 1, "the ping must be answered while a command is blocked" + ) + self.assertEqual(pongs[0]["requestId"], "ping-1") + finally: + connection._open_socket = original_open + released.set() + await conn.disconnect() + if __name__ == "__main__": unittest.main()