The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(guardrails): retrying a rate-limited call is not counted as a replay
Teknium455e0a7402b5
diff --git a/agent/tool_guardrails.py b/agent/tool_guardrails.pyindex 116cd9e95b5..489b6b05d7b 100644--- a/agent/tool_guardrails.py+++ b/agent/tool_guardrails.py@@ -15,7 +15,7 @@ from typing import Any, Mappingfrom utils import safe_json_loadsfrom agent.tool_result_classification import (- shape_failure_error, file_mutation_result_landed, has_failure_marker, is_guardrail_refusal)+ shape_failure_error, file_mutation_result_landed, has_failure_marker, is_guardrail_refusal, is_rate_limited)IDEMPOTENT_TOOL_NAMES = frozenset({@@ -392,7 +392,12 @@ class ToolCallGuardrailController:# a mutation since the last identical failure restarts the exact-args streak.if self._progress_since_failure.pop(signature, False):self._exact_failure_counts.pop(signature, None)- exact_count = self._exact_failure_counts[signature] = self._exact_failure_counts.get(signature, 0) + 1+ # A throttled call retried after its cooldown is the correct move, not a replay:+ # keep it out of the exact-args streak (whose warning says "stop retrying unchanged").+ # It still counts per tool below, so same_tool_failure_halt bounds a dead endpoint.+ exact_count = self._exact_failure_counts.get(signature, 0)+ if not is_rate_limited(result):+ exact_count = self._exact_failure_counts[signature] = exact_count + 1same_count = self._same_tool_failure_counts[tool_name] = self._same_tool_failure_counts.get(tool_name, 0) + 1self._no_progress.pop(signature, None)# same_tool_failure counts DIFFERENT args on one tool; for failure-tolerantdiff --git a/agent/tool_result_classification.py b/agent/tool_result_classification.pyindex 77aac93c8bc..f1c9161cdf2 100644--- a/agent/tool_result_classification.py+++ b/agent/tool_result_classification.py@@ -60,6 +60,28 @@ def has_failure_marker(result: str) -> bool:# ``timeout`` is deliberately absent: process(wait) returns it for a still-running job._FAILED_STATUSES = frozenset({"failed", "error"})+_RATE_LIMIT_RE = re.compile(r"rate[\s_-]?limit|too many requests|\b429\b", re.IGNORECASE)+_RETRY_AFTER_KEYS = ("retry_after", "retryAfter", "retry_after_seconds", "retry_after_ms")+++def is_rate_limited(result: Any) -> bool:+ """True when a FAILED result says the backend throttled the call (a ``retry_after`` field, a 429+ status, or rate-limit wording in its error). Only meaningful for results already judged failed:+ a successful page can mention rate limits in its content."""+ data = result+ if isinstance(result, str):+ try:+ data = json.loads(result.strip())+ except ValueError:+ return bool(_RATE_LIMIT_RE.search(result[:500]))+ if not isinstance(data, dict):+ return False+ if any(data.get(k) for k in _RETRY_AFTER_KEYS) or 429 in (data.get("status"), data.get("status_code"), data.get("code")):+ return True+ error = data.get("error")+ text = error.get("message") or error.get("code") if isinstance(error, dict) else error+ return isinstance(text, str) and bool(_RATE_LIMIT_RE.search(text))+def shape_failure_error(data: dict) -> str | None:"""Error text when a JSON-object result failed by SHAPE rather than by its top-leveldiff --git a/tests/agent/test_tool_guardrails.py b/tests/agent/test_tool_guardrails.pyindex 430fdb5e935..b9368d7aeab 100644--- a/tests/agent/test_tool_guardrails.py+++ b/tests/agent/test_tool_guardrails.py@@ -2,6 +2,8 @@import json+import pytest+from agent.tool_guardrails import (ToolCallGuardrailConfig,ToolCallGuardrailController,@@ -478,3 +480,23 @@ def test_execute_code_replay_streak_notice_fires_on_warn_only_desktop_config():assert notices[:2] == [None, None]assert all(n is not None and "consecutive identical call to execute_code" in n for n in notices[2:]), noticesassert controller.halt_decision is None, "warn-only surfaces must not halt"++[email protected]("result,second_attempt", [+ (json.dumps({"error": "Slack API error: ratelimited. Retry after 1 seconds."}), "allow"),+ (json.dumps({"ok": False, "error": "busy", "retry_after": 30}), "allow"),+ (json.dumps({"error": "channel_not_found"}), "warn"), # control: a real replay still warns+])+def test_rate_limited_retry_is_not_a_replay_but_stays_bounded(result, second_attempt):+ """Retrying a throttled read after its cooldown must not draw the "stop retrying unchanged"+ warning, yet an endpoint that never recovers still halts unattended runs on the per-tool cap."""+ controller = ToolCallGuardrailController(ToolCallGuardrailConfig.from_mapping({}, platform="webhook"))+ args = {"channel": "C123"}+ actions = []+ for _ in range(10):+ if not controller.before_call("mcp_slack_history", args).allows_execution:+ actions.append("block")+ break+ actions.append(controller.after_call("mcp_slack_history", args, result).action)+ assert actions[1] == second_attempt+ assert actions[-1] in {"halt", "block"}, actions