Skip to content

The agent that grows with you

fix: keep budget checkpoints out of cancelled tool results

Tekniuma7198a8855ad
diff --git a/agent/agent_init.py b/agent/agent_init.py
index 8d424a054b4..5f04649c364 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -10,7 +10,6 @@ Symbols that tests patch on ``run_agent.*`` (``OpenAI``, ``get_tool_definitions`
from __future__ import annotations
import logging
-import math
import os
import re
import sys
@@ -26,7 +25,7 @@ from urllib.parse import parse_qs, urlparse, urlunparse
from agent.context_compressor import ContextCompressor
from agent.agent_runtime_helpers import _ra
-from agent.iteration_budget import IterationBudget
+from agent.iteration_budget import IterationBudget, normalize_budget_warning_ratio
from agent.memory_manager import StreamingContextScrubber
from agent.session_activity import ActivityProvenance
from agent.model_metadata import (
@@ -318,16 +317,6 @@ def _normalize_run_budget_seconds(value) -> Optional[float]:
return seconds if seconds > 0 else None # NaN compares False → None
-def _normalize_budget_warning_ratio(value) -> Optional[float]:
- """A finite ratio strictly between zero and one, or None (feature off)."""
- if value is None or isinstance(value, bool):
- return None
- try:
- ratio = float(value)
- except (TypeError, ValueError):
- return None
- return ratio if math.isfinite(ratio) and 0 < ratio < 1 else None
-
def _refuse_checkpoint_required_on_codex_app_server(
checkpoint_required: bool, api_mode: Optional[str]
@@ -1320,7 +1309,7 @@ def _apply_agent_section(agent, _agent_cfg):
agent._skill_nudge_interval = int(_agent_cfg.get("skills", {}).get("creation_nudge_interval", 10))
_agent_section = _cfg_dict(_agent_cfg, "agent")
- agent.budget_warning_ratio = _normalize_budget_warning_ratio(
+ agent.budget_warning_ratio = normalize_budget_warning_ratio(
_agent_section.get("budget_warning_ratio")
)
# Both: "auto" (model-list match), true, false, or list of model substrings; independent
diff --git a/agent/iteration_budget.py b/agent/iteration_budget.py
index 1d1dfccdb64..d2e81ce12fa 100644
--- a/agent/iteration_budget.py
+++ b/agent/iteration_budget.py
@@ -7,9 +7,21 @@ cap is ``max_iterations`` (default 500), each subagent's ``delegation.max_iterat
from __future__ import annotations
+import math
import threading
+def normalize_budget_warning_ratio(value) -> float | None:
+ """A finite ratio strictly between zero and one, or None (feature off)."""
+ if value is None or isinstance(value, bool):
+ return None
+ try:
+ ratio = float(value)
+ except (TypeError, ValueError):
+ return None
+ return ratio if math.isfinite(ratio) and 0 < ratio < 1 else None
+
+
class IterationBudget:
"""Thread-safe iteration counter; ``execute_code`` (programmatic tool calling)
iterations are refunded via :meth:`refund` so they don't eat into the budget."""
diff --git a/agent/turn_iteration_prep.py b/agent/turn_iteration_prep.py
index 7790fcca665..a6541073d1a 100644
--- a/agent/turn_iteration_prep.py
+++ b/agent/turn_iteration_prep.py
@@ -33,6 +33,10 @@ def _maybe_inject_iteration_budget_warning(agent: Any, messages: Any) -> bool:
import os
from agent.delegation_context import is_dispatcher_owned_worker_context
+ # Cancellation results still need persistence, but must not urge more work.
+ if getattr(agent, "_interrupt_requested", False):
+ return False
+
ratio = getattr(agent, "budget_warning_ratio", None)
kanban_worker = (
bool(os.environ.get("HERMES_KANBAN_TASK"))
@@ -347,11 +351,8 @@ def begin_iteration(
# Grace call: budget exhausted but the model gets one more call. Consume the
# flag so the loop exits after this iteration regardless of outcome.
if agent._budget_grace_call:
- # Iteration budget: the LLM is only notified when it actually exhausts the iteration budget
- # (api_call_count >= max_iterations). At that point we inject ONE message, allow one final API call,
- # and if the model doesn't produce a text response, force a user-message asking it to summarise. No
- # intermediate pressure warnings — they caused models to "give up" prematurely on complex tasks
- # (#7915).
+ # Exhaustion retains one toolless grace call regardless of whether an opt-in
+ # checkpoint was emitted; the warning never extends the hard budget.
agent._budget_grace_call = False
elif not agent.iteration_budget.consume():
_turn_exit_reason = "budget_exhausted"
diff --git a/tests/agent/test_iteration_budget_warning.py b/tests/agent/test_iteration_budget_warning.py
index 0001c23672b..a1fdce440b1 100644
--- a/tests/agent/test_iteration_budget_warning.py
+++ b/tests/agent/test_iteration_budget_warning.py
@@ -11,50 +11,50 @@ def _agent(tmp_path, monkeypatch, ratio):
)
from run_agent import AIAgent
from hermes_state import SessionDB
+ from model_tools import _clear_tool_defs_cache
+ from tools.registry import invalidate_check_fn_cache
+
+ # Cases model separate worker processes; their availability caches must not
+ # survive a change from ordinary to dispatcher-owned construction.
+ invalidate_check_fn_cache()
+ _clear_tool_defs_cache()
return AIAgent(session_db=SessionDB(db_path=tmp_path / "proof.db"),
model="test-model", provider="openai-compat", api_key="test",
base_url="http://127.0.0.1:1/v1", max_iterations=4,
quiet_mode=True, skip_context_files=True, skip_memory=True)
[email protected]("ratio", ["null", "true", "0", "1", ".nan", "junk", "0.75"])
-def test_checkpoint_is_opt_in_and_does_not_rewrite_prior_turns(tmp_path, monkeypatch, ratio):
- from agent.turn_iteration_prep import prepare_iteration
- agent = _agent(tmp_path, monkeypatch, ratio)
- for _ in range(3):
- agent.iteration_budget.consume()
- messages = [{"role": "user", "content": "work"},
- {"role": "assistant", "tool_calls": [{"id": "t", "type": "function", "function": {"name": "read_file", "arguments": "{}"}}]},
- {"role": "tool", "tool_call_id": "t", "content": "result"}]
- original = deepcopy(messages)
- prepare_iteration(agent, messages=messages, api_call_count=3)
- assert messages[:-1] == original[:-1]
- assert (messages[-1]["content"] != "result") == (ratio == "0.75")
- snapshot = deepcopy(messages)
- prepare_iteration(agent, messages=messages, api_call_count=3)
- assert messages == snapshot
- assert agent.iteration_budget.used == 3
-
-
@pytest.mark.parametrize("content", ["result", [{"type": "text", "text": "result"}]])
-def test_checkpoint_rearms_per_turn_with_tools_still_available(tmp_path, monkeypatch, content):
[email protected]("interrupted", [False, True])
+def test_checkpoint_rearms_per_turn_without_changing_budget_or_durable_rows(
+ tmp_path, monkeypatch, content, interrupted
+):
from agent.turn_context import _reset_per_turn_agent_state
from agent.turn_iteration_prep import prepare_iteration
+ from agent.tool_executor import _flush_session_db_after_tool_progress
+
agent = _agent(tmp_path, monkeypatch, "0.75")
- for _ in range(2):
- _reset_per_turn_agent_state(agent)
- for _ in range(3):
- agent.iteration_budget.consume()
- messages = [{"role": "user", "content": "work"},
- {"role": "assistant", "tool_calls": [{"id": "t", "type": "function", "function": {"name": "read_file", "arguments": "{}"}}]},
- {"role": "tool", "tool_call_id": "t", "content": deepcopy(content)}]
- from agent.tool_executor import _flush_session_db_after_tool_progress
- assert _flush_session_db_after_tool_progress(agent, messages, stage="checkpoint")
- persisted = agent._session_db.get_messages(agent.session_id)
- assert "3 of 4" in str(persisted[-1]["content"])
- snapshot = deepcopy(messages)
- prepare_iteration(agent, messages=messages, api_call_count=3)
- assert messages == snapshot
- assert "3 of 4" in str(messages[-1]["content"])
- assert agent.iteration_budget.consume()
- assert not agent.iteration_budget.consume()
+ try:
+ for turn in range(2):
+ _reset_per_turn_agent_state(agent)
+ agent._interrupt_requested = interrupted
+ for _ in range(3):
+ agent.iteration_budget.consume()
+ messages = [{"role": "user", "content": f"work {turn}"},
+ {"role": "assistant", "tool_calls": [{"id": f"t{turn}", "type": "function", "function": {"name": "read_file", "arguments": "{}"}}]},
+ {"role": "tool", "tool_call_id": f"t{turn}", "content": deepcopy(content)}]
+ assert _flush_session_db_after_tool_progress(agent, messages, stage="checkpoint")
+ persisted = agent._session_db.get_messages(agent.session_id)
+ notices = sum("iteration budget checkpoint" in str(row["content"]) for row in persisted)
+ assert notices == (0 if interrupted else turn + 1)
+ assert ("3 of 4" in str(messages[-1]["content"])) is not interrupted
+ snapshot = deepcopy(messages)
+ # A durable result is never rewritten, even after interruption clears
+ # and a new turn has rearmed the notice latch.
+ agent._interrupt_requested = False
+ prepare_iteration(agent, messages=messages, api_call_count=3)
+ assert messages == snapshot
+ assert agent.iteration_budget.consume()
+ assert not agent.iteration_budget.consume()
+ finally:
+ agent._session_db.close()
diff --git a/tests/agent/test_kanban_budget_checkpoint.py b/tests/agent/test_kanban_budget_checkpoint.py
index c3ea13eca08..6d3bae69a09 100644
--- a/tests/agent/test_kanban_budget_checkpoint.py
+++ b/tests/agent/test_kanban_budget_checkpoint.py
@@ -1,19 +1,47 @@
+"""Checkpoint eligibility follows explicit opt-in or dispatcher ownership."""
+from contextlib import nullcontext
+from copy import deepcopy
+
import pytest
from tests.agent.test_iteration_budget_warning import _agent
[email protected]("owned", [True, False])
-def test_kanban_checkpoint_is_only_for_dispatcher_owner(tmp_path, monkeypatch, owned):
- from agent.delegation_context import non_dispatcher_owned_context
- from contextlib import nullcontext
+
[email protected]("ratio,scope,expected,kanban_notice", [
+ *[(ratio, "ordinary", False, False) for ratio in ("null", "true", "0", "1", ".nan", "junk")],
+ ("0.75", "ordinary", True, False),
+ ("null", "owner", True, True),
+ ("null", "non-owner", False, False),
+ ("null", "child", False, False),
+ ("0.75", "child", True, False),
+ ("null", "no-completion-tool", False, False),
+])
+def test_checkpoint_requires_opt_in_or_dispatcher_completion_scope(
+ tmp_path, monkeypatch, ratio, scope, expected, kanban_notice
+):
+ from agent.delegation_context import delegated_child_context, non_dispatcher_owned_context
from agent.turn_iteration_prep import prepare_iteration
- monkeypatch.setenv("HERMES_KANBAN_TASK", "t_checkpoint")
- with nullcontext() if owned else non_dispatcher_owned_context():
- agent = _agent(tmp_path, monkeypatch, "null")
- for _ in range(4):
- agent.iteration_budget.consume()
- messages = [{"role": "user", "content": "work"},
- {"role": "assistant", "tool_calls": [{"id": "t", "type": "function", "function": {"name": "read_file", "arguments": "{}"}}]},
- {"role": "tool", "tool_call_id": "t", "content": "verified artifact"}]
- prepare_iteration(agent, messages=messages, api_call_count=4)
- assert ("kanban_complete" in messages[-1]["content"]) is owned
- assert agent.iteration_budget.remaining == 0
+
+ if scope != "ordinary":
+ monkeypatch.setenv("HERMES_KANBAN_TASK", "t_checkpoint")
+ contexts = {"non-owner": non_dispatcher_owned_context, "child": delegated_child_context}
+ with contexts.get(scope, nullcontext)():
+ agent = _agent(tmp_path, monkeypatch, ratio)
+ try:
+ if scope == "no-completion-tool":
+ agent.valid_tool_names.discard("kanban_complete")
+ for _ in range(3):
+ agent.iteration_budget.consume()
+ messages = [{"role": "user", "content": "work"},
+ {"role": "assistant", "tool_calls": [{"id": "t", "type": "function", "function": {"name": "read_file", "arguments": "{}"}}]},
+ {"role": "tool", "tool_call_id": "t", "content": "verified artifact"}]
+ original = deepcopy(messages)
+ prepare_iteration(agent, messages=messages, api_call_count=3)
+ assert messages[:-1] == original[:-1]
+ assert (messages[-1]["content"] != "verified artifact") is expected
+ assert ("kanban_complete" in messages[-1]["content"]) is kanban_notice
+ snapshot = deepcopy(messages)
+ prepare_iteration(agent, messages=messages, api_call_count=3)
+ assert messages == snapshot
+ assert agent.iteration_budget.remaining == 1
+ finally:
+ agent._session_db.close()