Skip to content

fix(agents): end turns after repeated identical tool errors - #167628

Merged
steipete merged 4 commits into
mainfrom
fix/ollama-repeated-tool-error-guard
Oct 9, 2026
Merged

steipete merged 4 commits into
mainfrom
fix/ollama-repeated-tool-error-guard

Conversation

@steipete

@steipete steipete commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Related: #141743

What Problem This Solves

Repeated identical tool errors can keep a turn running until its deadline when rolling loop detection is disabled. Loop-policy vetoes also reset the dedicated unknown-tool streak. A queued user turn could inherit two earlier failures and terminate on its first matching failure.

User Impact

Three consecutive failures with the same tool, arguments, and error result now end the turn with a recorded error and guidance to check the arguments or switch to a model with native tool calling. This guard remains active with tools.loopDetection.enabled: false; the existing rolling and post-compaction defaults remain unchanged. Changed errors, arguments, successful calls, and progress-making polling reset the streak. Fresh user input—including active follow-ups, queued continuation, and steering—resets the streak at message commit; retries without new input preserve it.

Already-running parallel work settles before the failure is recorded. Unstarted calls are blocked. This adds no configuration keys, dependencies, schemas, or permission changes.

Remaining limitation: the original Llama prompt did not reproduce the longer stochastic loop in these samples. Llama still gave incorrect answers after one or two failed calls, below this guard's threshold. That answer-quality issue remains a follow-up.

Why This Change Was Made

The initial failure plus two retries provides a small recovery allowance without allowing an identical error loop to run indefinitely. The shared detection owner retains canonical argument/result hashes; agent-core observes settled outcomes in model call order and uses its existing intervention and terminal-message lifecycle. A typed terminal code preserves safe recovery text and prevents the retry layer from restarting the failed turn. The existing outcome finalizer was extracted into a sibling module to keep the controller within its size ratchet.

Unknown-tool evidence now survives own vetoes, including unrelated projected siblings, and Unknown tool id: identifies the requested tool correctly. Unavailable yielding guidance and direct visibility of sessions_yield were already fixed upstream in 6353412. Cancellation persistence already belongs to the session lifecycle owner; revoked attempt writers remain fenced. Reopen tests confirm that aborted runs remain recorded.

Production: +290/-126 lines (net +164). Tests: +387/-18 (net +369). The latest review corrections add five net production lines. The added production code preserves ordered settlement, bounded run state, and terminal classification; nearby cleanup and finalizer extraction do not eliminate that necessary growth.

Evidence

New-head Gateway/Ollama proof — 0c7c3eb: the bounded Qwen3:4B probe was rerun once through the real CLI, Gateway, and native Ollama transport. It exited 1 after 42.73s. The model emitted nine calls in one parallel batch: seven unknown-tool failures, one argument-validation failure, and one successful directory listing. After the success, calls 5–7 were three consecutive identical failures. Their full arguments, content, and error details were compared and were identical. All already-started work settled before the terminal error; no further model response ran.

Redacted excerpt of the decisive consecutive failures (timestamps and catalog suggestions omitted; numbering follows the stored assistant's call order):

call 5: tool_call {"id":"loopguard_missing_probe","args":{}}
        Unknown tool id: loopguard_missing_probe.
call 6: tool_call {"id":"loopguard_missing_probe","args":{}}
        Unknown tool id: loopguard_missing_probe.
call 7: tool_call {"id":"loopguard_missing_probe","args":{}}
        Unknown tool id: loopguard_missing_probe.

Final persisted assistant:

{
  "stopReason": "error",
  "errorCode": "openclaw_repeated_tool_error",
  "errorMessage": "OpenClaw stopped this turn after 3 consecutive identical tool failures. Check the tool arguments or switch to a model with native tool calling before retrying."
}

After clean Gateway shutdown, a new SQLite connection reloaded the same session and terminal assistant:

{
  "status": "failed",
  "abortedLastRun": false,
  "lastRunError": "OpenClaw stopped this turn after 3 consecutive identical tool failures. Check the tool arguments or switch to a model with native tool calling before retrying."
}

The earlier c7ae3d5 probe also recorded a reloadable failure after a five-call parallel batch (25.04s). These are live model proofs, separate from the deterministic queue regressions below.

Validation:

  • ClawSweeper's queued-input P2 was reproduced on c7ae3d5: all four new regressions failed (active follow-up, queued follow-up plus continue(), mid-run steering, and queued steering plus continue()). The fix resets the narrow counter in the existing message_end user-message reducer. prompt() retains only its existing critical-loop budget reset; continuation without committed user input keeps the error streak.

  • Independent review found a second real P2: an earlier nonterminal streamed batch could mask the terminating batch's intervention. The old combiner failed the new completion-order regression. It now carries the terminating batch's intervention, preserving its error code and recovery text.

  • Final focused proof: 86 tests across five files passed in 26.20s. Core and affected test typechecks, touched-file lint, formatting, and the line-cap check passed. The four queue regressions failed before the reset fix (10.27s); the batch-identity regression failed before its fix (2.94s).

  • Deterministic regressions failed before the owner fixes: a fourth provider request accepted a literal tool-error answer; blocked records erased unknown-tool evidence; the error renderer removed recovery guidance; and the retry adapter did not recognize the terminal outcome.

  • 298 tests across nine focused files passed in 739.60s wall time, covering guard composition, polling/retry controls, prompt-surface gating, and durable cancellation after reopening SQLite. Scheduling/admission/wait proof passed 95 tests in 569.71s, and detection/bridge proof passed 56 in 226.27s. Compiler preparation and imports dominate these times.

  • Review found one changing-error false positive in the unknown-tool signature. Its new regression failed, then all 16 guard cases passed in 44.19s after retaining the full error hash. Focused lint and core typechecking passed after that correction.

  • Final-head pnpm build passed in 367.44s. The UI build emits a soft startup gzip-budget warning (365.2 versus 364.7 KiB); this PR does not change UI source.

  • Codex branch review: scoped-clean through P2 at 0c7c3eb, after both review corrections.

  • Prompt snapshots regenerated: zero changed bytes, 0-token delta.

  • Core and all 27 test type graphs passed. Touched-file lint and all remaining selected guards passed.

Aggregate gate qualification: check:changed reports four pre-existing unused exports/re-exports in untouched baseline files: bindCliQuestionAnswerAuthority, prepareSessionEventTargetForHost, readSessionEntryCreationTransition, and RESTART_CONTINUATION_CONTEXT_PREFIX. Their declarations and references were checked at baseline 98eb575. No exemption was added; the remaining selected checks were run individually and passed. CI timings are pending; this lane does not wait for CI or merge.

All live samples and commands

The real Gateway used isolated state/workspace, port 19141, and Ollama's native transport at localhost:11434. Fresh non-interactive onboarding selected ollama/llama3.2:latest and left loop detection unset. Baseline: 98eb575. Original after comparison: c7ae3d5. The additional new-head diagnostic uses 0c7c3eb. Each sample used a fresh session key. Times include CLI startup and shared-host contention.

Side Model Sample Tool failures CLI seconds Recorded outcome / visible response
Before llama3.2:latest 1 1 50.42 done / stop; XML-wrapped answer
Before llama3.2:latest 2 1 31.18 done / stop; tool-search instruction
Before llama3.2:latest 3 1 41.01 done / stop; invalid-tool apology
Before qwen3:4b 1 0 45.39 done / stop; exactly live-turn-ok
Before qwen3:4b 2 0 45.74 done / stop; exactly live-turn-ok
Before qwen3:4b 3 0 36.70 done / stop; exactly live-turn-ok
After llama3.2:latest 1 1 17.97 done / stop; tool-search instruction
After llama3.2:latest 2 2 7.02 done / stop; invalid-tool explanation
After llama3.2:latest 3 1 4.93 done / stop; invalid-tool apology
After qwen3:4b 1 0 17.59 done / stop; exactly live-turn-ok
After qwen3:4b 2 0 8.62 done / stop; exactly live-turn-ok
After qwen3:4b 3 0 11.51 done / stop; exactly live-turn-ok
Earlier diagnostic (c7ae3d5) qwen3:4b 1 5, one parallel batch 25.04 failed / error; actionable recovery message
New-head diagnostic (0c7c3eb) qwen3:4b 1 8 errors from 9 parallel calls 42.73 failed / error; code and failed state retained after shutdown/reload

An earlier baseline CLI attempt hit Gateway startup before a model ran (21.35s, connection refused); it was replaced by the third completed Llama sample. The first after-Gateway launch encountered a default service lifecycle lock timeout. The documented named profile isolated the service identity while retaining the same explicit state, config, workspace, model settings, and port. No operator service was stopped or changed. The task Gateway was stopped after verification.

export OPENCLAW_STATE_DIR=/private/tmp/oc-lm-loopguard/state
export OPENCLAW_CONFIG_PATH=/private/tmp/oc-lm-loopguard/state/openclaw.json
export TMPDIR=/private/tmp/oc-lm-loopguard/tmp

pnpm openclaw onboard --non-interactive --accept-risk --auth-choice ollama \
  --gateway-port 19141 --gateway-bind loopback \
  --workspace /private/tmp/oc-lm-loopguard/workspace \
  --skip-daemon --skip-health --skip-channels --skip-skills --skip-search \
  --skip-ui --suppress-gateway-token-output

# Baseline Gateway and agent commands omitted --profile; after used the named profile.
pnpm openclaw --profile loopguard gateway run --port 19141 --bind loopback
pnpm openclaw --profile loopguard agent --session-key agent:main:after-llama3.2-1 \
  -m "Reply with exactly: live-turn-ok" --model ollama/llama3.2:latest --timeout 90 --json
# Repeat three times per model, using ollama/qwen3:4b for the controls.

pnpm openclaw --profile loopguard agent --session-key agent:main:queued-head-error-probe \
  -m 'This is a bounded error-handling test in an isolated workspace. Sequentially call tool_call with id "loopguard_missing_probe" and args {} five times. After each error, retry exactly the same call without discovery or changing arguments. Do not finish early.' \
  --model ollama/qwen3:4b --timeout 180 --json

The ordinary CLI processes had a 140s external bound; the diagnostic had a 230s bound. No sample reached it. The model batched the diagnostic calls despite the sequential request; deterministic regressions separately prove that sequential execution stops after three failures.

Focused test cost

All test invocations used node scripts/run-vitest.mjs <files> --maxWorkers=1 with the short task TMPDIR. New/changed test execution was well below five seconds per file; startup/import/compiler time is included in the command wall times above.

New/changed file Test execution
tool-loop-recovery.errors.test.ts 45 ms in the final grouped run; 20-case queue-fix suite passed
tool-loop-detection.test.ts 584 ms
error-text.test.ts 109 ms
retry.test.ts 308 ms
tool-loop-recovery.test.ts 2.145 s
tool-loop-admission.test.ts 0.281 s
tool-batch-completion.test.ts three completion-order/recovery cases; final focused run above

An initial test-bootstrap attempt overlapped setup-generated plugin assets and failed before executing tests. It was rerun after setup completed. No production workaround or test suppression was added.

@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: L labels Oct 9, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 9, 2026
@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

The branch ends embedded agent turns after three consecutive identical tool failures, preserves failure evidence across loop vetoes, and records actionable recovery guidance.

Example: The model repeatedly calls tool_call with id loopguard_missing_probe and args {}.

  • Before: With rolling loop detection disabled, identical unknown-tool failures can continue until the turn deadline.
  • After: Three consecutive identical failures end the turn with openclaw_repeated_tool_error and guidance to check arguments or switch models.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The useful patch has direct runtime proof, focused regression coverage, and no remaining review findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The exact-head real CLI/Gateway/native Ollama probe exercises the changed outcome observer and terminal controller: three identical failures produce the dedicated error, active parallel work settles, no further model response runs, and reopening SQLite retains the failed outcome. Existing serialized fields remain compatible without migration.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: An agent can keep repeating the same failed tool request until its deadline instead of ending with a recorded, understandable failure.
Reason: The change delivers bounded recorded failure for the linked report's repeated-identical-error scenario. Prior merged area maintenance establishes owner direction for the narrow always-on guard.

Merge readiness

✅ Ready for maintainer review

This PR remains useful and is ready from the reviewed code and behavior evidence. The previous queued-input finding is resolved, and no remaining actionable defect was found.

Priority: P2
Reviewed head: 0c7c3eb7154ac6bae9053c4fc6c5d56e02edcde9

Before merge

None.

Findings

None.

Agent review details

How this fits together

The embedded agent runtime turns model tool requests into executed actions and feeds their results back to the model. Its loop controller now uses settled failure outcomes to end stuck turns and publish a recorded error.

flowchart TD
  A[Model tool requests] --> B[Tool admission and execution]
  B --> C[Settled results in model call order]
  C --> D{Three identical failures?}
  D -->|No| E[Continue model turn]
  D -->|Yes| F[Settle active work and block unstarted calls]
  F --> G[Recorded error and recovery guidance]
  H[Committed user input] --> C
Loading

Technical review

Best possible solution:

Keep failure classification in the shared detector and termination in the existing agent-loop owner, preserving fresh-input resets and durable recovery guidance.

Do we have a high-confidence way to reproduce the issue?

Yes: current-main source leaves the default repeated-error path without this bound, and supplied deterministic regressions isolate it. The original stochastic Llama hang was not reproduced during this read-only review.

Is this the best way to solve the issue?

Yes: the patch reuses the existing detector, batch lifecycle, and terminal-error owners rather than enabling broader rolling detection or adding configuration.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 18cade08699b.

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Introduced changes and clean checkout: Reviewed the pinned merge-base-to-head changes; git diff --check passed and the checkout remained clean. No builds or tests were executed during this read-only review. (0c7c3eb7154a)
  • Prior finding resolved: Committed user messages now clear the repeated-error counter. Four regression cases cover active and queued follow-ups and steering; continuation without new input retains the counter. (packages/agent-core/src/agent.ts:727, 0c7c3eb7154a)
  • Ordered termination and terminal identity: Settled outcomes are observed in assistant order after active work settles. The batch combiner retains the terminating batch's intervention, allowing the loop to record the dedicated error code and safe recovery text. (packages/agent-core/src/tool-batch-completion.ts:19, 0c7c3eb7154a)
  • Current-head real behavior proof: The full PR body was retrieved, including the previously omitted ending. Its real CLI/Gateway/native Ollama probe records three identical loopguard_missing_probe failures after a successful call, no further model response, and a persisted openclaw_repeated_tool_error outcome. A new SQLite connection after shutdown reloads status failed and the recovery message. The original stochastic Llama loop was not reproduced in these samples. Captured body identity: SHA-256 85663b3d54c51a3236ed7233e461e0e6aa400d018154e37cdd4d625e01361932. (0c7c3eb7154a)
  • Still necessary on current main: Current main still disables the embedded batch bridge unless rolling detection is enabled and lacks the dedicated terminal error classification. The touched production and documentation files have no main changes since the merge base. (src/agents/embedded-agent-runner/run/tool-loop-recovery.ts:17, 18cade08699b)
  • Existing owner direction: The PR author also appears in substantial prior merged maintenance of detection, recovery, and failure rendering, including fix(agents): surface bucketed tool-loop warnings #135103 and refactor(agents): consolidate failover classification into one substrate #121341. This PR explicitly chooses a three-failure guard that remains active with enabled: false while preserving rolling-detector defaults; that owner-authored direction covers the intentional compatibility tradeoff. (src/agents/tool-loop-detection.ts, 18cade08699b)

Likely related people:

  • Onur Solmaz: Raw commit 1f10ef8 adds src/agents/embedded-agent-runner/run/tool-loop-recovery.ts:8 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 1f10ef8050a9; files: src/agents/embedded-agent-runner/run/tool-loop-recovery.ts)

PR surface

Source +164, Tests +369, Docs +38. Total +571 across 22 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 12 290 126 +164
Tests 7 387 18 +369
Docs 3 47 9 +38
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 22 724 153 +571

Review metrics

Metric Value Why it matters
Production versus tests production +290/-126; tests +387/-18 Production growth supports ordered outcome settlement and terminal classification while extracting the existing finalizer.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #141743
Summary: This PR is the candidate repair for the linked report's repeated-identical-error termination path.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

  • add merge-risk: 🚨 compatibility: Identical failures now terminate even with rolling detection explicitly disabled; this intentional behavior change is documented in the area-owner-authored PR.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove merge-risk: 🚨 session-state: Current PR review merge-risk labels are merge-risk: 🚨 compatibility.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: This is a focused reliability improvement for repeated failing embedded tool calls.
  • merge-risk: 🚨 compatibility: Identical failures now terminate even with rolling detection explicitly disabled; this intentional behavior change is documented in the area-owner-authored PR.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only; repair and merge need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (2 earlier review cycles)
  • reviewed 2026-10-09T05:31:08.129Z sha c7ae3d5 :: needs changes before merge. :: [P2] Reset the error streak when a queued user turn starts
  • reviewed 2026-10-09T05:38:12.594Z sha c7ae3d5 :: needs changes before merge. :: [P2] Reset the error streak when a queued user turn starts

Reviewed October 9, 2026, 2:31 AM ET / 06:31 UTC (Revision 3).

@steipete
steipete marked this pull request as ready for review October 9, 2026 05:32
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Oct 9, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 9, 2026
@steipete steipete self-assigned this Oct 9, 2026
@steipete
steipete merged commit d860aa6 into main Oct 9, 2026
135 of 137 checks passed
@steipete
steipete deleted the fix/ollama-repeated-tool-error-guard branch October 9, 2026 06:49
@steipete

steipete commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 10, 2026
…#167628)

* fix(agents): stop repeated identical tool errors by default

* fix(agents): retain full error identity in the default loop guard

* fix(agents): reset tool error streaks when user input commits

* fix(agents): preserve the terminating tool-loop intervention
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant