The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(kanban): honour a managed run's exit from its bound interpreter pid
Teknium41b48ef34d7f
diff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.pyindex b854e5d1693..406e41a8476 100644--- a/hermes_cli/kanban_db_dispatch.py+++ b/hermes_cli/kanban_db_dispatch.py@@ -1167,7 +1167,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 bound_interpreter_gone, owner_reclaim_paused+ from hermes_cli.kanban_owner_recovery import bound_interpreter_gone, managed_run_exit_code, owner_reclaim_pausedfor row in rows:lock = row["claim_lock"] or ""if not lock.startswith(host_prefix):@@ -1185,14 +1185,8 @@ def _reclaim_dead_workers(conn: sqlite3.Connection, board: Optional[str] = None)continuepid = int(row["worker_pid"])- # Managed interpreters are children of the authority, not this dispatcher.- # Their exact-run result survives a dispatcher restart and cannot be reaped here.- run = 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='worker_result' ORDER BY e.id DESC LIMIT 1",- (row["id"],)).fetchone()- result = _kb._json_dict(run["payload"]) if run else {}- exit_code = result.get("exit_code") if result.get("claim_lock") == row["claim_lock"] and result.get("pid") == pid else 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)retry_status = _kb._retry_status_for_run(conn, row["id"])dead.event_payload["retry_status"] = retry_statusdiff --git a/hermes_cli/kanban_owner_recovery.py b/hermes_cli/kanban_owner_recovery.pyindex 01f34519d14..ce379829037 100644--- a/hermes_cli/kanban_owner_recovery.py+++ b/hermes_cli/kanban_owner_recovery.py@@ -43,3 +43,27 @@ def bound_interpreter_gone(conn, task_id):return Falsebound = json.loads(row['payload'])return not _worker_alive(bound.get('pid'), bound.get('started_at'))+++def managed_run_exit_code(conn, task_id, worker_pid, claim_lock):+ """The exit code a managed run's authority recorded for the task's CURRENT run, else None.++ Managed interpreters are children of the authority, not the dispatcher, so their result is+ read from the run's ``worker_result`` event (it survives a dispatcher restart and cannot be+ reaped here). It speaks for the run only under the same claim and from a pid of this run:+ the dispatcher's own worker, or the owner-side interpreter ``worker_bound`` recorded under+ that claim — ``session_kanban._record_worker_result`` writes the interpreter's pid, never the+ spawned submitter's ``tasks.worker_pid``."""+ def latest(kind):+ row = 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=? ORDER BY e.id DESC LIMIT 1", (task_id, kind)).fetchone()+ try:+ payload = json.loads(row['payload']) if row else {}+ except ValueError:+ return {}+ return payload if isinstance(payload, dict) else {}++ result, bound = latest('worker_result'), latest('worker_bound')+ pids = {worker_pid, *([bound.get('pid')] if bound.get('claim_lock') == claim_lock else [])}+ return result.get('exit_code') if result.get('claim_lock') == claim_lock and result.get('pid') in pids else Nonediff --git a/tests/hermes_cli/test_kanban_managed_result_pid.py b/tests/hermes_cli/test_kanban_managed_result_pid.pynew file mode 100644index 00000000000..cfaa18dc026--- /dev/null+++ b/tests/hermes_cli/test_kanban_managed_result_pid.py@@ -0,0 +1,62 @@+"""A managed Kanban run's lost-ACK recovery honours the exit its authority recorded.++``tasks.worker_pid`` is the dispatcher's spawned submitter, but the managed interpreter that ran+the turns lives under the profile authority and writes ``worker_result`` with ITS pid (the one+``worker_bound`` recorded). The dead-worker sweep must accept that result under the same claim,+so a quota wall (exit 75) requeues as rate-limited instead of booking a crash.+"""++from __future__ import annotations++import subprocess+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: Path, monkeypatch: pytest.MonkeyPatch):+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setenv("HERMES_KANBAN_HOME", str(home))+ monkeypatch.setenv("HERMES_KANBAN_CRASH_GRACE_SECONDS", "0")+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ kbd._recent_worker_exits.clear()+ kb.init_db()+ with kbc.connect() as c:+ yield c+++def _dead_pid() -> int:+ proc = subprocess.Popen(["true"])+ proc.wait()+ return proc.pid++[email protected]("bound_claim, expected", [("own", "rate_limited"), ("foreign", "crashed")])+def test_managed_exit_75_requeues_rate_limited_not_crashed(conn, bound_claim, expected):+ host = kb._claimer_id().split(":", 1)[0]+ tid = kb.create_task(conn, title="managed", assignee="w")+ task = kb.claim_task(conn, tid, claimer=f"{host}:owner")+ assert task is not None+ submitter, interpreter = _dead_pid(), _dead_pid()+ assert submitter != interpreter+ kbd._set_worker_pid(conn, tid, submitter)+ claim = task.claim_lock if bound_claim == "own" else "someone-else"+ with kb.write_txn(conn):+ kb._append_event(conn, tid, "worker_bound", {"pid": interpreter, "claim_lock": claim, "started_at": "x"},+ run_id=task.current_run_id)+ kb._append_event(conn, tid, "worker_result", {"pid": interpreter, "claim_lock": task.claim_lock,+ "exit_code": kb.KANBAN_RATE_LIMIT_EXIT_CODE, "last_output": ""}, run_id=task.current_run_id)++ crashed = kbd.detect_crashed_workers(conn)++ outcome = conn.execute("SELECT outcome FROM task_runs WHERE id=?", (task.current_run_id,)).fetchone()[0]+ assert outcome == expected+ assert (tid in kbd.detect_crashed_workers._last_rate_limited) is (expected == "rate_limited")+ assert (tid in crashed) is (expected == "crashed")