The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(kanban): a worker spawned while `hermes update` drains the owner waits instead of crashing
Teknium042f87bb36ee
diff --git a/hermes_cli/gateway_client.py b/hermes_cli/gateway_client.pyindex 7d0b5c20858..5cb097bb47a 100644--- a/hermes_cli/gateway_client.py+++ b/hermes_cli/gateway_client.py@@ -31,6 +31,15 @@ class GatewayRPCError(GatewayClientError):"""A received owner refusal, distinct from an ambiguous transport failure."""+class GatewayUnavailableError(GatewayClientError):+ """No ready owner to dial: ``state`` is ``ensure_gateway_runtime``'s verdict (``draining`` while an+ update holds the install, ``starting`` past the deadline, ...). Nothing was submitted."""++ def __init__(self, message, state):+ super().__init__(message)+ self.state = state++class GatewayClient:def __init__(self, websocket):self.websocket = websocket@@ -142,7 +151,8 @@ async def connect_gateway():result = await asyncio.to_thread(ensure_gateway_runtime, home)if result.state != "ready" or result.endpoint is None:detail = f" ({result.detail})" if getattr(result, "detail", None) else ""- raise GatewayClientError(f"Gateway {result.state}: {result.reason_code or 'not_ready'}{detail}")+ raise GatewayUnavailableError(f"Gateway {result.state}: {result.reason_code or 'not_ready'}{detail}",+ result.state)endpoint = result.endpointticket = await asyncio.to_thread(_session_ticket, home, endpoint)url, protocols = gateway_ws_target(endpoint, ticket)diff --git a/hermes_cli/kanban_worker_client.py b/hermes_cli/kanban_worker_client.pyindex 871168c83f1..741867b5062 100644--- a/hermes_cli/kanban_worker_client.py+++ b/hermes_cli/kanban_worker_client.py@@ -11,28 +11,48 @@ import asyncioimport osfrom pathlib import Pathimport sys+import time++# A worker the dispatcher spawns while `hermes update` drains the owner (or while the new owner is+# still starting) waits for it instead of exiting: the condition is the host's, not the card's, and+# a failed exit here spends the card's failure budget on an update window. Nothing is submitted+# until an owner is ready, so waiting can never run the claim twice.+OWNER_WAIT_S = 180.0+_TRANSIENT_OWNER_STATES = frozenset({'draining', 'starting'})async def run(params, board_db):- from hermes_cli.gateway_client import connect_gateway, GatewayClientError+ from hermes_cli.gateway_client import connect_gateway, GatewayClientError, GatewayUnavailableErrorif os.environ.get('HERMES_TUI_GATEWAY_URL'):raise GatewayClientError('Kanban requires the assigned local profile owner')- async with connect_gateway() as client:- db = str(await asyncio.to_thread(Path(board_db).resolve))- accepted = await client.rpc('kanban.run', **dict(params, db=db))- sid, receipt = accepted['session_id'], accepted['receipt']- print(f'Session: {sid}', file=sys.stderr)- while receipt['status'] not in {'terminal', 'unknown'}:- await asyncio.sleep(.2)- receipt = await client.rpc('prompt.receipt', session_id=sid, admission_id=receipt['admission_id'])- if receipt['status'] == 'unknown':- raise GatewayClientError('Kanban execution unknown; retained by owner')- from gateway.session_kanban import worker_result- result = worker_result(board_db, params)- # The attempt's reply ends the log, as a one-shot worker's did: crash diagnostics quote it.- if result.get('last_output'):- print(result['last_output'])- return result.get('exit_code', 1)+ deadline = time.monotonic() + OWNER_WAIT_S+ while True:+ try:+ async with connect_gateway() as client:+ return await _submit_claim(client, params, board_db)+ except GatewayUnavailableError as exc:+ if exc.state not in _TRANSIENT_OWNER_STATES or time.monotonic() >= deadline:+ raise+ await asyncio.sleep(1)+++async def _submit_claim(client, params, board_db):+ from hermes_cli.gateway_client import GatewayClientError+ db = str(await asyncio.to_thread(Path(board_db).resolve))+ accepted = await client.rpc('kanban.run', **dict(params, db=db))+ sid, receipt = accepted['session_id'], accepted['receipt']+ print(f'Session: {sid}', file=sys.stderr)+ while receipt['status'] not in {'terminal', 'unknown'}:+ await asyncio.sleep(.2)+ receipt = await client.rpc('prompt.receipt', session_id=sid, admission_id=receipt['admission_id'])+ if receipt['status'] == 'unknown':+ raise GatewayClientError('Kanban execution unknown; retained by owner')+ from gateway.session_kanban import worker_result+ result = worker_result(board_db, params)+ # The attempt's reply ends the log, as a one-shot worker's did: crash diagnostics quote it.+ if result.get('last_output'):+ print(result['last_output'])+ return result.get('exit_code', 1)def main():diff --git a/tests/hermes_cli/test_kanban_worker_owner_wait.py b/tests/hermes_cli/test_kanban_worker_owner_wait.pynew file mode 100644index 00000000000..b0db0092f76--- /dev/null+++ b/tests/hermes_cli/test_kanban_worker_owner_wait.py@@ -0,0 +1,63 @@+"""A Kanban worker spawned while `hermes update` drains the owner waits for it instead of failing.++The dispatcher keeps spawning workers during an update window; the owner answers ``draining``+until the update releases the install. Exiting 1 there books a crash against the card, and two+of those trip the breaker and park a card that never ran (the in-flight handoff cell). The wait+must never submit the claim twice, and a non-transient refusal still fails at once.+"""++from contextlib import asynccontextmanager++import pytest++from hermes_cli import gateway_client, kanban_worker_client+++def _owner(states, submitted):+ @asynccontextmanager+ async def connect():+ state = states.pop(0) if states else None+ if state:+ # The exact refusal connect_gateway raises for a draining/starting owner.+ unavailable = getattr(gateway_client, "GatewayUnavailableError", None)+ if unavailable is None: # pre-fix tree: the same message as a plain client error+ raise gateway_client.GatewayClientError(f"Gateway {state}: update_paused")+ raise unavailable(f"Gateway {state}: update_paused", state)++ class _Client:+ async def rpc(self, method, **params):+ submitted.append(method)+ return {"session_id": "s1", "receipt": {"status": "terminal", "admission_id": "a1"}}++ yield _Client()++ return connect+++async def test_worker_waits_out_a_draining_owner_and_submits_once(monkeypatch, tmp_path):+ submitted = []+ monkeypatch.setattr(gateway_client, "connect_gateway", _owner(["draining", "starting"], submitted))+ monkeypatch.setattr(kanban_worker_client.asyncio, "sleep", _no_sleep)+ import gateway.session_kanban as session_kanban+ monkeypatch.setattr(session_kanban, "worker_result", lambda *_: {"exit_code": 0, "last_output": "card closed"})+ monkeypatch.delenv("HERMES_TUI_GATEWAY_URL", raising=False)++ assert await kanban_worker_client.run({"task_id": "t1"}, str(tmp_path / "kanban.db")) == 0+ assert submitted == ["kanban.run"]+++async def test_worker_fails_at_once_when_the_owner_is_not_transiently_down(monkeypatch, tmp_path):+ submitted = []+ monkeypatch.setattr(gateway_client, "connect_gateway", _owner(["inaccessible"], submitted))+ monkeypatch.setattr(kanban_worker_client.asyncio, "sleep", _no_sleep)+ monkeypatch.delenv("HERMES_TUI_GATEWAY_URL", raising=False)++ with pytest.raises(gateway_client.GatewayClientError):+ await kanban_worker_client.run({"task_id": "t1"}, str(tmp_path / "kanban.db"))+ assert submitted == []+++async def _no_sleep(_seconds):+ return None