Skip to content

The agent that grows with you

refactor(kanban): keep the lost-worker folds in kanban_owner_recovery, drop the FILE_LINES waivers

kshitijk4poora0712a5db1bd
diff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.py
index 8cf19f25d06..cff3def20be 100644
--- a/hermes_cli/kanban_db.py
+++ b/hermes_cli/kanban_db.py
@@ -1,4 +1,3 @@
-# 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
@@ -2354,7 +2353,7 @@ def release_stale_claims(
"WHERE status = 'running' AND claim_expires IS NOT NULL "
" AND claim_expires < ?", (now,),
).fetchall()
- from hermes_cli.kanban_owner_recovery import owner_reclaim_blocked, owner_reclaim_blocked_after_kill
+ from hermes_cli.kanban_owner_recovery import owner_reclaim_blocked, owner_reclaim_blocked_after_kill, reclaim_error
for row in stale:
if owner_reclaim_blocked(conn, row["id"]):
continue
@@ -2384,7 +2383,7 @@ def release_stale_claims(
# changes neither claim_lock nor worker_pid, so the CAS below cannot see it.
if owner_reclaim_blocked_after_kill(conn, row["id"], signalled=bool(termination.get("termination_attempted"))):
continue
- retry_status = _retry_status_for_run(conn, row["id"])
+ retry_status, error = _retry_status_for_run(conn, row["id"]), reclaim_error(conn, row["id"], row["claim_lock"])
cur = conn.execute(
"UPDATE tasks SET status = ?, claim_lock = NULL, "
"claim_expires = NULL, worker_pid = NULL, worker_started_at = NULL "
@@ -2396,11 +2395,6 @@ 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=error,
@@ -2413,7 +2407,6 @@ 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
diff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.py
index ebebe54c7e5..5585ace432b 100644
--- a/hermes_cli/kanban_db_dispatch.py
+++ b/hermes_cli/kanban_db_dispatch.py
@@ -1,4 +1,3 @@
-# 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
@@ -480,16 +479,10 @@ def _terminate_reclaimed_worker(
info["termination_attempted"] = True
try:
kill(int(pid), signal.SIGTERM)
- except ProcessLookupError:
- # Already gone = successful termination. Leaving terminated=False would
- # make the reclaim guard misread a dead worker as alive and defer forever.
- info["terminated"] = True
- return info
except OSError:
- # Windows reports an ABSENT pid as a bare OSError (WinError 87), not ProcessLookupError:
- # ask liveness again, so a gone pid is terminated and only a live one stays unproven.
- if not _kb._pid_alive(pid):
- info["terminated"] = True
+ # Already gone = successful termination (Windows reports an absent pid as a bare OSError, not
+ # ProcessLookupError). Leaving terminated=False would make the reclaim defer forever.
+ info["terminated"] = not _kb._pid_alive(pid)
return info
if _poll_worker_exit(pid, started_at):
@@ -1168,31 +1161,6 @@ 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 in ``worker.adopt`` writes no ``worker_result``, so its rc=0
- exit trailer reads as a protocol violation. The owner's ``worker_lost`` evidence outranks
- it: the turn never finished, so it books as a crash and charges the breaker, and the
- protocol-violation streak (which reads the persisted payload) does not count it.
- """
- 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
- if dead.protocol_violation:
- dead.protocol_violation = False
- dead.event_payload.pop("protocol_violation", None)
- dead.event_payload["exit_kind"] = dead.kind
- dead.event_kind = "crashed"
- 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()
@@ -1203,7 +1171,7 @@ def _reclaim_dead_workers(conn: sqlite3.Connection, board: Optional[str] = None)
"WHERE status = 'running' AND worker_pid IS NOT NULL"
).fetchall()
host_prefix = _kb._host_prefix()
- from hermes_cli.kanban_owner_recovery import managed_run_exit_code, owner_reclaim_blocked
+ from hermes_cli.kanban_owner_recovery import apply_attempt_note, managed_run_exit_code, owner_reclaim_blocked
for row in rows:
lock = row["claim_lock"] or ""
if not lock.startswith(host_prefix):
@@ -1224,7 +1192,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)
+ 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 ecb6e780925..5687b95ca61 100644
--- a/hermes_cli/kanban_owner_recovery.py
+++ b/hermes_cli/kanban_owner_recovery.py
@@ -205,6 +205,36 @@ def owner_attempt_note(conn, task_id) -> str:
return ""
+def reclaim_error(conn, task_id, claim_lock) -> str:
+ """A stale-lock reclaim's run error, naming how the attempt ended when the owner recorded it."""
+ note = owner_attempt_note(conn, task_id)
+ return f"stale_lock={claim_lock}" + (f" [{note}]" if note else "")
+
+
+def apply_attempt_note(conn, task_id, pid, dead) -> None:
+ """Fold the owner's own record of how the attempt ended into ONE dead worker's booking.
+
+ A managed worker that dies in ``worker.adopt`` writes no ``worker_result``, so its rc=0
+ exit trailer reads as a protocol violation. The owner's ``worker_lost`` evidence outranks
+ it: the turn never finished, so it books as a crash and charges the breaker, and the
+ protocol-violation streak (which reads the persisted payload) does not count it.
+ """
+ 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
+ if dead.protocol_violation:
+ dead.protocol_violation = False
+ dead.event_payload.pop("protocol_violation", None)
+ dead.event_payload["exit_kind"] = dead.kind
+ dead.event_kind = "crashed"
+ dead.error_text = f"pid {pid} exited cleanly after its managed worker was lost [{note}]"
+
+
def owner_reclaim_blocked(conn, task_id, *, crash_sweep=False) -> bool:
"""True when a reclaim path must leave this task alone.
diff --git a/tests/hermes_cli/test_kanban_managed_worker_loss.py b/tests/hermes_cli/test_kanban_managed_worker_loss.py
index 3284917293e..ecf3578d231 100644
--- a/tests/hermes_cli/test_kanban_managed_worker_loss.py
+++ b/tests/hermes_cli/test_kanban_managed_worker_loss.py
@@ -1,19 +1,9 @@
"""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:
+Regression for a card that stayed ``running`` for 49 minutes after its managed worker died in
+the ``worker.adopt`` handshake (claim long expired, every recorded pid dead, the owner gateway
+alive and its admission settled ``terminal/interrupted``). 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
@@ -81,7 +71,7 @@ class _Board:
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."""
+ """A ``running`` card whose managed worker was lost."""
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
@@ -216,7 +206,7 @@ def test_an_elapsed_claim_never_stays_running_after_one_tick(board, shape):
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."""
+ """The incident 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)