Skip to content

The agent that grows with you

fix: retry a failed kanban turn in place on the owner-side worker path

Tekniumcd8425c8763d
diff --git a/agent/kanban_turn_recovery.py b/agent/kanban_turn_recovery.py
index e54df564462..261268c6fbc 100644
--- a/agent/kanban_turn_recovery.py
+++ b/agent/kanban_turn_recovery.py
@@ -92,9 +92,16 @@ def kanban_task_id() -> Optional[str]:
return task_id or None
-def kanban_turn_recovery_enabled() -> bool:
- """On when ``HERMES_KANBAN_TASK`` is set and the attempt budget is non-zero."""
- if kanban_task_id() is None:
+def _resolve_task_id(task_id: Optional[str]) -> Optional[str]:
+ """An explicit carrier id (managed worker frame) wins; ``None`` reads the env pin."""
+ if task_id is None:
+ return kanban_task_id()
+ return task_id.strip() or None
+
+
+def kanban_turn_recovery_enabled(task_id: Optional[str] = None) -> bool:
+ """On when a worker task id is carried and the attempt budget is non-zero."""
+ if _resolve_task_id(task_id) is None:
return False
return max_recovery_attempts() > 0
@@ -131,7 +138,7 @@ def _turn_exit_is_terminal(result: dict) -> bool:
return reason.startswith(_TERMINAL_TURN_EXIT_PREFIXES)
-def should_recover_turn(result: Any, *, attempt: int) -> bool:
+def should_recover_turn(result: Any, *, attempt: int, task_id: Optional[str] = None) -> bool:
"""True when a settled worker turn grants in-place retry authority.
``attempt`` is the number of recovery attempts ALREADY made. Authority is
@@ -141,7 +148,7 @@ def should_recover_turn(result: Any, *, attempt: int) -> bool:
including ``partial`` / ``completed=False`` — is not authority to re-enter
the model. See the module docstring for the full rule set.
"""
- if not kanban_turn_recovery_enabled():
+ if not kanban_turn_recovery_enabled(task_id):
return False
if attempt >= max_recovery_attempts():
return False
@@ -180,7 +187,14 @@ def _now() -> int:
return int(time.time())
-def worker_claim_is_live() -> bool:
+def worker_claim_is_live(
+ *,
+ task_id: Optional[str] = None,
+ db_path: Optional[str] = None,
+ run_id: Optional[str] = None,
+ claim_lock: Optional[str] = None,
+ verify_pid: bool = True,
+) -> bool:
"""True when THIS process still owns a live, unexpired run/claim lease.
Verified read-only against the dispatcher-pinned board before EVERY retry.
@@ -203,16 +217,22 @@ def worker_claim_is_live() -> bool:
run/lock/pid, closed run, or expired lease returns False and the caller
does not re-enter the model — an honest non-zero exit is always available,
whereas mutating state under a released or expired claim is not recoverable.
+
+ An owner-side (managed) worker passes its carrier explicitly from the bound
+ worker frame instead of the env pins, and ``verify_pid=False`` because there
+ the run's ``worker_pid`` names the dispatcher-spawned submitter, not this
+ interpreter — that caller proves interpreter identity from its own
+ ``worker_bound`` event.
"""
- task_id = kanban_task_id()
+ task_id = _resolve_task_id(task_id)
if task_id is None:
return False
- db_path = _kanban_db_path()
+ db_path = _kanban_db_path() if db_path is None else (db_path.strip() or None)
if not db_path or not Path(db_path).exists():
logger.warning("kanban claim check: pinned board db %r not found — not retrying in place", db_path)
return False
- run_id_env = (os.environ.get("HERMES_KANBAN_RUN_ID") or "").strip()
- lock_env = (os.environ.get("HERMES_KANBAN_CLAIM_LOCK") or "").strip()
+ run_id_env = str(run_id if run_id is not None else os.environ.get("HERMES_KANBAN_RUN_ID") or "").strip()
+ lock_env = str(claim_lock if claim_lock is not None else os.environ.get("HERMES_KANBAN_CLAIM_LOCK") or "").strip()
if not run_id_env or not lock_env:
logger.warning(
"kanban claim check: missing dispatcher-pinned run-id/claim-lock carrier "
@@ -234,7 +254,7 @@ def worker_claim_is_live() -> bool:
if (row["status"] or "") != "running":
return False
worker_pid = row["worker_pid"]
- if worker_pid is not None and int(worker_pid) != os.getpid():
+ if verify_pid and worker_pid is not None and int(worker_pid) != os.getpid():
return False
# A running task with no run pointer is not proof of a live run: the
# dispatcher writes it on claim and clears it on release/end.
@@ -256,7 +276,7 @@ def worker_claim_is_live() -> bool:
if run["ended_at"] is not None:
return False
run_pid = run["worker_pid"]
- if run_pid is not None and int(run_pid) != os.getpid():
+ if verify_pid and run_pid is not None and int(run_pid) != os.getpid():
return False
if run["claim_expires"] is None or int(run["claim_expires"]) < now:
return False
@@ -273,7 +293,8 @@ def _truncate(text: str, limit: int = 300) -> str:
return text[: limit - 1] + "…" if len(text) > limit else text
-def build_recovery_nudge(result: Any, *, attempt: int, max_attempts: int) -> str:
+def build_recovery_nudge(result: Any, *, attempt: int, max_attempts: int,
+ task_id: Optional[str] = None) -> str:
"""The synthetic user turn sent after a failed worker turn.
Mirrors the stop-nudge contract (agent/kanban_stop.py): plain text is not a
@@ -284,7 +305,7 @@ def build_recovery_nudge(result: Any, *, attempt: int, max_attempts: int) -> str
error = ""
if isinstance(result, dict):
error = _truncate(str(result.get("error") or result.get("final_response") or ""))
- task_id = kanban_task_id() or "this task"
+ task_id = _resolve_task_id(task_id) or "this task"
return (
"[System: the previous turn ended UNFINISHED — the API call failed after "
f"all retries and the turn was interrupted (recovery attempt {attempt}/{max_attempts}). "
@@ -300,10 +321,10 @@ def build_recovery_nudge(result: Any, *, attempt: int, max_attempts: int) -> str
)
-def _emit_recovery_skipped(emit: Optional[Callable[[str], None]]) -> None:
+def _emit_recovery_skipped(emit: Optional[Callable[[str], None]], task_id: Optional[str] = None) -> None:
"""The one "no proof, no retry" line — fail-closed is worth saying out loud."""
message = (
- f"[kanban] in-place recovery skipped for {kanban_task_id() or 'task'}: this worker no "
+ f"[kanban] in-place recovery skipped for {_resolve_task_id(task_id) or 'task'}: this worker no "
"longer holds a live run/claim (already settled, reclaimed, or unverifiable)"
)
logger.warning("%s", message)
@@ -321,6 +342,7 @@ def recover_failed_kanban_turns(
sleep_fn: Callable[[float], None] = time.sleep,
emit: Optional[Callable[[str], None]] = None,
claim_check: Optional[Callable[[], bool]] = None,
+ task_id: Optional[str] = None,
) -> int:
"""Retry an authorised kanban worker turn in place; returns attempts made.
@@ -332,21 +354,23 @@ def recover_failed_kanban_turns(
deliberately does NOT extend its own claim lease during the backoff —
self-holding a claim is claim-lifetime policy (#95318), not this module's;
if the lease expires while sleeping, the re-proof fails and the attempt is
- not made.
+ not made. ``task_id`` carries the worker identity explicitly (owner-side
+ workers pass their bound frame's task); such callers must also pass a
+ ``claim_check`` built from the same explicit carrier.
"""
attempts = 0
check = claim_check or worker_claim_is_live
while True:
result = get_result()
- if not should_recover_turn(result, attempt=attempts):
+ if not should_recover_turn(result, attempt=attempts, task_id=task_id):
return attempts
if not check():
- _emit_recovery_skipped(emit)
+ _emit_recovery_skipped(emit, task_id)
return attempts
attempts += 1
delay = recovery_delay_seconds(attempts)
message = (
- f"[kanban] provider failure on {kanban_task_id() or 'task'} — retrying the turn in place "
+ f"[kanban] provider failure on {_resolve_task_id(task_id) or 'task'} — retrying the turn in place "
f"(attempt {attempts}/{max_recovery_attempts()}) after {int(delay)}s; session context preserved"
)
logger.warning("%s", message)
@@ -361,9 +385,10 @@ def recover_failed_kanban_turns(
# alone would let that one attempt run without live ownership (round-5 finding F1 —
# TOCTOU window). No proof, no retry; the caller's honest exit still applies.
if not check():
- _emit_recovery_skipped(emit)
+ _emit_recovery_skipped(emit, task_id)
return attempts
- turn_fn(build_recovery_nudge(result, attempt=attempts, max_attempts=max_recovery_attempts()))
+ turn_fn(build_recovery_nudge(result, attempt=attempts, max_attempts=max_recovery_attempts(),
+ task_id=task_id))
__all__ = [
diff --git a/gateway/session_kanban.py b/gateway/session_kanban.py
index dfd9f29cbf2..28200aa09e4 100644
--- a/gateway/session_kanban.py
+++ b/gateway/session_kanban.py
@@ -217,10 +217,7 @@ def run_worker_turns(agent, frame, history):
from hermes_cli.kanban_db_connect import connect_closing
from hermes_cli import kanban_db as kb
with connect_closing(Path(context['db'])) as conn, kb.write_txn(conn):
- row = conn.execute("SELECT payload FROM task_events WHERE task_id=? AND run_id=? AND kind='worker_bound' ORDER BY id DESC LIMIT 1",
- (context['task_id'], context['run_id'])).fetchone()
- bound = json.loads(row[0]) if row else {}
- if (bound.get('pid'), bound.get('claim_lock')) == (os.getpid(), context['claim_lock']):
+ if _bound_worker_matches(conn, context):
# Closing a run clears its claim/PID and replaces metadata; keep the
# result in the immutable attempt event stream instead.
kb._append_event(conn, context['task_id'], 'worker_result',
@@ -228,6 +225,29 @@ def run_worker_turns(agent, frame, history):
'last_output': last_output}, run_id=context['run_id'])
+def _bound_worker_matches(conn, context):
+ import os
+ row = conn.execute("SELECT payload FROM task_events WHERE task_id=? AND run_id=? AND kind='worker_bound' ORDER BY id DESC LIMIT 1",
+ (context['task_id'], context['run_id'])).fetchone()
+ bound = json.loads(row[0]) if row else {}
+ return (bound.get('pid'), bound.get('claim_lock')) == (os.getpid(), context['claim_lock'])
+
+
+def _bound_claim_is_live(context):
+ """Retry proof for a managed worker: the frame's exact run/claim lease is live and unexpired,
+ and THIS interpreter is the one ``bind_worker_context`` bound to it. The run's worker_pid is
+ the dispatcher's spawned submitter here, so pid identity comes from ``worker_bound`` instead."""
+ from agent.kanban_turn_recovery import worker_claim_is_live
+ if not worker_claim_is_live(task_id=context['task_id'], db_path=context['db'], run_id=str(context['run_id']),
+ claim_lock=context['claim_lock'], verify_pid=False):
+ return False
+ try:
+ with closing(sqlite3.connect(Path(context['db']).resolve().as_uri() + '?mode=ro', uri=True)) as conn:
+ return _bound_worker_matches(conn, context)
+ except sqlite3.Error:
+ return False
+
+
def worker_result(path, params):
"""Read only the dispatcher's exact attempt; never infer success from admission settlement."""
with closing(sqlite3.connect(Path(path).resolve().as_uri() + '?mode=ro', uri=True)) as conn:
@@ -248,7 +268,21 @@ def _run_task_turns(agent, frame, history, context):
raise ValueError('kanban_skills_unavailable')
prompt = '\n\n'.join(p for p in (skills, context['context'], frame['text']) if p)
result = agent.run_conversation(prompt, conversation_history=history)
- if not context['goal_mode']:
+
+ def recover(nudge):
+ nonlocal result
+ prior = result.get('messages') if isinstance(result, dict) else None
+ result = agent.run_conversation(nudge, conversation_history=prior or
+ agent._session_db.get_messages_as_conversation(agent.session_id))
+ # Same in-place retry as the one-shot CLI worker (agent/kanban_turn_recovery.py), but the
+ # carrier is this frame's bound claim, never the owner process's environment.
+ from agent.kanban_turn_recovery import recover_failed_kanban_turns
+ recover_failed_kanban_turns(recover, lambda: result, task_id=context['task_id'],
+ claim_check=lambda: _bound_claim_is_live(context))
+ from hermes_cli.turn_exit import turn_exit_code
+ # Only a settled turn may continue the goal loop: an exhausted or denied recovery reaches
+ # the honest exit path without re-entering the model under an unprovable claim.
+ if not context['goal_mode'] or turn_exit_code(result, kanban_worker=True) != 0:
return result
from hermes_cli.goals import run_kanban_goal_loop, DEFAULT_MAX_TURNS
from hermes_cli import kanban_db as kb
diff --git a/tests/gateway/test_session_kanban_turn_recovery.py b/tests/gateway/test_session_kanban_turn_recovery.py
new file mode 100644
index 00000000000..43a81de2f2b
--- /dev/null
+++ b/tests/gateway/test_session_kanban_turn_recovery.py
@@ -0,0 +1,77 @@
+"""Owner-side kanban workers retry a failed turn in place, proven from the bound frame's claim."""
+import json
+import os
+
+from agent import kanban_turn_recovery as rec
+from gateway import session_kanban
+from hermes_cli import kanban_db as kb
+from hermes_cli.kanban_db_connect import connect_closing
+
+FAILED = {"failed": True, "failure_retryable": True, "failure_reason": "timeout",
+ "error": "stream died", "messages": [{"role": "user", "content": "first"}]}
+
+
+class _Agent:
+ session_id = "s1"
+
+ def __init__(self, results):
+ self.results, self.calls = list(results), []
+ self._session_db = self
+
+ def get_messages_as_conversation(self, _sid):
+ return [{"role": "user", "content": "from-store"}]
+
+ def run_conversation(self, message, conversation_history=None):
+ self.calls.append((message, conversation_history))
+ return self.results.pop(0)
+
+
+def _claimed_frame(tmp_path, monkeypatch, *, expired=False, goal_mode=False):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.delenv("HERMES_KANBAN_TURN_RECOVERY", raising=False)
+ # The owner/gateway process carries a FOREIGN (stale) env carrier: the proof must ignore it.
+ for key, value in (("HERMES_KANBAN_TASK", "t_foreign"), ("HERMES_KANBAN_DB", str(tmp_path / "nope.db")),
+ ("HERMES_KANBAN_RUN_ID", "999"), ("HERMES_KANBAN_CLAIM_LOCK", "foreign")):
+ monkeypatch.setenv(key, value)
+ monkeypatch.setattr(rec, "RECOVERY_DELAYS_SECONDS", (0.0,))
+ monkeypatch.setattr("agent.skill_commands.build_preloaded_skills_prompt", lambda *a, **k: ("", [], []))
+ kb.init_db()
+ path = kb.kanban_db_path()
+ with connect_closing(path) as conn:
+ task_id = kb.create_task(conn, title="recover", assignee="default")
+ task = kb.claim_task(conn, task_id, claimer="private-host:owner")
+ assert task is not None
+ with kb.write_txn(conn):
+ kb._append_event(conn, task_id, "worker_bound", {"pid": os.getpid(), "claim_lock": task.claim_lock},
+ run_id=task.current_run_id)
+ if expired: # lease lapsed but not yet reaped: status/run/lock all still match
+ conn.execute("UPDATE tasks SET claim_expires = 1 WHERE id = ?", (task_id,))
+ conn.execute("UPDATE task_runs SET claim_expires = 1 WHERE id = ?", (task.current_run_id,))
+ context = {"db": str(path), "task_id": task_id, "run_id": task.current_run_id, "claim_lock": task.claim_lock,
+ "skills": [], "context": "", "goal_mode": goal_mode, "goal_text": "g", "goal_max_turns": 2}
+ return path, context, {"text": "work", "policy": {"kanban_json": json.dumps(context)}}
+
+
+def test_failed_turn_retries_in_place_from_frame_carrier(tmp_path, monkeypatch):
+ path, context, frame = _claimed_frame(tmp_path, monkeypatch)
+ agent = _Agent([dict(FAILED), {"completed": True, "final_response": "done"}])
+
+ result = session_kanban.run_worker_turns(agent, frame, [])
+
+ assert result["final_response"] == "done" and len(agent.calls) == 2
+ nudge, history = agent.calls[1]
+ assert context["task_id"] in nudge and "t_foreign" not in nudge
+ assert history == FAILED["messages"] # same session context, not a cold restart
+ assert session_kanban.worker_exit_code(path, context) == 0
+
+
+def test_unprovable_claim_denies_retry_and_goal_continuation(tmp_path, monkeypatch):
+ path, context, frame = _claimed_frame(tmp_path, monkeypatch, expired=True, goal_mode=True)
+ goal_calls = []
+ monkeypatch.setattr("hermes_cli.goals.run_kanban_goal_loop", lambda **kw: goal_calls.append(kw))
+ agent = _Agent([dict(FAILED)])
+
+ result = session_kanban.run_worker_turns(agent, frame, [])
+
+ assert result["failed"] and len(agent.calls) == 1 and goal_calls == []
+ assert session_kanban.worker_exit_code(path, context) == kb.KANBAN_RATE_LIMIT_EXIT_CODE