Skip to content

The agent that grows with you

fix(agent): bound worker finalization when iteration budget exhausted (#87096)

webtecnicaf1e3e0a4d9b8
diff --git a/agent/turn_finalizer.py b/agent/turn_finalizer.py
index 402e1b6a5dd..1d27e62d70d 100644
--- a/agent/turn_finalizer.py
+++ b/agent/turn_finalizer.py
@@ -22,6 +22,7 @@ keep the exact logger name (``"agent.conversation_loop"``).
from __future__ import annotations
+import logging
import os
from agent.codex_responses_adapter import _summarize_user_message_for_log
@@ -55,6 +56,54 @@ _VERIFICATION_CONTINUATION_FLAGS = (
)
+def _record_kanban_budget_exhausted(
+ kanban_task: str,
+ api_call_count: int,
+ max_iterations: int,
+ logger: logging.Logger,
+) -> None:
+ """Record a terminal ``timed_out`` outcome for a kanban worker that
+ exhausted its iteration budget.
+
+ This is a bounded fallback (#87096): the CAS invariant in ``_end_run``
+ (``WHERE ended_at IS NULL``) guarantees idempotence — if another path
+ already closed the run this is a no-op — so it is safe to call from
+ multiple exit paths.
+ """
+ try:
+ from hermes_cli import kanban_db as _kb
+ _conn = _kb.connect()
+ try:
+ _kb._record_task_failure(
+ _conn,
+ kanban_task,
+ error=(
+ f"Iteration budget exhausted "
+ f"({api_call_count}/{max_iterations}) — "
+ "task could not complete within the allowed "
+ "iterations"
+ ),
+ outcome="timed_out",
+ release_claim=True,
+ end_run=True,
+ event_payload_extra={
+ "budget_used": api_call_count,
+ "budget_max": max_iterations,
+ },
+ )
+ finally:
+ try:
+ _conn.close()
+ except Exception:
+ pass
+ except Exception:
+ logger.warning(
+ "Failed to record budget-exhausted failure for task %s",
+ kanban_task,
+ exc_info=True,
+ )
+
+
def _drop_verification_continuation_scaffolding(messages) -> None:
"""Remove verification-continuation nudge messages from *messages* in place.
@@ -155,42 +204,23 @@ def finalize_turn(
# consecutive-failure circuit breaker (#29747 gap 2).
_kanban_task = os.environ.get("HERMES_KANBAN_TASK")
if _kanban_task:
- try:
- from hermes_cli import kanban_db as _kb
- _conn = _kb.connect()
- try:
- _kb._record_task_failure(
- _conn,
- _kanban_task,
- error=(
- f"Iteration budget exhausted "
- f"({api_call_count}/{agent.max_iterations}) — "
- "task could not complete within the allowed "
- "iterations"
- ),
- outcome="timed_out",
- release_claim=True,
- end_run=True,
- event_payload_extra={
- "budget_used": api_call_count,
- "budget_max": agent.max_iterations,
- },
- )
- logger.info(
- "recorded budget-exhausted failure for task %s (%d/%d)",
- _kanban_task, api_call_count, agent.max_iterations,
- )
- finally:
- try:
- _conn.close()
- except Exception:
- pass
- except Exception:
- logger.warning(
- "Failed to record budget-exhausted failure for task %s",
- _kanban_task,
- exc_info=True,
- )
+ _record_kanban_budget_exhausted(
+ _kanban_task, api_call_count, agent.max_iterations, logger,
+ )
+ elif budget_exhausted:
+ # Bounded fallback (#87096): budget was exhausted but none of the
+ # normal fallback paths were eligible (interrupted / failed /
+ # anomalous exit_reason). If running as a kanban worker we must
+ # still record a terminal outcome so the task does not remain in
+ # an ambiguous lifecycle state. The worker's run is closed via
+ # ``_record_task_failure`` (compare-and-swap receipt path) which
+ # is a no-op if another path closed it — the CAS invariant in
+ # ``_end_run`` (``WHERE ended_at IS NULL``) guarantees idempotence.
+ _kanban_task = os.environ.get("HERMES_KANBAN_TASK")
+ if _kanban_task:
+ _record_kanban_budget_exhausted(
+ _kanban_task, api_call_count, agent.max_iterations, logger,
+ )
# Determine if conversation completed successfully
normal_text_response = str(_turn_exit_reason).startswith("text_response(")
diff --git a/tests/agent/test_turn_finalizer_iteration_limit_exit.py b/tests/agent/test_turn_finalizer_iteration_limit_exit.py
index 8ed40f4377e..f6bf0519bd3 100644
--- a/tests/agent/test_turn_finalizer_iteration_limit_exit.py
+++ b/tests/agent/test_turn_finalizer_iteration_limit_exit.py
@@ -235,3 +235,141 @@ def test_published_pending_candidate_is_not_duplicated_by_finalizer(monkeypatch)
assert persisted_roles == ["user", "assistant"]
+def test_bounded_fallback_records_kanban_failure_when_interrupted(monkeypatch):
+ """When budget is exhausted and the turn was interrupted,
+ ``finalize_turn`` must still record a terminal kanban failure via
+ the bounded fallback path (#87096).
+ """
+ monkeypatch.setattr("hermes_cli.plugins.invoke_hook", lambda *_a, **_kw: [])
+ monkeypatch.setenv("HERMES_KANBAN_TASK", "task-456")
+ record = MagicMock(name="record_task_failure")
+ conn = SimpleNamespace(close=lambda: None)
+ monkeypatch.setattr("hermes_cli.kanban_db.connect", lambda: conn)
+ monkeypatch.setattr("hermes_cli.kanban_db._record_task_failure", record)
+ agent = _LimitAgent()
+
+ # Budget exhausted (60/60), interrupted, no fallback-eligible exit_reason
+ result = finalize_turn(
+ agent,
+ final_response=None,
+ api_call_count=60,
+ interrupted=True,
+ failed=False,
+ messages=[{"role": "user", "content": "task"}],
+ conversation_history=[],
+ effective_task_id="task",
+ turn_id="turn",
+ user_message="task",
+ original_user_message="task",
+ _should_review_memory=False,
+ _turn_exit_reason="interrupted_by_user",
+ )
+
+ # The bounded fallback must fire even though interrupted=True
+ # makes budget_fallback_eligible=False.
+ record.assert_called_once()
+ args, kwargs = record.call_args
+ assert args[1] == "task-456"
+ assert kwargs["outcome"] == "timed_out"
+ assert kwargs["release_claim"] is True
+ assert kwargs["end_run"] is True
+ assert kwargs["event_payload_extra"]["budget_used"] == 60
+ assert kwargs["event_payload_extra"]["budget_max"] == 60
+
+
+def test_bounded_fallback_records_kanban_failure_when_failed(monkeypatch):
+ """When budget is exhausted and the turn failed,
+ the bounded fallback must still record a terminal kanban failure (#87096).
+ """
+ monkeypatch.setattr("hermes_cli.plugins.invoke_hook", lambda *_a, **_kw: [])
+ monkeypatch.setenv("HERMES_KANBAN_TASK", "task-789")
+ record = MagicMock(name="record_task_failure")
+ conn = SimpleNamespace(close=lambda: None)
+ monkeypatch.setattr("hermes_cli.kanban_db.connect", lambda: conn)
+ monkeypatch.setattr("hermes_cli.kanban_db._record_task_failure", record)
+ agent = _LimitAgent()
+
+ result = finalize_turn(
+ agent,
+ final_response=None,
+ api_call_count=60,
+ interrupted=False,
+ failed=True,
+ messages=[{"role": "user", "content": "task"}],
+ conversation_history=[],
+ effective_task_id="task",
+ turn_id="turn",
+ user_message="task",
+ original_user_message="task",
+ _should_review_memory=False,
+ _turn_exit_reason="provider_failure",
+ )
+
+ record.assert_called_once()
+ args, kwargs = record.call_args
+ assert args[1] == "task-789"
+ assert kwargs["outcome"] == "timed_out"
+
+
+def test_bounded_fallback_does_not_fire_without_kanban_task(monkeypatch):
+ """When budget is exhausted and interrupted but no kanban task is
+ active, the bounded fallback must NOT fire (#87096).
+ """
+ monkeypatch.setattr("hermes_cli.plugins.invoke_hook", lambda *_a, **_kw: [])
+ record = MagicMock(name="record_task_failure")
+ conn = SimpleNamespace(close=lambda: None)
+ monkeypatch.setattr("hermes_cli.kanban_db.connect", lambda: conn)
+ monkeypatch.setattr("hermes_cli.kanban_db._record_task_failure", record)
+ agent = _LimitAgent()
+
+ result = finalize_turn(
+ agent,
+ final_response=None,
+ api_call_count=60,
+ interrupted=True,
+ failed=False,
+ messages=[{"role": "user", "content": "task"}],
+ conversation_history=[],
+ effective_task_id="task",
+ turn_id="turn",
+ user_message="task",
+ original_user_message="task",
+ _should_review_memory=False,
+ _turn_exit_reason="interrupted_by_user",
+ )
+
+ record.assert_not_called()
+
+
+def test_bounded_fallback_does_not_fire_when_budget_not_exhausted(monkeypatch):
+ """When budget is NOT exhausted but turn is interrupted and a kanban
+ task is active, the bounded fallback must NOT fire (#87096).
+ """
+ monkeypatch.setattr("hermes_cli.plugins.invoke_hook", lambda *_a, **_kw: [])
+ monkeypatch.setenv("HERMES_KANBAN_TASK", "task-999")
+ record = MagicMock(name="record_task_failure")
+ conn = SimpleNamespace(close=lambda: None)
+ monkeypatch.setattr("hermes_cli.kanban_db.connect", lambda: conn)
+ monkeypatch.setattr("hermes_cli.kanban_db._record_task_failure", record)
+ agent = _LimitAgent(budget_remaining=60)
+
+ # api_call_count=10, max_iterations=60 — budget NOT exhausted
+ result = finalize_turn(
+ agent,
+ final_response=None,
+ api_call_count=10,
+ interrupted=True,
+ failed=False,
+ messages=[{"role": "user", "content": "task"}],
+ conversation_history=[],
+ effective_task_id="task",
+ turn_id="turn",
+ user_message="task",
+ original_user_message="task",
+ _should_review_memory=False,
+ _turn_exit_reason="interrupted_by_user",
+ )
+
+ record.assert_not_called()
+
+