The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(kanban): reap workers that outlive their finished run
teknium1aa5817d9be83
diff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.pyindex 4f4b625f74f..04198a301bb 100644--- a/hermes_cli/kanban_db.py+++ b/hermes_cli/kanban_db.py@@ -229,7 +229,7 @@ def notify_task_updated(# DispatchResult counters whose non-zero value means the tick did something._TICK_ACTIVITY_FIELDS = (- "spawned", "reclaimed", "promoted", "reconciled_orphans", "crashed", "stale",+ "spawned", "reclaimed", "promoted", "reconciled_orphans", "reaped_terminal_workers", "crashed", "stale","timed_out", "auto_blocked", "rate_limited", "auto_assigned_default","respawn_guarded", "skipped_per_profile_capped", "skipped_unassigned","skipped_nonspawnable",@@ -1000,6 +1000,10 @@ CREATE TABLE IF NOT EXISTS task_runs (claim_lock TEXT,claim_expires INTEGER,worker_pid INTEGER,+ -- Spawn-time start fingerprint of worker_pid (see tasks.worker_started_at). Retained with+ -- worker_pid after the run ends so a worker that outlives its terminal transition can+ -- still be found and reaped; NULL = legacy row, never signalled.+ worker_started_at INTEGER,max_runtime_seconds INTEGER,last_heartbeat_at INTEGER,started_at INTEGER NOT NULL,@@ -1909,7 +1913,12 @@ def _end_run(error: Optional[str] = None, metadata: Optional[dict] = None, status: Optional[str] = None,) -> Optional[int]:"""Close the active run (``status`` defaults to ``outcome``) and clear- ``current_run_id``; None when no run was active (never-claimed task)."""+ ``current_run_id``; None when no run was active (never-claimed task).++ ``worker_pid`` / ``worker_started_at`` / ``claim_lock`` stay on the closed+ row: they are the only evidence left of the OS process once the task row+ is wiped, and :func:`kanban_db_dispatch.reap_terminal_workers` needs them+ to end a worker that survived its own terminal transition."""now = int(time.time())run_id = _current_run_id(conn, task_id)if run_id is None:@@ -1923,9 +1932,7 @@ def _end_run(error = ?,metadata = ?,ended_at = ?,- claim_lock = NULL,- claim_expires = NULL,- worker_pid = NULL+ claim_expires = NULLWHERE id = ?AND ended_at IS NULL""",diff --git a/hermes_cli/kanban_db_connect.py b/hermes_cli/kanban_db_connect.pyindex 1f863ecd4a8..1bf4f183bfc 100644--- a/hermes_cli/kanban_db_connect.py+++ b/hermes_cli/kanban_db_connect.py@@ -831,6 +831,12 @@ _NOTIFY_SUB_COLUMNS = (("delivery_metadata", "delivery_metadata TEXT"),)+_TASK_RUN_COLUMNS = (+ # Spawn-time start fingerprint of the run's worker_pid (PID-reuse guard for the+ # terminal-worker reaper; NULL = legacy row, never signalled).+ ("worker_started_at", "worker_started_at INTEGER"),+)+def _column_names(conn: sqlite3.Connection, table: str) -> set[str]:return {row["name"] for row in conn.execute(f"PRAGMA table_info({table})")}@@ -902,6 +908,10 @@ def _migrate_add_optional_columns(conn: sqlite3.Connection) -> None:)if _table_exists(conn, "task_runs"):+ run_cols = _column_names(conn, "task_runs")+ for name, ddl in _TASK_RUN_COLUMNS:+ if name not in run_cols:+ _add_column_if_missing(conn, "task_runs", name, ddl)_backfill_legacy_inflight_runs(conn)# One-shot event-kind rename: old names still worked but were awkward on@@ -1001,7 +1011,7 @@ _REBUILD_SPECS = {" id INTEGER PRIMARY KEY AUTOINCREMENT,"" task_id TEXT NOT NULL, profile TEXT, step_key TEXT,"" status TEXT NOT NULL, claim_lock TEXT, claim_expires INTEGER,"- " worker_pid INTEGER, max_runtime_seconds INTEGER,"+ " worker_pid INTEGER, worker_started_at INTEGER, max_runtime_seconds INTEGER,"" last_heartbeat_at INTEGER, started_at INTEGER NOT NULL,"" ended_at INTEGER, outcome TEXT, summary TEXT, metadata TEXT,"" error TEXT)",diff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.pyindex 0347b3f8061..e711c7ff8a0 100644--- a/hermes_cli/kanban_db_dispatch.py+++ b/hermes_cli/kanban_db_dispatch.py@@ -93,6 +93,9 @@ class DispatchResult:reconciled_orphans: list[str] = field(default_factory=list)"""``running`` cards requeued by :func:`reconcile_orphaned_running` (brokenclaim bookkeeping, dead/gone worker)."""+ reaped_terminal_workers: list[str] = field(default_factory=list)+ """Task ids whose worker outlived its closed run and was terminated by+ :func:`reap_terminal_workers`."""spawned: list[tuple[str, str, str]] = field(default_factory=list)"""``(task_id, assignee, workspace_path)`` triples."""skipped_unassigned: list[str] = field(default_factory=list)@@ -389,6 +392,47 @@ def _terminate_reclaimed_worker(return info+def reap_terminal_workers(conn: sqlite3.Connection, *, signal_fn=None) -> list[str]:+ """End host-local workers that outlived their run (issue #111791) — a worker+ that called ``kanban_complete`` and then hung keeps its ``state.db`` sidecar+ fds open and no ``running``-only sweep can see it once ``tasks.worker_pid`` is+ cleared. Keys on the closed ``task_runs`` row's retained pid + spawn+ fingerprint: a legacy row (NULL fingerprint) or a recycled PID is never+ signalled; a pid that is simply gone just has its evidence cleared. Returns+ the task ids whose worker was terminated."""+ rows = conn.execute(+ "SELECT id, task_id, worker_pid, worker_started_at, claim_lock FROM task_runs "+ "WHERE ended_at IS NOT NULL AND worker_pid IS NOT NULL AND worker_started_at IS NOT NULL"+ ).fetchall()+ host_prefix = _kb._host_prefix()+ reaped: list[str] = []+ for row in rows:+ pid, fingerprint = int(row["worker_pid"]), int(row["worker_started_at"])+ if pid == os.getpid() or not str(row["claim_lock"] or "").startswith(host_prefix):+ continue+ alive = _worker_alive(pid, fingerprint)+ termination = None+ if alive:+ termination = _terminate_reclaimed_worker(+ pid, row["claim_lock"], signal_fn=signal_fn, started_at=fingerprint)+ if not termination["terminated"]:+ continue # still alive: try again next tick+ with _kb.write_txn(conn):+ conn.execute(+ "UPDATE task_runs SET worker_pid = NULL, worker_started_at = NULL "+ "WHERE id = ? AND worker_pid = ? AND worker_started_at = ?",+ (row["id"], pid, fingerprint),+ )+ if alive:+ _kb._append_event(+ conn, row["task_id"], "terminal_worker_reaped",+ {"pid": pid, "worker_started_at": fingerprint, **termination}, run_id=row["id"],+ )+ if alive:+ reaped.append(row["task_id"])+ return reaped++def _worker_survived_termination(termination: dict) -> bool:"""True when we tried to kill our own host-local worker and it is still alive.@@ -1172,7 +1216,8 @@ def _set_worker_pid(conn: sqlite3.Connection, task_id: str, pid: int) -> None:(int(pid), started_at, task_id))run_id = _kb._current_run_id(conn, task_id)if run_id is not None:- conn.execute("UPDATE task_runs SET worker_pid = ? WHERE id = ?", (int(pid), run_id))+ conn.execute("UPDATE task_runs SET worker_pid = ?, worker_started_at = ? WHERE id = ?",+ (int(pid), started_at, run_id))_kb._append_event(conn, task_id, "spawned", {"pid": int(pid), "started_at": started_at}, run_id=run_id)@@ -1753,6 +1798,7 @@ def _run_reclaim_phase() -> None:"""Reclaim stale/orphaned/crashed/timed-out running tasks, then promote."""reap_worker_zombies()+ result.reaped_terminal_workers = reap_terminal_workers(conn)result.reclaimed = _kb.release_stale_claims(conn, failure_limit=failure_limit)if reconcile_orphans:result.reconciled_orphans = reconcile_orphaned_running(conn)diff --git a/hermes_cli/kanban_ops.py b/hermes_cli/kanban_ops.pyindex 6805471a653..8a976269ce4 100644--- a/hermes_cli/kanban_ops.py+++ b/hermes_cli/kanban_ops.py@@ -94,7 +94,8 @@ def _cmd_dispatch(args: argparse.Namespace) -> int:if getattr(args, "json", False):_print_json({**{k: getattr(res, k)- for k in ("reclaimed", "crashed", "timed_out", "stale", "auto_blocked", "promoted")},+ for k in ("reclaimed", "crashed", "timed_out", "stale", "auto_blocked", "promoted",+ "reaped_terminal_workers")},"spawned": [{"task_id": tid, "assignee": who, "workspace": ws} for (tid, who, ws) in res.spawned],@@ -115,6 +116,8 @@ def _cmd_dispatch(args: argparse.Namespace) -> int:}, ascii=True)return 0print(f"Reclaimed: {res.reclaimed}")+ if res.reaped_terminal_workers:+ print(f"Reaped workers of finished tasks: {', '.join(res.reaped_terminal_workers)}")for label, items in (("Crashed: ", res.crashed),("Timed out: ", res.timed_out),diff --git a/tests/hermes_cli/test_kanban_terminal_worker_reaper.py b/tests/hermes_cli/test_kanban_terminal_worker_reaper.pynew file mode 100644index 00000000000..81477e743dc--- /dev/null+++ b/tests/hermes_cli/test_kanban_terminal_worker_reaper.py@@ -0,0 +1,98 @@+"""Invariant: a worker that outlives its own terminal transition is still+reachable and gets reaped by the dispatcher (issue #111791).++``complete_task`` wipes ``tasks.worker_pid`` and the ``running``-only reclaim+sweeps never look at a ``done`` card again, so a worker that called+``kanban_complete`` and then hung (holding deleted ``state.db`` sidecar fds)+was invisible to every command. The closed ``task_runs`` row now keeps the pid+and its spawn fingerprint, and ``reap_terminal_workers`` ends such a worker on+the next tick — never a recycled PID, never a legacy row without a fingerprint.+"""++from __future__ import annotations++import subprocess+import sys+import time+from pathlib import Path++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+++def conn(tmp_path, monkeypatch):+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ db_path = kb.kanban_db_path(board="default")+ kb._INITIALIZED_PATHS.discard(str(db_path.resolve()))+ kb.init_db()+ with kbc.connect() as c:+ yield c+++def _sleeper():+ proc = subprocess.Popen(+ [sys.executable, "-c", "import time; time.sleep(120)"],+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,+ )+ time.sleep(0.2)+ return proc+++def _completed_card_with_worker(conn, proc) -> tuple[str, int]:+ tid = kb.create_task(conn, title="finished", assignee="coder")+ kb.claim_task(conn, tid, claimer=kb._claimer_id())+ run_id = kb._current_run_id(conn, tid)+ kbd._set_worker_pid(conn, tid, proc.pid)+ assert kb.complete_task(conn, tid, result="done", expected_run_id=run_id) is True+ return tid, run_id+++def test_worker_alive_after_completion_is_reaped_on_dispatch_tick(conn):+ proc = _sleeper()+ try:+ tid, run_id = _completed_card_with_worker(conn, proc)+ # The evidence the running-only sweeps lost lives on the closed run row.+ run = conn.execute("SELECT worker_pid, worker_started_at, ended_at FROM task_runs WHERE id=?", (run_id,)).fetchone()+ assert run["ended_at"] is not None and run["worker_pid"] == proc.pid and run["worker_started_at"] is not None++ result = kbd.dispatch_once(conn, spawn_fn=lambda *a, **k: 0, dry_run=True, max_spawn=0)++ assert result.reaped_terminal_workers == [tid]+ assert proc.wait(timeout=10) is not None+ run = conn.execute("SELECT worker_pid, worker_started_at FROM task_runs WHERE id=?", (run_id,)).fetchone()+ assert run["worker_pid"] is None and run["worker_started_at"] is None+ kinds = [r["kind"] for r in conn.execute("SELECT kind FROM task_events WHERE task_id=?", (tid,))]+ assert "terminal_worker_reaped" in kinds+ finally:+ if proc.poll() is None:+ proc.kill()+ proc.wait()+++def test_recycled_pid_and_legacy_row_are_never_signalled(conn):+ stranger = _sleeper()+ legacy = _sleeper()+ try:+ tid, run_id = _completed_card_with_worker(conn, stranger)+ # PID reuse: the recorded fingerprint belongs to a process that no longer exists.+ conn.execute("UPDATE task_runs SET worker_started_at = worker_started_at - 1000000 WHERE id=?", (run_id,))+ _, legacy_run = _completed_card_with_worker(conn, legacy)+ conn.execute("UPDATE task_runs SET worker_started_at = NULL WHERE id=?", (legacy_run,))++ assert kbd.reap_terminal_workers(conn) == []++ assert stranger.poll() is None and legacy.poll() is None+ # Stale evidence is dropped so the row is not rescanned; the legacy row is left alone.+ assert conn.execute("SELECT worker_pid FROM task_runs WHERE id=?", (run_id,)).fetchone()["worker_pid"] is None+ assert conn.execute("SELECT worker_pid FROM task_runs WHERE id=?", (legacy_run,)).fetchone()["worker_pid"] == legacy.pid+ finally:+ for p in (stranger, legacy):+ p.kill()+ p.wait()diff --git a/website/docs/user-guide/features/kanban.md b/website/docs/user-guide/features/kanban.mdindex 52d49542b97..ae3e330284b 100644--- a/website/docs/user-guide/features/kanban.md+++ b/website/docs/user-guide/features/kanban.md@@ -123,7 +123,7 @@ They coexist: a kanban worker may call `delegate_task` internally during its run- `scratch` (default) — fresh tmp dir under `~/.hermes/kanban/workspaces/<id>/` (or `~/.hermes/kanban/boards/<slug>/workspaces/<id>/` on non-default boards). **Deleted when the task completes** — scratch is ephemeral by design. Files explicitly declared through `kanban_complete(artifacts=[...])` or `kanban_request_review(artifacts=[...])` are copied into durable per-task attachment storage before cleanup (a review handoff stages them at handoff time, since the reviewer's later completion is what deletes the scratch workspace); existing deliverable paths in legacy completion summaries receive the same treatment. Other scratch files are removed. A missing declared scratch artifact keeps the task in-flight so the worker can correct the path and retry. Use `worktree:` or `dir:<path>` when the whole workspace should remain available. The first time a scratch workspace is created on an install, the dispatcher logs a warning and emits a `tip_scratch_workspace` event on the task (visible via `hermes kanban show <id>`).- `dir:<path>` — an existing shared directory (Obsidian vault, mail ops dir, per-account folder). **Must be an absolute path.** Relative paths like `dir:../tenants/foo/` are rejected at dispatch because they'd resolve against whatever CWD the dispatcher happens to be in, which is ambiguous and a confused-deputy escape vector. The path is otherwise trusted — it's your box, your filesystem, the worker runs with your uid. This is the trusted-local-user threat model; kanban is single-host by design. **Preserved on completion.**- `worktree` — a git worktree under `.worktrees/<id>/` for coding tasks. Use `worktree:<path>` to pin the exact target path. Worker-side `git worktree add` creates it, using `--branch` when provided. **Preserved on completion.**-- **Dispatcher** — a long-lived loop that, every N seconds (default 60): reclaims stale claims, reclaims crashed workers (PID gone but TTL not yet expired), promotes ready tasks, atomically claims, spawns assigned profiles. Runs **inside the gateway** by default (`kanban.dispatch_in_gateway: true`). One dispatcher sweeps all boards per tick; workers are spawned with `HERMES_KANBAN_BOARD` pinned so they can't see other boards. After `kanban.failure_limit` consecutive spawn failures on the same task (default: 2) the dispatcher auto-blocks it with the last error as the reason — prevents thrashing on tasks whose profile doesn't exist, workspace can't mount, etc.+- **Dispatcher** — a long-lived loop that, every N seconds (default 60): reclaims stale claims, reclaims crashed workers (PID gone but TTL not yet expired), reaps workers that outlived their finished run (a worker still alive after its own `kanban_complete`/`kanban_block` is terminated on the next tick — matched by PID *and* spawn-time fingerprint, so a recycled PID is never signalled; recorded as a `terminal_worker_reaped` event), promotes ready tasks, atomically claims, spawns assigned profiles. Runs **inside the gateway** by default (`kanban.dispatch_in_gateway: true`). One dispatcher sweeps all boards per tick; workers are spawned with `HERMES_KANBAN_BOARD` pinned so they can't see other boards. After `kanban.failure_limit` consecutive spawn failures on the same task (default: 2) the dispatcher auto-blocks it with the last error as the reason — prevents thrashing on tasks whose profile doesn't exist, workspace can't mount, etc.- **Tenant** — optional string namespace *within* a board. One specialist fleet can serve multiple businesses (`--tenant business-a`) with data isolation by workspace path and memory key prefix. Tenants are a soft filter; boards are the hard isolation boundary.## Boards (multi-project)