The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(kanban): automatic stale-claim reclaims count toward the failure breaker
teknium1738d63a34d1c
diff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.pyindex 71653c03bac..a9d8fe72445 100644--- a/hermes_cli/kanban_db.py+++ b/hermes_cli/kanban_db.py@@ -2297,9 +2297,17 @@ def _extend_run_claim(conn: sqlite3.Connection, task_id: str, expires: int) -> Oreturn run_id-def release_stale_claims(conn: sqlite3.Connection, *, signal_fn=None) -> int:+def release_stale_claims(+ conn: sqlite3.Connection, *, signal_fn=None, failure_limit: Optional[int] = None,+) -> int:"""Reclaim ``running`` tasks whose claim expired; returns the count reclaimed.+ Every reclaim that actually releases a claim is a non-success attempt and+ is booked through ``_record_task_failure`` (#111306): a claim that expired+ without a worker ever spawning otherwise loops claim -> reclaim -> claim+ with ``consecutive_failures`` stuck at 0, so the breaker never trips.+ ``reclaim_task`` (operator path) deliberately resets the counter instead.+A host-local worker that is still alive gets its claim *extended* instead(a slow model can sit longer than the TTL inside one tool-free call, so noheartbeat) — unless ``last_heartbeat_at`` is older than@@ -2353,14 +2361,8 @@ def release_stale_claims(conn: sqlite3.Connection, *, signal_fn=None) -> int:with write_txn(conn):retry_status = _retry_status_for_run(conn, row["id"])cur = conn.execute(- # The reclaim had no live worker to keep the claim for, so the- # run failed without a verdict — count it against the- # failure_threshold breaker (consecutive_failures), else a- # claim-without-spawn spins forever with the counter at 0- # (#111306)."UPDATE tasks SET status = ?, claim_lock = NULL, "- "claim_expires = NULL, worker_pid = NULL, "- "consecutive_failures = consecutive_failures + 1 "+ "claim_expires = NULL, worker_pid = NULL ""WHERE id = ? AND status = 'running' AND claim_lock IS ? ""AND claim_expires IS NOT NULL AND claim_expires < ?",(retry_status, row["id"], row["claim_lock"], now),@@ -2382,6 +2384,15 @@ def release_stale_claims(conn: sqlite3.Connection, *, signal_fn=None) -> int:},)reclaimed += 1+ # Own txn, after the reclaim commit (same shape as ``enforce_max_runtime``):+ # 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']}",+ 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},+ )# Post-commit observer; every non-reclaim branch ``continue``d above.if _kanban_observer_consumed("on_kanban_worker_stale_claim"):_fire_kanban_lifecycle_hook(@@ -4148,6 +4159,7 @@ from hermes_cli.kanban_db_dispatch import ( # noqa: E402_clear_failure_counter,_defer_reclaim_for_live_worker,_pid_alive,+ _record_task_failure,_terminate_reclaimed_worker,_worker_alive,_worker_survived_termination,diff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.pyindex ed37025ac2b..0a8327b2ae5 100644--- a/hermes_cli/kanban_db_dispatch.py+++ b/hermes_cli/kanban_db_dispatch.py@@ -1723,7 +1723,7 @@ def _run_reclaim_phase() -> None:"""Reclaim stale/orphaned/crashed/timed-out running tasks, then promote."""reap_worker_zombies()- result.reclaimed = _kb.release_stale_claims(conn)+ result.reclaimed = _kb.release_stale_claims(conn, failure_limit=failure_limit)if reconcile_orphans:result.reconciled_orphans = reconcile_orphaned_running(conn)result.stale = detect_stale_running(conn, stale_timeout_seconds=stale_timeout_seconds)diff --git a/tests/hermes_cli/test_kanban_db.py b/tests/hermes_cli/test_kanban_db.pyindex ccf8f74ed4a..046bdaec589 100644--- a/tests/hermes_cli/test_kanban_db.py+++ b/tests/hermes_cli/test_kanban_db.py@@ -248,56 +248,31 @@ def test_stale_claim_reclaim_event_records_diagnostic_payload(assert payload["host_local"] is True-def test_stale_claim_reclaim_without_spawn_counts_failure(kanban_home):- """Automatic reclaim of a claim that was never spawned (``worker_pid``- NULL) must increment ``consecutive_failures`` (#111306): otherwise a- claim-without-spawn reclaims forever, ``consecutive_failures`` stays 0,- and the failure_threshold breaker can never trip."""+def test_stale_claim_reclaim_without_spawn_counts_toward_breaker(kanban_home):+ """A claim that expires without a worker ever spawning is a non-success+ attempt (#111306): each automatic reclaim advances ``consecutive_failures``+ and the breaker trips at ``failure_limit`` instead of the card spinning+ claim -> reclaim -> claim forever."""with kbc.connect() as conn:t = kb.create_task(conn, title="never spawned", assignee="a")host = kb._claimer_id().split(":", 1)[0]- kb.claim_task(conn, t, claimer=f"{host}:worker")- # No _set_worker_pid: the claimer never spawned a worker.- old_expires = int(time.time()) - 3600- conn.execute(- "UPDATE tasks SET claim_expires = ? WHERE id = ?",- (old_expires, t),- )- assert kb.release_stale_claims(conn, signal_fn=lambda _p, _s: None) == 1- row = conn.execute(- "SELECT status, consecutive_failures FROM tasks WHERE id = ?",- (t,),- ).fetchone()- assert row["status"] == "ready"- assert row["consecutive_failures"] == 1---def test_stale_claim_reclaim_dead_worker_counts_failure(- kanban_home, monkeypatch,-):- """Automatic reclaim of a claim whose worker already died must increment- ``consecutive_failures`` (#111306): the reclaim had no live worker to- terminate, so it counts against the failure_threshold breaker."""- import hermes_cli.kanban_db as _kb-- with kbc.connect() as conn:- t = kb.create_task(conn, title="dead worker", assignee="a")- host = _kb._claimer_id().split(":", 1)[0]- kb.claim_task(conn, t, claimer=f"{host}:worker")- kbd._set_worker_pid(conn, t, 12345)- old_expires = int(time.time()) - 3600- conn.execute(- "UPDATE tasks SET claim_expires = ? WHERE id = ?",- (old_expires, t),- )- monkeypatch.setattr(_kb, "_pid_alive", lambda _pid: False)- assert kb.release_stale_claims(conn, signal_fn=lambda _p, _s: None) == 1- row = conn.execute(- "SELECT status, consecutive_failures FROM tasks WHERE id = ?",- (t,),- ).fetchone()- assert row["status"] == "ready"- assert row["consecutive_failures"] == 1+ for expected in (1, 2):+ kb.claim_task(conn, t, claimer=f"{host}:worker")+ # No _set_worker_pid: the claimer never spawned a worker.+ conn.execute(+ "UPDATE tasks SET claim_expires = ? WHERE id = ?",+ (int(time.time()) - 3600, t),+ )+ assert kb.release_stale_claims(+ conn, signal_fn=lambda _p, _s: None, failure_limit=2,+ ) == 1+ row = conn.execute(+ "SELECT status, consecutive_failures FROM tasks WHERE id = ?", (t,),+ ).fetchone()+ assert row["consecutive_failures"] == expected+ assert row["status"] == "blocked"+ kinds = [e.kind for e in kb.list_events(conn, t)]+ assert kinds[-2:] == ["reclaimed", "gave_up"]def test_stale_claim_extend_live_worker_does_not_count_failure(diff --git a/website/docs/user-guide/features/kanban.md b/website/docs/user-guide/features/kanban.mdindex 94c41523121..4ca4475a153 100644--- a/website/docs/user-guide/features/kanban.md+++ b/website/docs/user-guide/features/kanban.md@@ -1293,7 +1293,7 @@ Every transition appends a row to `task_events`. Each row carries an optional `r|---|---|---|| `spawned` | `{pid}` | Dispatcher successfully started a worker process. || `heartbeat` | `{note?}` | Worker called `hermes kanban heartbeat $TASK` to signal liveness during long operations. |-| `reclaimed` | `{stale_lock}` | Claim TTL expired without a completion; task goes back to `ready`. |+| `reclaimed` | `{stale_lock}` | Claim TTL expired without a completion; task goes back to `ready`. An automatic reclaim counts as one non-successful attempt toward the `gave_up` breaker (a claim that never spawned a worker would otherwise loop claim → reclaim → claim forever); an operator `reclaim` resets the counter instead. || `crashed` | `{pid, claimer}` | Worker PID no longer alive but TTL hadn't expired yet. || `timed_out` | `{pid, elapsed_seconds, limit_seconds, sigkill}` | `max_runtime_seconds` exceeded; dispatcher SIGTERM'd (then SIGKILL'd after 5 s grace) and re-queued. || `stale` | `{elapsed_seconds, last_heartbeat_at, heartbeat_age_seconds, timeout_seconds, pid, terminated}` | Task ran longer than `kanban.dispatch_stale_timeout_seconds` (default 4 h) AND no `kanban_heartbeat` arrived in the last hour. Dispatcher SIGTERM'd the host-local worker (if any), reset the task to `ready` for re-dispatch. Does NOT tick the failure counter (stale is dispatcher-side absence detection, not a worker fault). Workers running long operations should call `kanban_heartbeat` at least once an hour to avoid this. |