Skip to content

The agent that grows with you

fix(kanban): make archive-time worker termination race-safe and audited

Teknium053f8b1b1735
diff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.py
index 04e747c57e6..17e9c7b77c0 100644
--- a/hermes_cli/kanban_db.py
+++ b/hermes_cli/kanban_db.py
@@ -3494,20 +3494,29 @@ def specify_triage_task(
return True
-def archive_task(conn: sqlite3.Connection, task_id: str) -> bool:
- # Snapshot pid+claim before the DB update clears them, so we can
- # terminate the worker process even after those columns are NULLed.
- row = conn.execute(
- "SELECT worker_pid, claim_lock FROM tasks WHERE id = ?",
- (task_id,),
- ).fetchone()
- prev_pid = row["worker_pid"] if row else None
- prev_lock = row["claim_lock"] if row else None
- # Terminate the worker process first (same order as reclaim_task).
- # If the task wasn't running on this host, this is a safe no-op.
- termination = _terminate_reclaimed_worker(prev_pid, prev_lock)
-
+def archive_task(conn: sqlite3.Connection, task_id: str, *, signal_fn=None) -> bool:
+ """Archive a task; a *running* task's host-local worker is terminated.
+
+ Clearing ``worker_pid`` in the DB alone left the OS process running past its
+ own archive — it kept executing (and pushing work) against a task nothing
+ tracked anymore (#76196). Snapshot pid+claim inside the archive txn so the
+ kill is contingent on THIS caller winning the archive transition (a losing
+ concurrent archiver must never signal the pid); the kill itself runs after
+ commit — ``_poll_worker_exit`` can wait ~5 s and must not hold the write
+ lock. Post-release kill is safe here because ``archived`` is terminal: no
+ dispatcher can spawn a duplicate worker off the released claim. The
+ termination outcome lands as its own ``archive_worker_termination`` event so
+ the ``archived`` event stays atomic with the status flip.
+ """
with write_txn(conn):
+ row = conn.execute(
+ "SELECT status, claim_lock, worker_pid FROM tasks WHERE id = ?",
+ (task_id,),
+ ).fetchone()
+ if not row:
+ return False
+ was_running = row["status"] == "running"
+ prev_pid, prev_lock = row["worker_pid"], row["claim_lock"]
cur = conn.execute(
"UPDATE tasks SET status = 'archived', "
" claim_lock = NULL, claim_expires = NULL, worker_pid = NULL "
@@ -3520,9 +3529,11 @@ def archive_task(conn: sqlite3.Connection, task_id: str) -> bool:
conn, task_id, outcome="reclaimed", status="reclaimed",
summary="task archived with run still active",
)
- payload = {}
- payload.update(termination)
- _append_event(conn, task_id, "archived", payload, run_id=run_id)
+ _append_event(conn, task_id, "archived", None, run_id=run_id)
+ if was_running:
+ termination = _terminate_reclaimed_worker(prev_pid, prev_lock, signal_fn=signal_fn)
+ with write_txn(conn):
+ _append_event(conn, task_id, "archive_worker_termination", termination, run_id=run_id)
# ``archived`` parents no longer block children; promote them now.
recompute_ready(conn)
# Reap the workspace on archive too (never-completed tasks kept it forever).
diff --git a/tests/hermes_cli/test_kanban_db.py b/tests/hermes_cli/test_kanban_db.py
index 8a0b1976e8f..59f7619f8bb 100644
--- a/tests/hermes_cli/test_kanban_db.py
+++ b/tests/hermes_cli/test_kanban_db.py
@@ -1656,3 +1656,57 @@ def test_bare_connect_does_not_close_on_context_exit(tmp_path):
# Still usable after with-block exit (the leak).
conn.execute("SELECT 1").fetchone()
conn.close() # explicit close to avoid leaking THIS test
+
+
+def test_archive_running_task_terminates_worker(kanban_home, monkeypatch):
+ """``archive_task`` on a *running* task must actually signal its host-local
+ worker process, not just null ``worker_pid`` in the DB (#76196: a worker
+ kept running past its own archive and could still push/complete work
+ against a task nothing tracks anymore). The termination outcome is
+ auditable via the ``archive_worker_termination`` event."""
+ import json
+
+ with kbc.connect() as conn:
+ t = kb.create_task(conn, title="x", assignee="a")
+ host = kb._claimer_id().split(":", 1)[0]
+ kb.claim_task(conn, t, claimer=f"{host}:worker")
+ kbd._set_worker_pid(conn, t, 54321)
+
+ monkeypatch.setattr(kb, "_pid_alive", lambda _pid: False)
+ signalled = []
+ assert kb.archive_task(
+ conn, t, signal_fn=lambda pid, sig: signalled.append((pid, sig)),
+ ) is True
+
+ assert signalled and signalled[0][0] == 54321
+
+ row = conn.execute(
+ "SELECT payload FROM task_events "
+ "WHERE task_id = ? AND kind = 'archive_worker_termination'",
+ (t,),
+ ).fetchone()
+ payload = json.loads(row["payload"])
+ assert payload["prev_pid"] == 54321
+ assert payload["host_local"] is True
+ assert payload["termination_attempted"] is True
+ assert payload["terminated"] is True
+ assert kb.get_task(conn, t).status == "archived"
+
+
+def test_archive_non_running_task_does_not_attempt_termination(kanban_home):
+ """A never-claimed (``triage``/``ready``/``done``) task has no live worker:
+ ``archive_task`` must not signal anything, and no termination event is
+ recorded — only for tasks that were actually ``running`` at archive time."""
+ with kbc.connect() as conn:
+ t = kb.create_task(conn, title="x", assignee="a")
+ signalled = []
+ assert kb.archive_task(
+ conn, t, signal_fn=lambda pid, sig: signalled.append((pid, sig)),
+ ) is True
+ assert signalled == []
+ row = conn.execute(
+ "SELECT 1 FROM task_events "
+ "WHERE task_id = ? AND kind = 'archive_worker_termination'",
+ (t,),
+ ).fetchone()
+ assert row is None