Skip to content

The agent that grows with you

fix(agent): ignore execute_code per-call metadata in the loop-detector result hash

Daniel.lu0cc43227d9fd
diff --git a/agent/tool_guardrails.py b/agent/tool_guardrails.py
index c6dd1f3d9e3..b68a9ff5835 100644
--- a/agent/tool_guardrails.py
+++ b/agent/tool_guardrails.py
@@ -422,7 +422,7 @@ class ToolCallGuardrailController:
self._no_progress.pop(signature, None)
return ToolGuardrailDecision(tool_name=tool_name, signature=signature)
- result_hash = _result_hash(result)
+ result_hash = _result_hash(result, tool_name)
previous = self._no_progress.get(signature)
repeat_count = previous[1] + 1 if previous is not None and previous[0] == result_hash else 1
self._no_progress[signature] = (result_hash, repeat_count)
@@ -446,7 +446,7 @@ class ToolCallGuardrailController:
"""
is_plain_str = isinstance(result, str)
signature = ToolCallSignature.from_call(tool_name, _coerce_args(args))
- result_hash = _result_hash(result) if is_plain_str else ""
+ result_hash = _result_hash(result, tool_name) if is_plain_str else ""
if is_plain_str and (signature, result_hash) == (self._identical_streak_sig, self._identical_streak_result_hash):
self._identical_streak_count += 1
@@ -600,9 +600,28 @@ def _coerce_args(args: Mapping[str, Any] | None) -> Mapping[str, Any]:
return args if isinstance(args, Mapping) else {}
-def _result_hash(result: str | None) -> str:
+# execute_code reports per-call kernel bookkeeping — a running `kernel.execution_count` and wall-clock
+# `duration_seconds` — that changes on every invocation even when the code did the same thing. Hashed
+# as-is, every replay of an identical empty probe looks new and the identical-call streak never forms
+# (a model re-ran one empty execute_code call 147 times unflagged). Only these known locations in
+# execute_code's own result shape are dropped: for any other tool the same key names can be real output.
+def _without_execute_code_metadata(parsed: Any) -> Any:
+ if not isinstance(parsed, dict):
+ return parsed
+ cleaned = {k: v for k, v in parsed.items() if k != "duration_seconds"}
+ kernel = cleaned.get("kernel")
+ if isinstance(kernel, dict):
+ cleaned["kernel"] = {k: v for k, v in kernel.items() if k != "execution_count"}
+ return cleaned
+
+
+def _result_hash(result: str | None, tool_name: str = "") -> str:
parsed = safe_json_loads(result or "")
- return _sha256(_canonical_json(parsed) if parsed is not None else (result or ""))
+ if parsed is None:
+ return _sha256(result or "")
+ if tool_name == "execute_code":
+ parsed = _without_execute_code_metadata(parsed)
+ return _sha256(_canonical_json(parsed))
_BOOL_WORDS = {w: True for w in ("1", "true", "yes", "on", "enabled")} | {w: False for w in ("0", "false", "no", "off", "disabled")}
diff --git a/tests/agent/test_tool_guardrails.py b/tests/agent/test_tool_guardrails.py
index b6dc0ad66ed..931f7052c0b 100644
--- a/tests/agent/test_tool_guardrails.py
+++ b/tests/agent/test_tool_guardrails.py
@@ -400,3 +400,56 @@ def test_a_real_tool_error_is_still_a_failure():
assert _detect_tool_failure("read_file", real)[0] is True
# The marker is only honoured as the literal boolean, never as truthy prose.
assert classify_tool_failure("read_file", '{"error": "x", "guardrail_refusal": "yes"}')[0] is True
+
+
+def test_identical_streak_ignores_volatile_execution_metadata():
+ # execute_code results carry per-call metadata (execution_count, duration_seconds) that
+ # changes on every run. Hashing it made each empty replay look "new", so a model re-ran
+ # the same empty probe 147 times without the identical-call halt ever firing.
+ controller = ToolCallGuardrailController(
+ ToolCallGuardrailConfig(hard_stop_enabled=True, no_progress_block_after=5)
+ )
+ args = {"code": "import subprocess\nprint(subprocess.run(['true']).returncode) if False else None"}
+
+ def result(n):
+ return json.dumps({
+ "status": "success", "output": "", "exit_code": 0, "tool_calls_made": 0,
+ "duration_seconds": 1.0 + n / 100,
+ "kernel": {"mode": "session", "reused": True, "execution_count": 100 + n, "state_reset": False},
+ "stdout_truncated": False, "stdout_bytes_captured": 0,
+ })
+
+ for i in range(4):
+ controller.observe_call("execute_code", args, result(i), failed=False)
+ assert controller.halt_decision is None, f"halted early at {i}"
+ controller.observe_call("execute_code", args, result(4), failed=False)
+ halt = controller.halt_decision
+ assert halt is not None, "volatile metadata defeated the identical-call streak"
+ assert halt.code == "identical_call_streak_halt"
+
+
+def test_identical_streak_still_resets_when_real_output_changes():
+ controller = ToolCallGuardrailController(
+ ToolCallGuardrailConfig(hard_stop_enabled=True, no_progress_block_after=3)
+ )
+ args = {"code": "print(1)"}
+ for i in range(6):
+ out = json.dumps({"status": "success", "output": f"line {i}", "duration_seconds": 1.0,
+ "kernel": {"execution_count": i}})
+ controller.observe_call("execute_code", args, out, failed=False)
+ assert controller.halt_decision is None, "different real output must not count as a replay"
+
+
+def test_other_tools_keep_duration_and_execution_count_as_real_output():
+ # Only execute_code's known metadata locations are volatile. For any other tool these keys
+ # can be the actual answer (e.g. a job-status tool reporting how long a job ran), so results
+ # that differ only there are different results and must not form an identical streak.
+ controller = ToolCallGuardrailController(
+ ToolCallGuardrailConfig(hard_stop_enabled=True, no_progress_block_after=3)
+ )
+ args = {"job": "build-42"}
+ for i in range(6):
+ out = json.dumps({"status": "done", "duration_seconds": 10 + i,
+ "stats": {"execution_count": 100 + i}})
+ controller.observe_call("mcp_ci_job_status", args, out, failed=False)
+ assert controller.halt_decision is None, "a real change in duration_seconds/execution_count was treated as a replay"