Repository navigation
fix(agents): end turns after repeated identical tool errors - #167628
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThe 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 {}.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete 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 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe 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
Technical reviewBest 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
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +164, Tests +369, Docs +38. Total +571 across 22 files. Added test files: 2. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (2 earlier review cycles)Reviewed October 9, 2026, 2:31 AM ET / 06:31 UTC (Revision 3). |
|
Merged via squash.
|
…#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
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 ofsessions_yieldwere 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):
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 pluscontinue()). The fix resets the narrow counter in the existingmessage_enduser-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 buildpassed 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:changedreports four pre-existing unused exports/re-exports in untouched baseline files:bindCliQuestionAnswerAuthority,prepareSessionEventTargetForHost,readSessionEntryCreationTransition, andRESTART_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:latestand 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.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.
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=1with 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.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.