Skip to content

fix(agent): the loop guard corrects before it stops, and names the real cause - #3908

Merged
kovtcharov-amd merged 2 commits into
amd:mainfrom
kovtcharov:claude/fix-3888-loop-guard
Sep 24, 2026
Merged

kovtcharov-amd merged 2 commits into
amd:mainfrom
kovtcharov:claude/fix-3888-loop-guard

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

After four identical tool calls, the agent ended the task and blamed a service outage. In a 168-run Fireworks benchmark the guard fired 6 times with no outage behind any of them: a throttle where none of the calls ran, a policy refusal, a bad argument, a 404, and a test script that exited non-zero. Two of those stops replaced a finished refactor's answer with "it kept failing … check that the underlying service is running." Now throttled calls don't count as repeats, the model gets one "try a different approach" correction before the guard stops it, and the final message names the real cause (rate-limited, not permitted, or the actual error — the service hint only for connection failures).

The legacy tool path also summarised every failing loop as "Task completed", because error recovery cleared the results it read; it now reads the same history as the native path.

Test plan

  • pytest tests/unit/agents/test_loop_guard_correction.py — throttled calls not counted (and the wait is capped/cancellable), correction injected before termination on both the legacy and native paths (native keeps its tool_call_id), and each summary variant: rate-limited, not permitted, connection, plain failure, last stderr line, return code; output that merely mentions "blocked" stays a plain failure; a repeat limit below 2 is refused
  • pytest tests/unit/agents/ hub/agents/gaia/python/tests hub/agents/chat/python/tests — 1540 passed; the 3 failures (tool-count goldens) fail on main in the same environment
  • Agent eval gate: runs in the self-hosted CI job once the branch is pushed to amd/gaia (this changes agent-loop behaviour)

Fixes #3888

@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

This fixes a real and well-diagnosed problem: the agent used to end a task after four identical tool calls and tell the user a service was down, even when nothing was down. Now a throttled call (which never ran) doesn't count as a repeat, the model gets one "try something else" nudge before the turn is killed, and the closing message names the actual cause. The legacy tool path also stops reporting "Task completed" on a loop of failures — that was reading a results list that error recovery had already emptied.

Two things to look at before merging:

  • The error-cause classifier can still mislabel a connection failure as a permission problem on Windows. The Windows "target machine actively refused it" message doesn't match the connection patterns, but it does match the refusal patterns, so the user gets "not permitted here — try splitting it into steps" instead of "check that the service is running." That's the same class of wrong answer this PR is fixing, just on a different platform.
  • The agent eval hasn't run yet. This changes agent-loop behaviour, which the project's rules make a hard gate. You've already marked it pending on the combined branch — it just needs to be green before this lands.

Smaller: the counts in both the nudge and the final message are one or two higher than the number of calls that actually executed, since the repeats that trigger the guard are never run.

Real-world evidence

N/A — no evidence bundle was produced for this run. The change is internal to the agent loop with no CLI/API/UI surface of its own, so the automated lane had nothing to exercise; the behaviour it does change is user-visible in chat output, and that is exactly what the pending agent-eval run would cover. The verdict here rests on static review plus the unit tests in the PR.

🔍 Technical details

🟡 Important

Windows connection refusals classify as "not permitted" (src/gaia/agents/base/agent.py:7240-7251)

_LOOP_CONNECTION_RE requires the literal connection refused (with the space), so the standard Windows socket error — [WinError 10061] No connection could be made because the target machine actively refused it — misses it and falls through to _LOOP_NOT_PERMITTED_RE, which matches on the bare refus fragment. Result: "…but it is not permitted here… Try a different approach — for example, split it into separate steps" for a dead Lemonade/LLM server on GAIA's primary platform. ConnectionRefusedError: [Errno 111] Connection refused happens to be safe only because the POSIX strerror includes the spaced form.

    _LOOP_CONNECTION_RE = re.compile(
        r"connection (?:refused|reset|aborted|error)|connecterror|not reachable"
        r"|unreachable|could not connect|failed to establish|max retries exceeded"
        r"|name or service not known|getaddrinfo|connect(?:ion)? timed out"
        r"|actively refused|no connection could be made|winerror 1006\d",
        re.IGNORECASE,
    )

Worth a parametrized case in test_summary_for_a_connection_error_keeps_the_service_hint for the WinError string. Separately, refus as a standalone alternative in _LOOP_NOT_PERMITTED_RE is broad enough to catch other prose ("refusing to overwrite", "peer refused"); refused (?:by|to)|refus(?:ed|es) (?:the )?(?:request|access|operation) would be tighter, but the connection-regex fix above is the one that matters.

Agent eval not yet run (process, not a code line)

CLAUDE.md → "Run agent evals when changing LLM-affecting code paths" names the agent-loop catchall and error classification explicitly. This PR changes both the loop-exit condition and the text injected back into the conversation, so gaia eval agent against the relevant category, diffed against tests/fixtures/eval_baselines/…, is the gate. The test plan already tracks it unchecked — flagging once so it isn't lost in the combined-branch merge.

🟢 Minor

Repeat counts overstate the calls that actually ran (agent.py:7300, agent.py:7319)

With max_consecutive_repeats=4, the correction fires at consecutive_count == 4 after only 3 executions, and the terminal summary fires at 5 after the same 3. The model is told "You have called X 4 times" and the user reads "I tried calling X 5 times". The visible test makes this concrete: agent.calls == 2 while the correction says "called … 3 times". Passing consecutive_count - 1 at the correction site (and - 2 at the break, since the corrected call also didn't run) would make both honest — or just reword to "repeatedly" and drop the number.

Throttled calls are now fully exempt from the loop guard (agent.py:6280-6283, agent.py:6525-6528)

Popping from tool_call_history means a persistently throttled tool can never trip the guard; the only bound is max_steps, and each retry can sleep up to _RATE_LIMIT_WAIT_CAP_S in-band. In practice the shell limiter's windows (3/10 s, 10/min) drain within a few capped waits and the cap is cancel-event aware, so this is bounded at tens of seconds rather than unbounded — but it is worth a comment saying so, since the 15 s cap is deliberately shorter than the 60 s wait the per-minute limit reports, which guarantees at least one wasted retry.

Stale parameter name (agent.py:7316-7321)

_build_loop_break_summary(..., step_results: list) — both call sites now pass a list derived from previous_outputs, and the whole point of the fix is that step_results is the wrong source. Renaming to recent_results matches the callers and the new docstring.

Strengths

  • The diagnosis is empirical, not speculative: six real guard firings across a 168-run benchmark, each categorized, with the fix shaped to the categories found. That's the right way to change agent-loop heuristics.
  • previous_outputs vs step_results is a genuinely subtle bug — step_results.clear() in the error-recovery branch (agent.py:5465) runs before the next repeat is evaluated, so the legacy path was structurally guaranteed to see an empty list and print "Task completed" on a loop of pure failures. Catching that, and leaving a one-line comment naming the reason, is exactly the right depth.
  • Test coverage is thorough and reads well: both the native and legacy paths, tool_call_id pairing preserved on the native correction, the wait cap and cancel-event behaviour, and one case per summary variant including the stderr-fallback and return-code-fallback branches. The test_verification_scope.py update correctly rewrites the stale docstring rather than just flipping the assertion.
  • No silent fallbacks introduced — _wait_out_rate_limit logs and returns on a non-numeric wait_time_seconds instead of guessing a duration, which matches the project's fail-loudly rule.

@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve

The loop guard now corrects before it stops, and rate-throttled calls no longer count as repeats — two clean, independently useful improvements that ship together naturally.

No blocking issues. A few things worth noting for the record:

The shared loop_corrected_calls set keys on (tool_name, str(tool_args)) and is correctly shared between the native fan-out path and the legacy embedded-JSON path, so a correction issued during a fan-out turn is still honoured if the legacy path fires next.

The correction message in the native path passes tool_call_id to _create_tool_message; the legacy path omits it — both are correct for their respective message formats.

The _LOOP_CONNECTION_RE / _LOOP_NOT_PERMITTED_RE ordering in _build_loop_break_summary is critical: "actively refused" matches refus in the permission pattern but also matches actively refused in the connection pattern, and the connection check runs first, so Windows socket errors correctly route to the "check the service" message rather than "try a different approach."

The test_verification_scope.py change is correct — the old assertion was explicitly testing the pre-fix wrong behaviour and the comment said so; the new assertion tests the now-fixed output.

One note for the commit record: the correction message says "called N times" where N equals consecutive_count at the guard threshold, but only N−1 calls actually executed (the Nth triggers the guard and is skipped). This is intentional — the count reflects the detected pattern, not the execution count — but worth knowing if the wording ever needs tuning.

@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve — the loop-guard correction mechanism is correct, well-scoped, and has thorough tests.

The PR adds three things: a one-shot correction message before the loop terminates (giving the model one chance to change approach), rate-limit-aware repeat counting (throttled results don't advance the repeat counter), and better-categorized terminal summaries that name the real cause.

The logic is sound. A few things I verified:

  • loop_corrected_calls is correctly scoped to the turn (initialized at the top of process_query's loop), so each turn gets a fresh set.
  • The correction in the native path passes tool_call_id for correct pairing; the legacy path correctly omits it since that format has no tool call IDs.
  • step_results → recent_results substitution in the terminal path is correct: the comment explains step_results can be cleared during error recovery, making recent_results the reliable source.
  • _LOOP_CONNECTION_RE is checked before _LOOP_NOT_PERMITTED_RE, so Windows "actively refused" is correctly routed to the service-hint branch rather than the permissions branch. The regex patterns and test coverage for this case are both present.
  • After _wait_out_rate_limit, the throttled result falls through to normal processing (the LLM sees the rate-limit error and retries). This is intentional and verified by test_rate_limited_calls_do_not_count_toward_the_limit.

Tests in test_loop_guard_correction.py cover correction injection, native/legacy path tool_call_id handling, throttle counting, wait cap, cancel-event honoring, and all four terminal summary branches. test_verification_scope.py gets a docstring tweak only.

No security concerns. No silent fallbacks introduced. Scope is clean.

@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

The loop-guard correction flow is sound — giving the LLM one chance to self-correct before hard-stopping is exactly the right UX, and counting only calls that actually ran prevents misleading "tried N times" messages. The new test file covers the correction flow, throttle handling, and all four terminal-summary categories (rate-limited, connection error, not-permitted, plain failure). The Windows socket-error fix (actively refused / no connection could be made → connection regex) is verified by name.

🟢 One nit: blocked in _LOOP_NOT_PERMITTED_RE is unusually broad. A tool logging "IO blocked" or "blocked by CORS" would be classified as a policy refusal and told to "split the task into steps" instead of the generic failure path. Since the connection check runs first, this can't misfire on dead-service errors, but it could misfire on unrelated tool output. Consider \bblocked\b or a tighter phrase like blocked by policy|blocked by administrator.

🔍 Technical details

The -2 arithmetic is correct. With max_consecutive_repeats = N: N-1 calls actually run; the Nth hits threshold (appended to history, correction sent, continue); the (N+1)th hits threshold again (appended to history, terminates). History length at termination = N+1, so consecutive_count - 2 = N-1 = actual_run_count. Verified for N=2,3 in both the test assertions and manual trace.

|blocked| in _LOOP_NOT_PERMITTED_RE (agent.py:7252 approximately):

        r"not allowed|not permitted|not in (?:the )?allowed|access denied"
        r"|permission denied|\bblocked\b|refused (?:by|to)"
        r"|refus(?:ed|es) (?:the )?(?:request|access|operation)",

tool_call_history.pop() for throttled calls — correct and bounded as the comment says. The list can't underflow because the append that adds the entry happens unconditionally before _execute_tool_timed, and the pop is guarded by _is_throttled_result (which only fires when the tool actually returned a rate-limited dict, never on a tool that threw).

Both execution paths covered — the success branch (line ~6280) and the error branch (line ~6524) both get the throttle pop and the loop_corrected_calls correction logic. The native-path test (test_native_path_correction_answers_the_tool_call_id) confirms the tool_call_id is threaded correctly for OpenAI-format tool calls.

@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve 🟢

The correction-before-termination logic is sound and the tests cover it well. No blocking issues found.

Two small observations worth a look before merge:

🟡 _LOOP_NOT_PERMITTED_RE includes r"blocked" with no word-boundary anchors — "unblocked", "blocked ports", or any tool output containing that word as a substring would incorrectly classify a plain failure as a permissions issue. A word-boundary (\bblocked\b) or a more specific phrase would tighten this.

🟢 _loop_correction_result says "You have called {tool} 0 times with the same arguments" when max_consecutive_repeats = 1 (threshold fires before the tool's first run, so executed_count = consecutive_count - 1 = 0). The default is 3 so this is an edge case, but the message is grammatically odd. Clamping to max(1, executed_count) or documenting min_value = 2 would clean it up.

🔍 Technical details

blocked substring match (agent.py — _LOOP_NOT_PERMITTED_RE):
The pattern r"blocked" (no word boundaries) matches any string containing "blocked" anywhere. Tool output like "processing blocked ports list", "unblocked 3 connections", or "data transfer blocked temporarily" would trigger the "not permitted here — try a different approach" message instead of the plain-failure branch. Suggested fix: r"\bblocked\b" or replace with a more specific phrase like r"operation blocked".

executed_count = 0 correction message:
At max_consecutive_repeats = 1: threshold fires at consecutive_count = 1, before any execution, so executed_count = 1 - 1 = 0. The correction reads: "You have called X 0 times with the same arguments and it returned no new progress." This is factually correct (0 runs) but grammatically strange.

For context: the test suite only exercises max_consecutive_repeats = 3, so neither of these is covered by the new test file.

@kovtcharov

Copy link
Copy Markdown
Contributor Author

Tool output that only mentions "blocked", like "unblocked 3 connections", is no longer reported to the user as "not permitted here". A repeat limit below 2 now fails when the agent is built, instead of producing a guard that never lets a tool run and a message saying "called X 0 times".

Still open: the agent eval, which runs in the self-hosted CI job once a maintainer pushes this branch to amd/gaia.

🔍 Technical details
  • 🟡 Bare blocked in _LOOP_NOT_PERMITTED_RE (7110edd): \bblocked\b alone still matches "IO blocked" and "blocked ports", so I narrowed it to verdict phrasings: blocked by, (is|are|was|were|been) blocked and edit blocked. These still catch GAIA's own refusals: "Downloaded file blocked by security policy", "Edit blocked: …", the wmic "… are blocked." and "Read-only query blocked by SQLite". Tests cover three false positives, which now read as plain failures, and three real verdicts, which still read as not permitted.
  • 🟢 "called X 0 times" (7110edd): I required the limit to be at least 2 rather than clamping the count. At 1 the guard counts the call being made, so every tool call is a repeat of itself and nothing ever runs; clamping would only hide that. Agent.__init__ raises ValueError naming the minimum. The docstring and docs/spec/agent-base.mdx state the limit. Tests cover limits of 1, 0 and -1, plus 2 reporting "called … 1 times" after the one real call.
  • Main: this branch still merges cleanly, so I didn't merge.
  • Verified: pytest tests/unit/agents/ hub/agents/gaia/python/tests hub/agents/chat/python/tests gives 1540 passed. The 3 failures (tool-count goldens) fail on main in this environment too. flake8, black and isort are clean.

kovtcharov added a commit to kovtcharov/gaia that referenced this pull request Sep 20, 2026
Both PRs change what happens when the guard stops a turn, so they have to
agree on the order: correct once in place of the repeated call, and only on
the next identical call end the turn — now with the closing answer instead of
the canned notice. The summary stays for the error and refused branches, which
is where its rate-limited / not-permitted / dead-service wording belongs.

The count handed to the closing call is the calls that actually ran, the same
number the summary reports, and the cleanliness check both sides need is one
predicate now instead of two copies.
…al cause

After four identical tool calls the loop guard ended the task and told the user
to "check that the underlying service is running" — even when calls were
throttled and never ran, refused by policy, or a script exited non-zero. In a
168-run benchmark it fired 6 times with no outage behind any of them, and twice
replaced a finished task's answer with a failure message.

- Rate-limited calls never executed, so they no longer count as repeats; the
  loop waits out the reported wait (capped at 15s) before continuing.
- The first time a call hits the limit, the model gets one correction as that
  call's result ("do not repeat it — try a different approach"); only a repeat
  after the correction ends the turn.
- The summary now says rate-limited, not permitted, or the actual failure, and
  only blames a service for connection errors. With no error key it quotes the
  last stderr line.
- The legacy path read step_results, which error recovery clears before every
  retry, so a loop of failures was summarised as "Task completed". It now reads
  previous_outputs like the native path.

Folded in from review:
- read a Windows socket error as a dead service, not a refusal
- read a dead service as a dead service, and count only calls that ran
- read "blocked" as a refusal only when it is one, and reject a repeat limit
  below 2

Fixes amd#3888
@kovtcharov
kovtcharov force-pushed the claude/fix-3888-loop-guard branch from 7110edd to 41b17cf Compare September 21, 2026 11:59
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Rebased onto current main as one commit. First in the turn-ending stack, nothing to merge before it; #4028 builds on this.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Merge this one first — two other open PRs sit on top of it.

#4028 and #4035 both already contain this PR's commit, but all three are marked base: main, so GitHub shows them as independent. Merging either of the others first silently makes this PR redundant without closing it, and squash-merging any of the three rewrites the shared commit and conflicts the other two.

Order: #3908 → #4028 → #4035, as merge commits rather than squashes.

🔍 Technical details

git log origin/main..fork/claude/step-cap-final-answer shows 41b17cf9f (this PR's commit) inside #4028, and git log origin/main..fork/claude/loop-break-answer-from-work shows both 41b17cf9f and 2dc1e47d7/50aa38fb0 (#4028's) inside #4035. The branches merge bottom-up already (triage/3908 → triage/4028 → triage/4035); only the PR base fields are out of step.

The bases can't be retargeted as-is — claude/fix-3888-loop-guard and claude/step-cap-final-answer exist only on the kovtcharov fork, and a PR base must be a branch in amd/gaia.

All three rewrite src/gaia/agents/base/agent.py (184 / 352 / 479 lines), a file 29 other open PRs also touch, so the ordering matters well beyond these three.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 24, 2026
Merged via the queue into amd:main with commit 69fc540 Sep 24, 2026
43 checks passed
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 25, 2026
…md#4373)

When an agent ran out of steps, the user got a canned "Reached maximum
steps limit" note with an empty tool list and no word on what happened.
In a benchmark where GitHub rate-limited every `gh` call, GAIA spent all
30 steps on workarounds and never mentioned the rate limit. Now, at the
step limit, the agent gets one more model call in which it can't use
tools, and answers from what its tool results show: what it found, what
it couldn't finish and why, and what to do next. If that call fails, the
old note comes back with a line saying why.

Replicates amd#4028, which lives on the `kovtcharov/gaia` fork — push
access was revoked mid-review, so that PR could no longer be refreshed
against main and was stuck `CONFLICTING`. Same content, re-resolved
against current main. No content changes beyond the conflict resolution.

## Test plan

- [x] `python -m pytest tests/unit/agents/test_step_cap_final_answer.py
tests/unit/test_claude_provider.py
tests/unit/test_lemonade_tool_choice.py` — 89 passed
- [x] `python -m pytest tests/unit/agents` — 1511 passed, 50 skipped, 0
failed
- [x] Provider-layer selection (`-k "claude or lemonade or provider"`)
diffed against a clean-`main` worktree baseline — identical failure
sets, zero regressions (the 12 remaining are pre-existing macOS/posix
tests failing on a Windows host)
- [x] `python util/lint.py --black --isort --fix` clean, no changes;
`python util/lint.py --flake8` passes
- [ ] `gaia eval agent --category tool_selection` — not run here;
carried over unchecked from amd#4028
- [ ] Live step-capped run on NPU/FLM — the Lemonade half was confirmed
on amd#4028 (a `fireworks.kimi-k2p7-code` run accepted the closing call
with tools + `tool_choice="none"` and answered from its results);
NPU/FLM still unchecked

<details>
<summary>🔍 Technical details</summary>

**Replication method.** amd#4028 was stacked on amd#3908, which main
squash-merged as `69fc540b5`. A plain merge would re-apply amd#3908's fork
commit on top of its own squash, so instead the three commits that are
amd#4028's own work were cherry-picked onto main: `2dc1e47d7`, `50aa38fb0`,
`429de6a48`. amd#3908's fork commit and main's squash were verified
byte-identical before dropping it.

**Only conflict: `src/gaia/llm/providers/claude.py`.** Main changed
`_build_params` to also return a `name_map` (`_to_anthropic_tools` now
returns a tuple); amd#4028 added a `tool_choice` parameter and passed it
through from `chat`. Both kept — the signature takes `tool_choice` and
returns `tuple[dict, Dict[str, str]]`. This is the identical resolution
the author made in `26d80fcfa` on the fork, confirmed by reading that
merge's combined diff; it was the only evil-merge content across all
three of the branch's merge commits, so the replicated tree reproduces
the PR head exactly. Verified by matching symbol counts for
`_STEP_CAP_ANSWER_PROMPT`, `_answer_at_step_cap`, `max_steps_reached`,
`user_stopped` and `tool_choice` against `refs/pull/4028/head`.

**Review findings from amd#4028 are all addressed in the replicated
commits.** The `user_stopped` guard (declining "Continue with 50 more
steps?" no longer fires the wrap-up call) landed in `429de6a48`, and the
Claude structural fix (keep the tools, send `tool_choice="none"`) in
`50aa38fb0`.

- The closing call goes through the loop's own path:
`self.chat.send_messages` or `send_messages_stream`, with the loop's
`messages` plus one user instruction, the same system prompt, the same
tools, and `tool_choice="none"`. Tools stay because Anthropic rejects
tool_use/tool_result history on a request with no tools. A model without
native tool calling sends no tools and no `tool_choice`.
- `tool_choice` is a new explicit parameter on `LemonadeProvider.chat`,
`ClaudeProvider.chat` and `LemonadeClient.chat_completions`. Both raise
if it comes without tools; Claude maps `"none"`/`"auto"` and raises on
anything else.
- `_generate_max_steps_message` looked for OpenAI-style `tool_calls` on
assistant entries, which GAIA's `conversation` never contains, so the
"tools used" list was always empty. It now counts `role: tool` entries.
- The closing call counts as one more step, so the CLI shows "Processing
stopped after 51/50 steps" at the cap. `max_steps_reached` is new on
every result.

**Stacking.** amd#3908 is merged. amd#4035 sits on top of this PR and
generalises the closing call to the loop-guard path (`_closing_answer`);
it will need retargeting onto this branch once this lands.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Co-authored-by: Kalin Ovtcharov <[email protected]>
Co-authored-by: Claude Opus 5 <[email protected]>
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 26, 2026
amd#4373 landed this PR's step-cap half on main (replicating amd#4028), and amd#3908
merged as a squash, so both of this branch's stacked parents are now upstream.
Nine conflicts in agent.py, all in the code the two changes share:

- `_answer_at_step_cap` → `_closing_answer(messages, conversation, instruction,
  step)`. This PR generalises the method so the loop-guard path can reuse it;
  the step-cap call site now passes `_STEP_CAP_ANSWER_PROMPT` as the
  instruction. Same request, same prompt.
- `max_steps_reached` keeps main's `user_stopped` term. That is this PR's own
  first review finding — declining "Continue with 50 more steps?" or pressing
  Ctrl-C must not fire another model call — and amd#4373 fixed it while this
  branch was open.
- Both loop-guard call sites drop main's `_build_loop_break_summary`
  assignment: `_answer_after_repeated_calls` builds that summary itself and
  returns it for repeats that failed or were refused.
- `_build_loop_break_summary` keeps the extracted `_repeats_carry_a_failure`
  predicate over main's inline condition; they are equivalent, and `denied` is
  still used further down.
- `min_context_size`'s docstring takes main's wording, which describes the
  resolver that is now in place.

The closing answer is now printed, not just returned. The normal and step-cap
paths call `print_final_answer` where they set `final_answer`; the loop guard
returned its answer and broke out, so on the CLI — where the console is the
only thing that prints — the turn ended on the repeat warning and the answer
this path exists to produce was never shown. Confirmed by driving a real
loop-guard break: `print_final_answer` was called zero times while the answer
sat in `result["result"]`, which is why every existing test missed it. The
post-loop block mirrors the step-cap one, so the printed text carries its
verification-scope line and the turn record is sealed before it prints.
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 26, 2026
…4035)

An agent that finished a task and then re-ran the same check a few times
used to have its answer thrown away: the user got "I stopped after
calling `run_python` 3 times in a row without making progress, so I
can't confirm the task is finished" on runs where the code had been
changed, documented, and pytest had passed — the verification line on
that same answer said "verified — pytest ran and passed". A judge scored
one of those tasks 3.00 against Claude Code's 4.75, the largest quality
gap left in the suite. The agent now answers from the work it actually
did; repeats that failed or were refused still report the failure,
because there the failure is what the user needs to hear.

Stacked on amd#4028 and amd#3908, merged in that order (main → amd#4028 → amd#3908 →
this), so the diff here includes both until they land. Together the
guard corrects once in place of the repeated call and only ends the turn
on the next identical call — that closing turn is what this PR changes.

## Test plan

- [ ] `python -m pytest tests/unit/agents/test_loop_break_answer.py
tests/unit/agents/test_loop_guard_correction.py
tests/unit/agents/test_step_cap_final_answer.py
tests/unit/agents/test_loop_break_truthful.py -q` — closing answer on
both tool paths after the correction round, error/refused repeats
unchanged, failure and cancel handling
- [ ] `python -m pytest tests/unit/agents -q` (1056 passed locally on
the merged tree)
- [ ] `gaia eval agent --category tool_selection` shows no regression
against the committed baseline — not run here

<details>
<summary>🔍 Technical details</summary>

- The step-limit closing call was generalised to
`_closing_answer(messages, conversation, instruction, step)`; the
step-limit and loop-guard paths differ only in the instruction they
pass. Both loop-guard call sites (native fan-out and legacy
embedded-JSON) go through `_answer_after_repeated_calls`, which returns
`(answer, steps_taken)` and `(None, …)` when the user pressed Stop.
- Merge resolution at both call sites: `if current_call not in
loop_corrected_calls: … continue` first, then
`print_repeated_tool_warning()` followed by
`_answer_after_repeated_calls(...)` with `consecutive_count - 2` — the
calls that actually ran, the same number `_build_loop_break_summary`
reports.
- The gate is `_repeats_carry_a_failure`: an errored or `status:
"denied"` last result keeps `_build_loop_break_summary`, so amd#3908's
rate-limited / not-permitted / dead-service wording is untouched.
`_build_loop_break_summary` now calls that predicate instead of
repeating the condition.
- The guard stops mid-fan-out, which leaves an assistant tool-call turn
with no result for the call it stopped — Anthropic and other spec-strict
providers reject that outright. `_unanswered_tool_call_messages` answers
every dangling id with "Not run — the turn stopped before this call"
before the closing request goes out, and a test asserts the outgoing
message list accounts for every id (the correction message answers its
own id, so only the stopping call needs sealing).
- On failure the behaviour mirrors the step-limit path: warn, and return
the existing notice with one line saying why the summary couldn't be
written. A reply that asks for a tool instead of answering counts as a
failure.
- The extra call counts as a step and its stats land in `conversation`,
so tokens are aggregated as usual. The verification-scope line is still
appended once, post-loop.
- Both call sites pass `recent_results` (from `previous_outputs`), never
`step_results`, which error recovery clears before every retry — a
legacy-path test fails if that is swapped back.
- amd#3908's own `test_repeat_after_the_correction_ends_the_turn` needed no
change: its repeats return an error, which stays on the summary branch.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Co-authored-by: Ovtcharov <[email protected]>
Co-authored-by: probe <probe@local>
Co-authored-by: Kalin Ovtcharov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(agent): the loop guard ends working tasks and blames the service

2 participants