Skip to content

The agent that grows with you

fix(kanban): dispose of a lost managed worker within one tick

SanLuis-AI-Solutions2432f9c29acd
diff --git a/agent/runtime_session_store.py b/agent/runtime_session_store.py
index f05c66459eb..b942bd21e24 100644
--- a/agent/runtime_session_store.py
+++ b/agent/runtime_session_store.py
@@ -22,6 +22,57 @@ logger = logging.getLogger(__name__)
_worker_process = False
+# The ``worker.adopt`` handshake is a round trip through the OWNER's event loop, and a live
+# gateway legitimately spends 1000 s+ inside one turn (fan/gateway.log 2026-10-22:
+# ``time=1018.3s api_calls=46``). A 5 s budget lost that race and cost a whole dispatch
+# cycle silently: the managed worker died in ``worker.adopt``, the card kept saying
+# ``running``, and nothing retried. Generous by default, overridable, and a TIMEOUT (never
+# an auth/protocol failure) is retried with backoff.
+WORKER_RPC_OPEN_TIMEOUT_SECONDS = 60.0
+WORKER_RPC_CONNECT_ATTEMPTS = 3
+WORKER_RPC_RETRY_SLEEP_SECONDS = 1.0
+
+
+def worker_rpc_open_timeout():
+ """The handshake budget: ``HERMES_WORKER_RPC_OPEN_TIMEOUT`` seconds, else 60 s."""
+ # The adopt handshake runs BEFORE the worker may import config (agent/managed_worker.py:
+ # "No agent/config imports before adopted process authority"), so no config.yaml key can
+ # size it; resolved per call, 60 s default.
+ raw = os.environ.get('HERMES_WORKER_RPC_OPEN_TIMEOUT', '').strip() # health: allow HX002 -- the adopt handshake runs before the worker may import config, so no config.yaml key can size it; read per call, 60 s default
+ if raw:
+ try:
+ value = float(raw)
+ except ValueError:
+ value = 0.0
+ if value > 0:
+ return value
+ return WORKER_RPC_OPEN_TIMEOUT_SECONDS
+
+
+def connect_worker_link(connect, url, protocols, *, open_timeout=None, attempts=None, sleep=None):
+ """Open the owner link, retrying a handshake that TIMED OUT because the owner was busy.
+
+ Only ``TimeoutError`` is retried: an authentication or protocol failure will not heal with
+ another attempt, and re-sending after a completed handshake is never safe. Each attempt
+ gets the full budget; ``sleep`` is a test seam.
+ """
+ import time as _time
+ budget = worker_rpc_open_timeout() if open_timeout is None else float(open_timeout)
+ tries = max(1, int(WORKER_RPC_CONNECT_ATTEMPTS if attempts is None else attempts))
+ pause = _time.sleep if sleep is None else sleep
+ last = None
+ for attempt in range(tries):
+ try:
+ return connect(url, subprotocols=protocols, open_timeout=budget, close_timeout=1,
+ max_size=8 * 1024 * 1024, proxy=None, ping_interval=None)
+ except TimeoutError as exc:
+ last = exc
+ if attempt + 1 < tries:
+ logger.warning('owner handshake timed out after %ss (attempt %d/%d); retrying',
+ budget, attempt + 1, tries)
+ pause(WORKER_RPC_RETRY_SLEEP_SECONDS * (2 ** attempt))
+ raise last
+
def is_worker_process():
"""A successful self-registration makes this interpreter compute-only.
@@ -155,8 +206,7 @@ class WorkerRPC:
# The owner is loopback, like connect_gateway's peer: an inherited HTTPS_PROXY must not carry it.
# No library keepalive: its pong deadline would run independently of (and could fail) a call
# inside its receipt budget; that budget and the observed close are the liveness checks.
- self.link = _OwnerLink(connect(url, subprotocols=protocols, open_timeout=5, close_timeout=1,
- max_size=8 * 1024 * 1024, proxy=None, ping_interval=None))
+ self.link = _OwnerLink(connect_worker_link(connect, url, protocols))
return self.link
def _drop(self):
diff --git a/gateway/session_kanban.py b/gateway/session_kanban.py
index 19ec95340d6..93e58088498 100644
--- a/gateway/session_kanban.py
+++ b/gateway/session_kanban.py
@@ -312,6 +312,44 @@ def _record_worker_result(context, code, last_output):
'last_output': last_output}, run_id=context['run_id'])
+def record_worker_loss(policy, reason, *, pid=None, bound=False):
+ """Durably record that this attempt's managed execution was LOST — on the card's board.
+
+ ``worker.adopt`` runs before ``bind_worker_context``, so a worker that dies in the adopt
+ handshake writes neither ``worker_bound`` nor ``worker_result``: the run learns nothing
+ from its own loss, and the dispatcher can only guess from a dead pid. 2026-10-22
+ (t_f5fad63f) the gateway logged ``Managed worker lost: managed_worker_failed`` 24 s in
+ and the card still said ``running`` 49 minutes later. A warning in a log file is not a
+ disposition, so the owner writes the disposition where the board can read it.
+
+ Best-effort and run-scoped: a loss recorded against a run the card has already moved
+ past is not evidence about the current attempt, so it is dropped. Never raises — the
+ loss itself must reach the caller.
+ """
+ context = json.loads(getattr(policy, 'kanban_json', None) or 'null')
+ if not context:
+ return
+ try:
+ from hermes_cli.kanban_db_connect import connect_closing
+ from hermes_cli import kanban_db as kb
+ run_id = int(context['run_id'])
+ with connect_closing(Path(context['db'])) as conn, kb.write_txn(conn):
+ row = conn.execute('SELECT status, current_run_id FROM tasks WHERE id=?',
+ (context['task_id'],)).fetchone()
+ if row is None or row[0] != 'running' or row[1] != run_id:
+ return
+ kb._append_event(conn, context['task_id'], 'worker_lost',
+ {'reason': str(reason)[:200], 'claim_lock': context['claim_lock'],
+ 'run_id': run_id, 'pid': pid, 'bound': bool(bound)},
+ run_id=run_id)
+ except Exception as exc:
+ # The loss must reach its caller, never be masked; the traceback is the only place a
+ # failing board write is diagnosable (the caller keeps the original loss either way).
+ import logging
+ logging.getLogger(__name__).exception('kanban worker_lost record failed: %s',
+ type(exc).__name__)
+
+
def _bound_worker_matches(conn, context):
import os
row = conn.execute("SELECT payload FROM task_events WHERE task_id=? AND run_id=? AND kind='worker_bound' ORDER BY id DESC LIMIT 1",
diff --git a/gateway/session_managed_worker.py b/gateway/session_managed_worker.py
index 9a7d81e771a..0c361d6e392 100644
--- a/gateway/session_managed_worker.py
+++ b/gateway/session_managed_worker.py
@@ -545,6 +545,23 @@ def _stopped_before_spawn(authority, ref, row):
return True
+async def _record_lost_attempt(policy, reason, scope):
+ """Leave a BOARD disposition for a lost attempt, not only the log line above.
+
+ ``worker.adopt`` precedes ``bind_worker_context``, so a worker that dies in the handshake
+ never writes ``worker_bound``/``worker_result`` and the card's run learns nothing
+ (2026-10-22: 49 minutes of "in progress" on a corpse). A deliberate Stop or a superseded
+ generation is not a loss, and a turn with no board has nowhere to write.
+ """
+ if not getattr(policy, 'kanban_json', None):
+ return
+ if reason in ('managed_worker_stopped', 'stale_generation', 'CancelledError'):
+ return
+ from gateway.session_kanban import record_worker_loss
+ await asyncio.to_thread(record_worker_loss, policy, reason,
+ pid=(scope or {}).get('pid'), bound=scope is not None)
+
+
async def _spawn_registered_worker(authority, ref, row):
"""Spawn the turn's child and register it for Stops: ``(worker, process)``, or None when the spawn was cancelled (the
interrupted result is already recorded). The generation stays marked spawning until registration."""
@@ -675,8 +692,9 @@ async def execute_managed(authority, ref, row, policy):
raise RuntimeStoreError('invalid_worker_frame')
except (Exception, asyncio.CancelledError) as exc:
import logging
- logging.getLogger(__name__).warning('Managed worker lost: %s',
- exc.reason if isinstance(exc, RuntimeStoreError) else type(exc).__name__)
+ reason = exc.reason if isinstance(exc, RuntimeStoreError) else type(exc).__name__
+ logging.getLogger(__name__).warning('Managed worker lost: %s', reason)
+ await _record_lost_attempt(policy, reason, scope)
if scope is None:
if isinstance(exc, asyncio.CancelledError) or (
isinstance(exc, RuntimeStoreError) and exc.reason == 'managed_worker_stopped'):
diff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.py
index 19642948d0d..8cf19f25d06 100644
--- a/hermes_cli/kanban_db.py
+++ b/hermes_cli/kanban_db.py
@@ -1,3 +1,4 @@
+# health: allow FILE_LINES -- the lost-managed-worker fix (2026-10-22 stall) needs the reclaim's run error to name the owner's own record of how the attempt ended; that is two statements at this existing chokepoint, and the topic split of this facade is a separate refactor
"""SQLite-backed Kanban board shared across profiles (the cross-profile coordination primitive).
Lives under the shared Hermes root: ``default`` board DB at ``<root>/kanban.db`` (pre-boards
@@ -2395,9 +2396,14 @@ def release_stale_claims(
)
if cur.rowcount != 1:
continue
+ # Name WHY the attempt ended when the owner already recorded it (a lost managed
+ # worker, or a settled admission): a bare ``stale_lock=`` is not a disposition.
+ from hermes_cli.kanban_owner_recovery import owner_attempt_note
+ attempt_note = owner_attempt_note(conn, row["id"])
+ error = f"stale_lock={row['claim_lock']}" + (f" [{attempt_note}]" if attempt_note else "")
run_id = _record_reclaim(
conn, row["id"], termination,
- error=f"stale_lock={row['claim_lock']}",
+ error=error,
payload={
"stale_lock": row["claim_lock"],
"worker_pid": _opt_int(row["worker_pid"]),
@@ -2407,6 +2413,7 @@ def release_stale_claims(
"host_local": host_local,
"heartbeat_stale": bool(heartbeat_stale),
"retry_status": retry_status,
+ **({"attempt_note": attempt_note} if attempt_note else {}),
},
)
reclaimed += 1
@@ -2414,7 +2421,7 @@ def release_stale_claims(
# the run ended without a verdict, so it counts toward the breaker and a
# trip flips the task to ``blocked`` + ``gave_up`` on top of ``reclaimed``.
_record_task_failure(
- conn, row["id"], f"stale_lock={row['claim_lock']}",
+ conn, row["id"], error,
outcome="reclaimed", failure_limit=failure_limit,
release_claim=False, end_run=False,
event_payload_extra={"worker_pid": _opt_int(row["worker_pid"]), "retry_status": retry_status},
diff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.py
index e25346e58dd..6f7babc2c3d 100644
--- a/hermes_cli/kanban_db_dispatch.py
+++ b/hermes_cli/kanban_db_dispatch.py
@@ -1,3 +1,4 @@
+# health: allow FILE_LINES -- the lost-managed-worker fix (2026-10-22 stall) adds the run-scoped worker_lost fold (_apply_attempt_note) plus the absent-pid kill-step branch at this existing chokepoint; the topic split of this module is a separate refactor
"""Dispatcher: crash/stale/orphan detection, failure accounting and the respawn circuit breaker, memory-aware concurrency caps, the one-shot ``dispatch_once`` pass, worker spawning (``_default_spawn``), worker-log rotation and the long-lived ``run_daemon`` loop.
Split out of ``hermes_cli.kanban_db``; origin-resident helpers are reached
@@ -485,6 +486,14 @@ def _terminate_reclaimed_worker(
info["terminated"] = True
return info
except OSError:
+ # Windows reports an ABSENT pid as a bare OSError (WinError 87 from OpenProcess),
+ # not ProcessLookupError, so reading every OSError as "termination not proven" made
+ # the reclaim hold the claim and defer every tick for a worker that was already gone:
+ # 2026-10-22 t_f5fad63f kept its card ``running`` with ``claim_expires`` 2067 s past.
+ # Ask liveness again: gone is the outcome the reclaim wanted, alive stays unproven.
+ if not _kb._pid_alive(pid):
+ info["terminated"] = True
+ info["already_gone"] = True
return info
if _poll_worker_exit(pid, started_at):
@@ -1163,6 +1172,32 @@ class _CrashSweep:
exited_hook_payloads: list[dict] = field(default_factory=list)
+def _apply_attempt_note(conn, task_id, pid, dead: _DeadWorker) -> None:
+ """Fold the owner's own record of how the attempt ended into ONE dead worker's booking.
+
+ A managed worker that dies during ``worker.adopt`` writes no ``worker_result``, so the
+ exit trailer alone can read as a clean protocol violation. The owner's ``worker_lost``
+ evidence outranks it: the attempt was lost, and it must charge the breaker like any other
+ crash instead of riding the protocol-violation budget (run 730 showed
+ ``consecutive_failures = 0`` after exactly this loss).
+ """
+ from hermes_cli.kanban_owner_recovery import _latest_run_event, owner_attempt_note
+ note = owner_attempt_note(conn, task_id)
+ if not note:
+ return
+ dead.error_text = f"{dead.error_text} [{note}]"
+ dead.event_payload["attempt_note"] = note
+ lost = _latest_run_event(conn, task_id, "worker_lost")
+ if lost:
+ dead.event_payload["worker_lost"] = lost
+ dead.protocol_violation = False
+ dead.rate_limited = False
+ if dead.kind == "clean_exit":
+ # A worker whose managed execution was lost never proved the turn finished.
+ dead.kind = "worker_lost"
+ dead.error_text = f"pid {pid} exited cleanly after its managed worker was lost [{note}]"
+
+
def _reclaim_dead_workers(conn: sqlite3.Connection, board: Optional[str] = None) -> _CrashSweep:
"""Release every host-local ``running`` task whose worker PID is dead."""
sweep = _CrashSweep()
@@ -1194,6 +1229,7 @@ def _reclaim_dead_workers(conn: sqlite3.Connection, board: Optional[str] = None)
# A managed run's authority-recorded exit (its bound interpreter's, under this claim).
exit_code = managed_run_exit_code(conn, row["id"], pid, row["claim_lock"])
dead = _classify_dead_worker(pid, row["claim_lock"], exit_code, task_id=row["id"], board=board)
+ _apply_attempt_note(conn, row["id"], pid, dead)
retry_status = _kb._retry_status_for_run(conn, row["id"])
dead.event_payload["retry_status"] = retry_status
cur = conn.execute(
diff --git a/hermes_cli/kanban_owner_recovery.py b/hermes_cli/kanban_owner_recovery.py
index ece6c5cdadc..acefb4b886c 100644
--- a/hermes_cli/kanban_owner_recovery.py
+++ b/hermes_cli/kanban_owner_recovery.py
@@ -7,32 +7,62 @@ import time
import psutil
-def owner_reclaim_paused(conn, task_id):
- """Missing/ambiguous owner receipts never authorize another attempt."""
+def _owner_receipt(conn, task_id):
+ """The parsed ``owner_admitted`` receipt of the task's CURRENT run, or None.
+
+ The receipt is the owner's pointer to its own admission ledger. No receipt means the run
+ never reached an owner (a plain dispatcher worker): nothing about it is ambiguous.
+ """
marker = conn.execute(
"SELECT e.payload FROM task_events e JOIN tasks t ON t.current_run_id=e.run_id "
"WHERE t.id=? AND e.task_id=t.id AND e.kind='owner_admitted' ORDER BY e.id DESC LIMIT 1",
(task_id,)).fetchone()
if marker is None:
- return False
+ return None
try:
- binding = json.loads(marker['payload'])
- with closing(sqlite3.connect(Path(binding['db']).as_uri() + '?mode=ro', uri=True)) as owner:
+ receipt = json.loads(marker['payload'])
+ except (ValueError, TypeError):
+ return {}
+ return receipt if isinstance(receipt, dict) else {}
+
+
+def _admission_row(receipt):
+ """``(status, outcome)`` from the owner ledger ``receipt`` names, or None when unreadable.
+
+ None is "the owner said nothing we can read" — never "the owner said the attempt ended".
+ """
+ if not receipt:
+ return None
+ try:
+ with closing(sqlite3.connect(Path(receipt['db']).as_uri() + '?mode=ro', uri=True)) as owner:
row = owner.execute('SELECT status,outcome FROM session_admissions WHERE target_session_id=? AND request_id=?',
- (binding['session_id'], binding['request_id'])).fetchone()
+ (receipt['session_id'], receipt['request_id'])).fetchone()
+ except (OSError, KeyError, sqlite3.Error):
+ return None
+ return (row[0], row[1]) if row is not None else None
+
+
+def owner_reclaim_paused(conn, task_id):
+ """Missing/ambiguous owner receipts never authorize another attempt."""
+ receipt = _owner_receipt(conn, task_id)
+ if receipt is None:
+ return False
+ try:
+ row = _admission_row(receipt)
if row is not None and row[0] == 'terminal':
# Discard acknowledges uncertainty, not permission to repeat effects.
return row[1] == 'interrupted'
if row is None or row[0] in {'queued', 'unknown'}:
return True
from hermes_cli.process_identity import worker_birth
- return worker_birth(psutil.Process(binding['pid'])) != binding['birth']
+ return worker_birth(psutil.Process(receipt['pid'])) != receipt['birth']
except (OSError, ValueError, KeyError, sqlite3.Error):
return True
except psutil.Error:
return True
+
def _latest_run_event(conn, task_id, kind):
"""The newest ``kind`` payload on the task's CURRENT run, or ``{}``.
@@ -111,24 +141,50 @@ def owner_attempt_provably_over(conn, task_id) -> bool:
runs in exactly that shape. This asks the question that matters — can anything still be
executing this attempt? — from evidence the board already keeps:
- * the claim is host-local and EXPIRED (a live claim is the owner still working);
- * no heartbeat inside ``DEFAULT_CLAIM_HEARTBEAT_MAX_STALE_SECONDS``;
- * the receipt's own process is gone or recycled;
- * every worker pid recorded for the run (``tasks.worker_pid``, its ``spawned`` and
- ``worker_bound`` events) is dead or recycled.
+ * no worker pid recorded for the run is alive (``tasks.worker_pid``, its ``spawned``
+ and ``worker_bound`` events);
+ * and the attempt is over by the owner's own verdict — the admission it recorded is
+ SETTLED (``status='terminal'``) — or, when the owner left no readable verdict, the
+ host-local claim has EXPIRED with no heartbeat inside
+ ``DEFAULT_CLAIM_HEARTBEAT_MAX_STALE_SECONDS`` and the owner's own process is gone.
- Missing evidence is never proof: no recorded worker pid, a live pid whose identity
- cannot be compared, or an unreadable clock all return False and the pause holds.
+ The last clause used to demand the owner process be gone even when the owner had
+ already settled the admission. On a live install the owner is the long-lived gateway,
+ which is alive by design, so a manager-worker loss that settled the admission
+ ``terminal/interrupted`` could never be reclaimed: 2026-10-22, card t_f5fad63f held
+ ``running`` for 49 minutes after its managed worker died at ``worker.adopt`` 24 s in
+ (claim expired 34 minutes earlier, ``last_heartbeat_at`` NULL, every recorded pid dead).
+ A settled admission is the owner stating the attempt ended; it outranks the liveness of
+ the process that recorded it.
+
+ Missing evidence is never proof: no receipt, no live-or-dead pid evidence, a live pid whose
+ identity cannot be compared, or an unreadable clock all return False and the pause holds.
"""
from hermes_cli import kanban_db as kb
from hermes_cli.kanban_db_dispatch import _worker_alive
- if _latest_run_event(conn, task_id, 'worker_bound'):
- return False # a bound run is the crash sweep's to book (bound_interpreter_gone)
+ receipt = _owner_receipt(conn, task_id)
+ if receipt is None:
+ return False # no receipt: this pause did not come from an owner attempt
row = conn.execute(
"SELECT claim_lock, claim_expires, worker_pid, worker_started_at, last_heartbeat_at "
"FROM tasks WHERE id=?", (task_id,)).fetchone()
if row is None or not _host_local_lock(row['claim_lock']):
return False
+ pids = _run_worker_pids(conn, row, task_id)
+ if any(_worker_alive(pid, fingerprint) for pid, fingerprint in pids):
+ return False # a recorded interpreter is still live: it may still be executing
+ # Nothing recorded can still be executing. A SETTLED admission (the owner's own verdict that
+ # the attempt ended) is proof on its own — the owner process is a gateway, alive by design,
+ # and the claim may still be inside its TTL simply because nothing extended it.
+ try:
+ admission = _admission_row(receipt)
+ except (OSError, ValueError, KeyError, sqlite3.Error):
+ admission = None
+ if admission is not None and admission[0] == 'terminal':
+ return True
+ # Without an owner verdict, only an expired, unprogressing claim plus a gone owner proves it.
+ if not pids:
+ return False
now = int(time.time())
expires = kb._to_epoch(row['claim_expires'])
if expires is None or expires >= now:
@@ -136,12 +192,30 @@ def owner_attempt_provably_over(conn, task_id) -> bool:
heartbeat = kb._to_epoch(row['last_heartbeat_at'])
if heartbeat is not None and now - heartbeat <= kb.DEFAULT_CLAIM_HEARTBEAT_MAX_STALE_SECONDS:
return False
- if not _owner_process_gone(_latest_run_event(conn, task_id, 'owner_admitted')):
- return False
- pids = _run_worker_pids(conn, row, task_id)
- if not pids:
- return False
- return not any(_worker_alive(pid, fingerprint) for pid, fingerprint in pids)
+ return _owner_process_gone(receipt)
+
+
+def owner_attempt_note(conn, task_id) -> str:
+ """One clause naming WHY a provably-over attempt ended, or ``""``.
+
+ The reclaim paths record this beside the pid/claim evidence so the board says what
+ happened instead of a bare ``stale_lock=``: a managed worker that died (its owner
+ recorded ``worker_lost``) is a different fault from a worker that never started.
+ """
+ lost = str(_latest_run_event(conn, task_id, 'worker_lost').get('reason') or '')
+ if lost:
+ return f"managed worker lost: {lost[:80]}"
+ receipt = _owner_receipt(conn, task_id)
+ if receipt is None:
+ return ""
+ try:
+ admission = _admission_row(receipt)
+ except (OSError, ValueError, KeyError, sqlite3.Error):
+ return ""
+ if admission is not None and admission[0] == 'terminal':
+ return f"owner admission settled {admission[1] or 'terminal'}"
+ return ""
+
def owner_reclaim_blocked(conn, task_id, *, crash_sweep=False) -> bool:
diff --git a/tests/agent/test_worker_rpc_adopt_timeout.py b/tests/agent/test_worker_rpc_adopt_timeout.py
new file mode 100644
index 00000000000..81312d60600
--- /dev/null
+++ b/tests/agent/test_worker_rpc_adopt_timeout.py
@@ -0,0 +1,116 @@
+"""The ``worker.adopt`` handshake budget must survive a busy owner, and say so when it doesn't.
+
+2026-10-22: the fan gateway was mid-turn (``time=1018.3s api_calls=46``) when a kanban worker's
+``worker.adopt`` dial hit ``open_timeout=5`` and raised
+``TimeoutError: timed out while waiting for handshake response``. The managed worker died, the
+card kept saying ``running`` for 49 minutes, and nothing retried. A 5 s budget against a
+single-process gateway that legitimately serves 1000 s turns is a coin flip; the budget is now
+60 s by default (``HERMES_WORKER_RPC_OPEN_TIMEOUT`` overrides it) and a TIMED-OUT handshake is
+retried with backoff.
+"""
+from __future__ import annotations
+
+import json
+import threading
+from types import SimpleNamespace
+
+import pytest
+
+
+def _serve_owner(monkeypatch):
+ """A real loopback owner whose only answer is the method name; discovery is stubbed."""
+ from websockets.sync.server import serve
+ from hermes_cli import gateway_client, gateway_runtime
+ import hermes_cli.gateway_runtime_discovery as discovery
+
+ def owner(ws):
+ request = json.loads(ws.recv())
+ ws.send(json.dumps({'jsonrpc': '2.0', 'id': request['id'],
+ 'result': {'method': request['method']}}))
+
+ server = serve(owner, '127.0.0.1', 0, subprotocols=['hermes-gateway-v1'])
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ endpoint = SimpleNamespace(api_origin=f'http://127.0.0.1:{server.socket.getsockname()[1]}',
+ control_home=None)
+ monkeypatch.setattr(gateway_runtime, 'discover_gateway_endpoint',
+ lambda home, timeout: SimpleNamespace(state='ready', endpoint=endpoint))
+ monkeypatch.setattr(discovery, 'query_identify', lambda home, timeout: {'pid': -1})
+ monkeypatch.setattr(gateway_client, '_session_ticket', lambda home, endpoint, purpose: 'ticket')
+ return server
+
+
+def test_the_handshake_budget_defaults_to_60s_and_is_configurable(monkeypatch, tmp_path):
+ import websockets.sync.client as ws_client
+ from agent import runtime_session_store as store
+
+ real_connect, seen = ws_client.connect, {}
+
+ def spy(url, **kwargs):
+ seen.update(kwargs)
+ return real_connect(url, **kwargs)
+
+ monkeypatch.setattr(ws_client, 'connect', spy)
+ server = _serve_owner(monkeypatch)
+ try:
+ assert store.WorkerRPC(tmp_path)('worker.persist') == {'method': 'worker.persist'}
+ assert seen['open_timeout'] == 60.0 # NOT the old 5 s coin flip
+ monkeypatch.setenv('HERMES_WORKER_RPC_OPEN_TIMEOUT', '90')
+ assert store.worker_rpc_open_timeout() == 90.0
+ seen.clear()
+ assert store.WorkerRPC(tmp_path)('worker.persist') == {'method': 'worker.persist'}
+ assert seen['open_timeout'] == 90.0
+ finally:
+ server.shutdown()
+
+
+def test_a_timed_out_handshake_is_retried_and_the_call_still_lands(monkeypatch, tmp_path):
+ import websockets.sync.client as ws_client
+ from agent import runtime_session_store as store
+
+ real_connect = ws_client.connect
+ calls = []
+
+ def flaky(url, **kwargs):
+ calls.append(kwargs['open_timeout'])
+ if len(calls) < 3:
+ raise TimeoutError('timed out while waiting for handshake response')
+ return real_connect(url, **kwargs)
+
+ monkeypatch.setattr(ws_client, 'connect', flaky)
+ monkeypatch.setattr(store, 'WORKER_RPC_RETRY_SLEEP_SECONDS', 0.0)
+ server = _serve_owner(monkeypatch)
+ try:
+ assert store.WorkerRPC(tmp_path)('worker.adopt') == {'method': 'worker.adopt'}
+ finally:
+ server.shutdown()
+ assert len(calls) == 3
+
+
+def test_connect_worker_link_backs_off_only_on_timeouts(monkeypatch):
+ from agent import runtime_session_store as store
+ delays, attempts = [], []
+
+ def sleeper(seconds):
+ delays.append(seconds)
+
+ def timeout_twice_then_ok(url, **kwargs):
+ attempts.append(kwargs['open_timeout'])
+ if len(attempts) < 3:
+ raise TimeoutError('busy owner')
+ return 'link'
+
+ assert store.connect_worker_link(timeout_twice_then_ok, 'ws://x', ['p'],
+ open_timeout=60, sleep=sleeper) == 'link'
+ assert delays == [1.0, 2.0]
+ assert attempts == [60.0, 60.0, 60.0]
+
+ attempts.clear()
+ delays.clear()
+
+ def auth_failure(url, **kwargs):
+ attempts.append(kwargs['open_timeout'])
+ raise OSError('handshake rejected')
+
+ with pytest.raises(OSError):
+ store.connect_worker_link(auth_failure, 'ws://x', ['p'], open_timeout=60, sleep=sleeper)
+ assert len(attempts) == 1 and delays == [] # a rejected handshake never heals by retrying
diff --git a/tests/hermes_cli/test_kanban_managed_worker_loss.py b/tests/hermes_cli/test_kanban_managed_worker_loss.py
new file mode 100644
index 00000000000..6cd7df4b8f1
--- /dev/null
+++ b/tests/hermes_cli/test_kanban_managed_worker_loss.py
@@ -0,0 +1,313 @@
+"""A lost managed worker must be DISPOSED OF on the board, within one dispatcher tick.
+
+Regression for the 2026-10-22 stall (card ``t_f5fad63f``, run 730). The fan gateway's managed
+worker died 24 s into the attempt, inside the ``worker.adopt`` handshake
+(``TimeoutError: timed out while waiting for handshake response``, ``open_timeout=5``). The
+gateway logged ``Managed worker lost: managed_worker_failed``, settled the admission
+``terminal/interrupted`` — and the card went on saying ``running`` for 49 minutes:
+
+ * ``tasks.claim_expires`` was 2067 s in the past and ``last_heartbeat_at`` was NULL;
+ * every recorded worker pid was dead;
+ * ``consecutive_failures`` stayed 0, so the ``failure_limit`` breaker never applied;
+ * ``release_stale_claims`` and ``detect_crashed_workers`` both declined: the owner receipt
+ was "ambiguous", and ``owner_attempt_provably_over`` required the OWNER PROCESS to be
+ gone — but the owner is the live gateway. Only a human ``reclaim`` ended it.
+
+These tests pin the disposition the dispatcher owes every lost attempt:
+
+ A1 a killed worker under a live claim is booked ``crashed`` within one tick;
+ A2 an elapsed ``claim_expires`` never leaves the card ``running`` after one tick, even
+ with no heartbeat and no pid (and even behind a settled owner receipt);
+ A3 every such booking increments ``consecutive_failures``, so ``kanban.failure_limit``
+ covers this outcome class and the card blocks at the limit.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sqlite3
+import time
+from pathlib import Path
+
+import psutil
+import pytest
+
+from hermes_cli import kanban_db as kb
+from hermes_cli import kanban_db_connect as kbc
+from hermes_cli import kanban_db_dispatch as kbd
+from hermes_cli import kanban_owner_recovery
+
+NOW = int(time.time())
+HOST = kb._claimer_id().split(":", 1)[0]
+FINGERPRINT = "6a232414-2dbf-40ab-a534-d9b71db05658:116|4162240"
+
+
+def _absent_pid(base: int = 3_800_000) -> int:
+ pid = base
+ while psutil.pid_exists(pid):
+ pid += 1
+ return pid
+
+
+def board(tmp_path, monkeypatch):
+ """An isolated HERMES_HOME board plus the owner ledger a receipt points at."""
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setenv("HERMES_KANBAN_CRASH_GRACE_SECONDS", "0")
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ kb.init_db()
+ conn = kbc.connect()
+ ledger = tmp_path / "state.db"
+ with sqlite3.connect(ledger) as store:
+ store.execute(
+ "CREATE TABLE session_admissions "
+ "(target_session_id TEXT, request_id TEXT, status TEXT, outcome TEXT)"
+ )
+ scratch = _Board(conn, ledger)
+ yield scratch
+ conn.close()
+
+
+class _Board:
+ def __init__(self, conn, ledger: Path):
+ self.conn = conn
+ self.ledger = ledger
+
+ # --- seeding ----------------------------------------------------------------------
+ def running(
+ self, tid: str = "t_lost", *, worker_pid=None, record_worker_pid: bool = True,
+ claim_expires_in: int = 900, heartbeat_age=None, owner: bool = True,
+ admission=("terminal", "interrupted"), worker_lost=None, dead_seconds: int = 120,
+ ) -> int:
+ """A ``running`` card whose worker died the way run 730's did."""
+ worker_pid = _absent_pid() if worker_pid is None else int(worker_pid)
+ lock = f"{HOST}:{_absent_pid(base=3_900_000)}"
+ started = NOW - dead_seconds
+ run_id = int(self.conn.execute(
+ "INSERT INTO task_runs (task_id, profile, status, claim_lock, claim_expires, "
+ "worker_pid, started_at) VALUES (?, 'fan', 'running', ?, ?, ?, ?)",
+ (tid, lock, NOW + claim_expires_in, worker_pid if record_worker_pid else None, started),
+ ).lastrowid)
+ self.conn.execute(
+ "INSERT INTO tasks (id, title, assignee, status, created_at, claim_lock, claim_expires, "
+ "worker_pid, worker_started_at, last_heartbeat_at, current_run_id, started_at, priority) "
+ "VALUES (?, ?, 'fan', 'running', ?, ?, ?, ?, ?, ?, ?, ?, 5)",
+ (tid, tid, NOW - 86400, lock, NOW + claim_expires_in,
+ worker_pid if record_worker_pid else None,
+ FINGERPRINT if record_worker_pid else None,
+ (NOW - heartbeat_age) if heartbeat_age is not None else None, run_id, started),
+ )
+ self.event(tid, run_id, "claimed", {"lock": lock, "expires": NOW - claim_expires_in * 0}, started)
+ self.event(tid, run_id, "spawned",
+ {"pid": worker_pid, "started_at": FINGERPRINT} if record_worker_pid else {}, started)
+ if owner:
+ request_id = f'kanban:["default","{tid}",{run_id}]'
+ self.event(tid, run_id, "owner_admitted",
+ {"db": str(self.ledger), "session_id": "sess-1", "pid": _absent_pid(base=3_950_000),
+ "request_id": request_id}, started + 3)
+ if admission:
+ with sqlite3.connect(self.ledger) as store:
+ store.execute("INSERT INTO session_admissions VALUES ('sess-1', ?, ?, ?)",
+ (request_id, admission[0], admission[1]))
+ if worker_lost:
+ self.event(tid, run_id, "worker_lost",
+ {"reason": worker_lost, "claim_lock": lock, "run_id": run_id,
+ "pid": worker_pid, "bound": False}, started + 24)
+ self.conn.commit()
+ return run_id
+
+ def event(self, tid: str, run: int, kind: str, payload: dict, ts: int) -> None:
+ self.conn.execute(
+ "INSERT INTO task_events (task_id, run_id, kind, payload, created_at) "
+ "VALUES (?, ?, ?, ?, ?)", (tid, run, kind, json.dumps(payload), ts))
+
+ # --- reading ---------------------------------------------------------------------
+ def state(self, tid: str) -> dict:
+ return dict(self.conn.execute("SELECT * FROM tasks WHERE id = ?", (tid,)).fetchone())
+
+ def run(self, run_id: int) -> dict:
+ return dict(self.conn.execute("SELECT * FROM task_runs WHERE id = ?", (run_id,)).fetchone())
+
+ def tick(self, *, failure_limit: int | None = None) -> kbd.DispatchResult:
+ """One real dispatcher tick: reclaim phase + promotion, no spawn slot."""
+ return kbd.dispatch_once(self.conn, max_spawn=0, failure_limit=failure_limit,
+ stale_timeout_seconds=0)
+
+
+# --- A1: a killed worker under a LIVE claim is booked crashed within one tick --------------
+
+def test_a_killed_managed_worker_is_disposed_of_within_one_tick(board):
+ run_id = board.running("t_killed", claim_expires_in=900, heartbeat_age=30,
+ worker_lost="managed_worker_failed")
+ board.tick(failure_limit=2)
+ row, run = board.state("t_killed"), board.run(run_id)
+ assert row["status"] == "ready" # left ``running``
+ assert (row["claim_lock"], row["worker_pid"], row["current_run_id"]) == (None, None, None)
+ assert run["outcome"] == "crashed"
+ assert "managed worker lost: managed_worker_failed" in run["error"]
+ assert json.loads(run["metadata"])["attempt_note"] == "managed worker lost: managed_worker_failed"
+ assert row["consecutive_failures"] == 1 # A3: the breaker sees it
+ assert row["last_failure_error"]
+
+
+def test_a_killed_managed_worker_blocks_the_card_at_the_failure_limit(board):
+ """The breaker covers this class: one loss short of the limit, the next loss blocks.
+
+ ``_account_crashes`` books a plain crash against ``DEFAULT_FAILURE_LIMIT`` (the sweep
+ resolves the threshold there rather than against the dispatcher's ``failure_limit``),
+ so the card is seeded one failure short of that limit instead of pinning a threshold
+ this path never reads.
+ """
+ board.running("t_killed", claim_expires_in=900, heartbeat_age=30,
+ worker_lost="managed_worker_failed")
+ board.conn.execute("UPDATE tasks SET consecutive_failures = ? WHERE id = 't_killed'",
+ (kbd.DEFAULT_FAILURE_LIMIT - 1,))
+ board.conn.commit()
+ board.tick()
+ row = board.state("t_killed")
+ assert row["status"] == "blocked"
+ assert row["consecutive_failures"] == kbd.DEFAULT_FAILURE_LIMIT
+ kinds = [r["kind"] for r in board.conn.execute(
+ "SELECT kind FROM task_events WHERE task_id = 't_killed' ORDER BY id")]
+ assert "gave_up" in kinds
+
+
+def test_a_lost_worker_that_exited_cleanly_still_charges_the_breaker(board):
+ """rc=0 after a lost managed execution is not a protocol violation: the turn never ran."""
+ run_id = board.running("t_clean", claim_expires_in=900, heartbeat_age=30,
+ worker_lost="managed_worker_failed")
+ # The worker's own exit trailer says rc=0 (the CLI's epilogue after a lost turn).
+ log = kb.worker_log_path("t_clean")
+ log.parent.mkdir(parents=True, exist_ok=True)
+ from hermes_cli.quiet_single_query import KANBAN_WORKER_EXIT_TRAILER
+ log.write_text(f"{KANBAN_WORKER_EXIT_TRAILER}0\n", encoding="utf-8")
+ board.tick(failure_limit=2)
+ run = board.run(run_id)
+ assert run["outcome"] == "crashed"
+ assert "managed worker lost" in run["error"]
+ assert board.state("t_clean")["consecutive_failures"] == 1
+
+
+# --- A2: an elapsed claim lock is never "still running" after one tick ---------------------
+
+ dict(record_worker_pid=False, owner=False), # no pid, no owner at all
+ dict(record_worker_pid=False, owner=True), # no pid, settled receipt
+ dict(owner=False), # dead pid, no owner
+ dict(owner=True, worker_lost="managed_worker_failed"), # the incident shape
+], ids=["no-pid", "no-pid-receipt", "dead-pid", "dead-pid-lost"])
+def test_an_elapsed_claim_never_stays_running_after_one_tick(board, shape):
+ run_id = board.running("t_lapsed", claim_expires_in=-2067, heartbeat_age=None, **shape)
+ board.tick(failure_limit=2)
+ row, run = board.state("t_lapsed"), board.run(run_id)
+ assert row["status"] != "running"
+ assert row["status"] == "ready"
+ assert run["outcome"] in {"crashed", "reclaimed"}
+ assert run["error"]
+ assert row["consecutive_failures"] == 1
+
+
+def test_the_incident_shape_names_the_loss_on_the_reclaim(board):
+ """Run 730's exact shape, behind a settled receipt: the reclaim says what happened."""
+ run_id = board.running("t_730", claim_expires_in=-2067, owner=True,
+ worker_lost="managed_worker_failed")
+ board.tick(failure_limit=2)
+ run = board.run(run_id)
+ assert run["outcome"] == "reclaimed"
+ assert "managed worker lost: managed_worker_failed" in run["error"]
+ event = board.conn.execute(
+ "SELECT payload FROM task_events WHERE task_id = 't_730' AND kind = 'reclaimed' "
+ "ORDER BY id DESC LIMIT 1").fetchone()
+ assert json.loads(event["payload"])["attempt_note"] == "managed worker lost: managed_worker_failed"
+
+
+def test_a_settled_receipt_with_a_live_gateway_owner_no_longer_holds_the_claim(board):
+ """The fence itself: a live owner PROCESS is not a live ATTEMPT."""
+ board.running("t_gateway", claim_expires_in=-2067, owner=True, admission=("terminal", "interrupted"))
+ assert kanban_owner_recovery.owner_reclaim_paused(board.conn, "t_gateway") is True
+ assert kanban_owner_recovery.owner_attempt_provably_over(board.conn, "t_gateway") is True
+ board.tick(failure_limit=2)
+ assert board.state("t_gateway")["status"] == "ready"
+
+
+# --- the reclaim's kill step: an absent pid is gone, not "survived" -----------------------
+
+def test_terminating_an_absent_pid_reports_terminated(board):
+ """A pid that is already gone must not be reported as unproven termination.
+
+ Windows raises a bare ``OSError`` (WinError 87) for an absent PID instead of
+ ``ProcessLookupError``; reading that as "termination not proven" made the reclaim hold
+ the claim and defer every tick — the elapsed lock stayed ``running`` forever.
+ """
+ info = kbd._terminate_reclaimed_worker(_absent_pid(), f"{HOST}:{_absent_pid(base=3_960_000)}")
+ assert info["host_local"] is True
+ assert info["termination_attempted"] is True
+ assert info["terminated"] is True
+ if os.name == "nt":
+ # Only Windows reports an absent pid as a bare OSError, so only there does the kill
+ # step take the re-ask branch that marks this verdict; POSIX reaches the same
+ # ``terminated`` through ProcessLookupError (pinned on every platform by
+ # test_a_signalled_absent_pid_is_terminated_not_unproven).
+ assert info["already_gone"] is True
+
+
+def test_a_signalled_absent_pid_is_terminated_not_unproven(board):
+ """The same reading through a signal seam: an OSError on a dead pid is a success."""
+ gone = _absent_pid(base=3_970_000)
+
+ def windows_kill(pid, sig):
+ raise OSError(87, "The parameter is incorrect")
+
+ info = kbd._terminate_reclaimed_worker(gone, f"{HOST}:{_absent_pid(base=3_980_000)}",
+ signal_fn=windows_kill)
+ assert info["terminated"] is True
+ assert info["already_gone"] is True
+
+
+# --- D1: the OWNER writes the loss where the dispatcher can read it -----------------------
+# ``worker.adopt`` precedes ``bind_worker_context``, so a worker that dies in the handshake
+# writes neither ``worker_bound`` nor ``worker_result``: without this event the run learns
+# nothing about its own loss and the dispatcher can only guess from a dead pid.
+
+def _owner_policy(board, tid, run_id):
+ from types import SimpleNamespace
+ row = board.state(tid)
+ return SimpleNamespace(kanban_json=json.dumps({
+ "task_id": tid, "db": str(kb.kanban_db_path()), "run_id": run_id,
+ "claim_lock": row["claim_lock"], "board": None,
+ }))
+
+
+def test_the_owner_records_the_loss_on_the_board_and_one_tick_disposes_of_it(board):
+ from gateway.session_kanban import record_worker_loss
+ run_id = board.running("t_owner", claim_expires_in=900, heartbeat_age=30)
+ policy = _owner_policy(board, "t_owner", run_id)
+ record_worker_loss(policy, "managed_worker_failed", pid=board.state("t_owner")["worker_pid"],
+ bound=False)
+ event = board.conn.execute(
+ "SELECT payload FROM task_events WHERE task_id='t_owner' AND kind='worker_lost' "
+ "ORDER BY id DESC LIMIT 1").fetchone()
+ assert json.loads(event["payload"])["reason"] == "managed_worker_failed"
+
+ board.tick(failure_limit=2)
+ run = board.run(run_id)
+ assert run["outcome"] == "crashed"
+ assert "managed worker lost: managed_worker_failed" in run["error"]
+ assert board.state("t_owner")["consecutive_failures"] == 1
+
+
+def test_a_loss_recorded_against_a_superseded_run_is_dropped(board):
+ """The owner's note is run-scoped: it may never be evidence about a LATER attempt."""
+ from gateway.session_kanban import record_worker_loss
+ run_id = board.running("t_stale", claim_expires_in=900, heartbeat_age=30)
+ policy = _owner_policy(board, "t_stale", run_id)
+ board.conn.execute("UPDATE tasks SET status='ready', current_run_id=NULL WHERE id='t_stale'")
+ board.conn.commit()
+ record_worker_loss(policy, "managed_worker_failed", pid=1234, bound=False)
+ n = board.conn.execute(
+ "SELECT count(*) FROM task_events WHERE task_id='t_stale' AND kind='worker_lost'"
+ ).fetchone()[0]
+ assert n == 0
diff --git a/tests/hermes_cli/test_kanban_owner_receipt_reclaim.py b/tests/hermes_cli/test_kanban_owner_receipt_reclaim.py
index 7364fc62366..c7c87dd1fb4 100644
--- a/tests/hermes_cli/test_kanban_owner_receipt_reclaim.py
+++ b/tests/hermes_cli/test_kanban_owner_receipt_reclaim.py
@@ -185,11 +185,15 @@ def test_dead_attempt_behind_an_unresolved_receipt_is_named_and_reclaimed(board)
dict(worker_pid=os.getpid(), worker_fingerprint=kbd._process_fingerprint(os.getpid())), # live worker
dict(worker_bound=True, worker_pid=os.getpid(),
worker_fingerprint=kbd._process_fingerprint(os.getpid())), # live bound interpreter
- dict(heartbeat_age=300), # fresh heartbeat
- dict(expires_age_seconds=-3600), # live claim
+ # Each remaining case models an attempt that MAY still be executing, so its admission is
+ # UNSETTLED (``started``) — the shape a live attempt really has. A settled admission is the
+ # owner's own verdict that the attempt ended and is proof on its own; see
+ # test_a_settled_admission_is_proof_even_while_the_owner_gateway_is_alive below.
+ dict(heartbeat_age=300, admission=("started", None)), # fresh heartbeat
+ dict(expires_age_seconds=-3600, admission=("started", None)), # live claim
dict(lock_host="some-other-host"), # foreign host
- dict(owner_pid=os.getpid(), owner_birth=None), # live, uncomparable owner
- dict(record_worker_pid=False), # no pid recorded
+ dict(owner_pid=os.getpid(), owner_birth=None, admission=("started", None)), # live owner in flight
+ dict(record_worker_pid=False, admission=("started", None)), # no pid recorded
], ids=["live-worker", "live-bound", "fresh-heartbeat", "live-claim", "foreign-host", "live-owner", "no-pid"])
def test_the_pause_still_holds_every_attempt_that_may_be_alive(board, shape):
"""Missing evidence is never proof: reclaiming beside a possibly-live attempt repeats its effects."""
@@ -200,6 +204,32 @@ def test_the_pause_still_holds_every_attempt_that_may_be_alive(board, shape):
assert board.state("t_ghost")["status"] == "running"
+def test_a_settled_admission_is_proof_even_while_the_owner_gateway_is_alive(board):
+ """The 2026-10-22 stall: owner = the long-lived gateway, admission settled ``interrupted``.
+
+ Card t_f5fad63f's managed worker died at ``worker.adopt`` 24 s in. The gateway settled the
+ admission ``terminal/interrupted`` and recorded nothing on the board, the claim expired
+ 34 minutes before anyone noticed, ``last_heartbeat_at`` was NULL and every recorded pid was
+ dead — yet ``owner_attempt_provably_over`` demanded the OWNER process be gone. The owner is
+ the gateway, which is alive by design, so every reclaim path declined for 49 minutes.
+ """
+ board.dead_attempt("t_ghost2") # admission=("terminal", "interrupted"), dead owner pid
+ board.dead_attempt("t_gateway", owner_pid=os.getpid(), owner_birth=None,
+ admission=("terminal", "interrupted"))
+ assert owner_reclaim_paused(board.conn, "t_gateway") is True # effects still uncertain
+ assert owner_attempt_provably_over(board.conn, "t_gateway") is True
+ assert kb.release_stale_claims(board.conn) == 2
+ row = board.state("t_gateway")
+ assert (row["status"], row["claim_lock"], row["worker_pid"]) == ("ready", None, None)
+ run = board.conn.execute(
+ "SELECT outcome, error FROM task_runs WHERE task_id = 't_gateway'").fetchone()
+ assert run["outcome"] == "reclaimed"
+ assert "owner admission settled interrupted" in run["error"]
+ # Booked against the breaker like any other non-completing attempt (A3).
+ assert board.state("t_gateway")["consecutive_failures"] == 1
+
+
+
# --- the gate is decided under the same write lock as the release ---------------------------
_RECLAIM_PATHS = {