Files
hermes-agent/tests/gateway/test_session_socket_preload.py
kshitijk4poor 80350460d5 fix(gateway): a default ensure waits out a CPU-starved cold start
On a CPU-capped host (a 10% cgroup quota, a loaded runner) a cold `gateway run`
needs a few seconds of CPU that take minutes of wall time. The fixed 60 s
deadline of ensure_gateway_runtime (9c7dbc6e6f) then turns every cold
`hermes -z` into `Gateway starting: deadline`: main failed 3 of 3 runs at a
10% quota, each at about 61 s.

- A default ensure (no explicit timeout) extends its deadline while the
  pending start's owner (the home's verified running gateway, else the
  spawned child) keeps accruing CPU, at least 0.1 s per 15 s window, up to a
  300 s cap. A control probe that times out on such an owner is retried
  instead of ending the wait. Only a start this call is waiting on (one it
  spawned, joined or saw pending, a multiplexer root included) is sampled: a
  wedged READY gateway that spins still fails at 60 s, as before. An owner that makes no progress (stopped,
  blocked on a lock) still fails at the base 60 s, and an explicit --timeout
  stays a hard deadline. On macOS the one-off launchd job gets the moved
  deadline too, or its poll() would stop reporting an exit past the original.
- A client's own idle-exit gateway imports the /api/ws handler on a worker
  thread before READY, waiting at most 30 s for it, and an attach fetches the
  handler on a worker thread too. Left to the first upgrade, that ~0.7 s CPU
  import ran on the event loop inside the client's 10 s open timeout and
  failed the attach right after READY on a starved host.

At a 10% quota a cold `hermes -z` now attaches and answers (3 of 3); with no
quota the attach time is unchanged (3.90 s vs main 3.92 s), and a SIGSTOPped
gateway still fails with `starting: deadline`.
2026-11-09 00:56:23 +05:30

139 lines
5.8 KiB
Python

"""The /api/ws handler is imported off the loop before READY, and a failed or hung import never holds READY."""
import asyncio
import sys
import threading
from types import SimpleNamespace
import pytest
from gateway import run_api
@pytest.fixture
def unloaded(monkeypatch):
"""``tui_gateway.ws`` absent from sys.modules; record which thread imports it."""
import importlib
monkeypatch.delitem(sys.modules, "tui_gateway.ws", raising=False)
seen = {}
real = importlib.import_module
def spy(name, *args, **kwargs):
if name == "tui_gateway.ws":
seen["thread"] = threading.current_thread()
return SimpleNamespace(handle_ws=None)
return real(name, *args, **kwargs)
monkeypatch.setattr(importlib, "import_module", spy)
return seen
@pytest.mark.asyncio
async def test_preload_imports_off_the_event_loop(unloaded):
await run_api.await_session_socket_preload(run_api.preload_session_socket())
assert unloaded["thread"] is not threading.main_thread()
@pytest.mark.asyncio
async def test_failed_preload_never_fails_startup(caplog):
async def boom():
raise ImportError("broken handler")
await run_api.await_session_socket_preload(asyncio.ensure_future(boom()))
assert "loads on first attach" in caplog.text
@pytest.mark.asyncio
async def test_a_hung_preload_never_holds_ready(caplog):
hang = asyncio.ensure_future(asyncio.Event().wait())
await run_api.await_session_socket_preload(hang, timeout=0.05)
assert "publishing READY" in caplog.text and not hang.cancelled()
hang.cancel()
@pytest.mark.asyncio
async def test_an_attach_never_imports_the_handler_on_the_event_loop(unloaded):
"""An import still running past READY must not block the loop for the first attach."""
await run_api.session_socket_handler()
assert unloaded["thread"] is not threading.main_thread()
@pytest.mark.asyncio
async def test_a_preload_never_awaited_logs_no_unretrieved_exception(monkeypatch):
"""A startup that raises before awaiting the preload: its failure is not an asyncio warning."""
import gc
import importlib
def boom(name, *args, **kwargs):
raise ImportError("broken handler")
monkeypatch.delitem(sys.modules, "tui_gateway.ws", raising=False)
monkeypatch.setattr(importlib, "import_module", boom)
seen = []
loop = asyncio.get_running_loop()
monkeypatch.setattr(loop, "call_exception_handler", seen.append)
task = run_api.preload_session_socket()
assert task is not None
await asyncio.wait({task})
del task
gc.collect()
assert not [c for c in seen if "never retrieved" in c.get("message", "")]
def _attach_scope(ticket):
return {'type': 'websocket', 'path': '/api/ws', 'scheme': 'ws', 'query_string': b'',
'client': ('127.0.0.1', 1234), 'server': ('127.0.0.1', 9999),
'headers': [(b'sec-websocket-protocol', ('hermes-gateway-v1, hermes-gateway-ticket.' + ticket).encode())],
'subprotocols': ['hermes-gateway-v1', 'hermes-gateway-ticket.' + ticket]}
async def _attach_while_loading(tmp_path, monkeypatch, *, during_load, purpose='interactive'):
"""Attach over the real ``/api/ws`` admission with a redeemed ticket; ``during_load(runner)`` runs
while the handler fetch is pending. Returns (whether the handler ran, the ASGI messages sent)."""
from gateway.run_api import GatewayRuntimeAPI
from gateway.runtime_bootstrap import TicketStore
from hermes_cli import web_server as web
from hermes_cli import web_server_chat
tickets = TicketStore('owner', [str(tmp_path)])
ticket = tickets.mint(profile_id=str(tmp_path), subject='human', purpose=purpose)
authority = SimpleNamespace(db=SimpleNamespace(db_path=tmp_path / 'state.db'), profile_id=str(tmp_path), runner=None)
runner = SimpleNamespace(_draining=False, session_runtime_descriptor={'state': 'ready'},
session_authority=authority, session_ticket_store=tickets)
handled, sent = [], []
async def loading_handler():
during_load(runner)
async def handle(ws, **kwargs):
handled.append(True)
await ws.close()
return handle
monkeypatch.setattr(run_api, 'session_socket_handler', loading_handler)
monkeypatch.setattr(web, '_DASHBOARD_EMBEDDED_CHAT_ENABLED', True)
monkeypatch.setattr(web_server_chat, '_ws_request_is_allowed', lambda ws: True)
async def fallback(*args):
pytest.fail('a native ticket must not enter the legacy fallback')
incoming = iter([{'type': 'websocket.connect'}])
async def receive(): return next(incoming)
async def send(value): sent.append(value)
await GatewayRuntimeAPI(fallback, runner, web.app)(_attach_scope(ticket), receive, send)
return bool(handled), sent
@pytest.mark.asyncio
async def test_an_attach_counts_as_a_client_while_its_handler_is_still_loading(tmp_path, monkeypatch):
"""The ticket is redeemed before the handler fetch yields: an idle check in that gap must still
see this client, or an idle-exit gateway shuts down under its first connection."""
from gateway import run_idle_exit
seen = []
handled, _ = await _attach_while_loading(
tmp_path, monkeypatch, during_load=lambda runner: seen.append(run_idle_exit._client_busy(runner, window=0.0)))
assert seen == ['1 client(s) attached'] and handled
@pytest.mark.asyncio
async def test_a_drain_that_began_while_the_handler_loaded_refuses_the_attach(tmp_path, monkeypatch):
"""Admission is re-checked after the fetch: an interactive client is refused (1013) by a drain
that started while the handler loaded, exactly as if it had arrived after the drain."""
def drain(runner):
runner._draining = True
handled, sent = await _attach_while_loading(tmp_path, monkeypatch, during_load=drain)
assert not handled and sent[-1] == {'type': 'websocket.close', 'code': 1013, 'reason': ''}