Skip to content

fix(agents): continue a malformed tool call after a consumed tool failure - #170846

Open
akushonkamen wants to merge 4 commits into
openclaw:mainfrom
akushonkamen:fix/170522-settled-tool-error-continuation
Open

akushonkamen wants to merge 4 commits into
openclaw:mainfrom
akushonkamen:fix/170522-settled-tool-error-continuation

Conversation

@akushonkamen

@akushonkamen akushonkamen commented Oct 13, 2026 •

Copy link
Copy Markdown

Root cause: src/agents/embedded-agent-runner/run/incomplete-turn-recovery.ts:465 treats a retained tool error as consumed only when executionStarted === false (and :484 also requires a not_started receipt on every failure), so a tool that ran and returned an error keeps vetoing the single continuation for a later tool call rejected before dispatch, although the model already read that failure.

Fixes #199537

Thanks @jaxonparrott for the production report and source trace, and @akushonkamen for the original fix.

What Problem This Solves

A tool runs and returns an error, the model reads it and makes its next tool call, and that call streams malformed JSON arguments. The call is rejected before it runs, and the turn ends with "couldn't finish this reply" instead of getting the one continuation every other rejected call gets. In the reported cron run this threw away 13.5 minutes and 4.7M tokens.

User Impact

The turn continues once and the model can re-issue its call or answer. Completed tools are not repeated. Failures the model has not seen (no result yet, a result after the rejected response, a prior turn, or a different tool), unfinished or asynchronous work, and the one-continuation budget still block, as before.

Why This Change Was Made

The continuation replays nothing: the rejected call never ran, and the earlier failure already sits in the transcript before the rejected response. Whether that failed tool had started does not change what the continuation does, so the started/not-started split only blocked recovery. The retained error now counts as consumed when its failed result is the latest failure in the current turn, precedes the rejected response, and names the retained tool.

This keeps @akushonkamen's commits and reconciles them with the transcript check main gained in #170615: the settled-batch exemption from the original commit is superseded by that check, and the executed-failure cases join the existing rejected-call test table. docs/concepts/agent-loop.md describes the new boundary. No new model-facing text. Production lines: +5/-14.

Evidence

Isolated Gateway from source (ocx src) on main vs this branch, local Anthropic Messages fixture: an edit call that runs and returns an error, then a write call with truncated JSON arguments.

  • Chat turn: main ends "Your request couldn't be completed." with no continuation request; this branch sends one continuation and the model answers. The failed edit is not repeated.
  • Scheduled run (with fix: scheduled runs stop on a malformed tool call #201117, which removes the separate optional-reply suppression): main ends status=error; with both fixes the run ends status=ok after one continuation.
  • A model that keeps sending malformed calls: one continuation ("retrying 1/1"), then the turn fails as before.
  • Controls with a successful tool before the malformed call: unchanged.
  • Regressions continues after consumed tool failures (started | unknown | earlier started) fail on main and pass here; the negative table (missing, unconsumed, prior-turn, different tool, active, async) still passes.

Proof log: #170846 (comment)

Merge danger: two-way door; a revert restores the started-failure veto. No config, schema or state change. Blast radius: turns whose last model response was a tool call rejected before dispatch after an earlier tool error in the same turn.

… tool failure

When the provider streams a tool call with malformed arguments after an
earlier tool in the same turn failed, the bounded rejected-call
continuation was still skipped and the turn ended with 'Agent run
failed'. shouldSkipNonVisibleTurnRetry vetoed on attempt.lastToolError
regardless of the rejectedBeforeDispatch tolerance, and recordSuccess
clears lastToolError only when the same tool name succeeds, so an
exec preflight refusal followed by a malformed second call dropped the
turn even though the failed result was already in the transcript and
the rejected call never ran.

resolveEmptyResponseRetryInstruction now proves provenance through
resolveSettledToolBatchEvidence: when the rejected call never
dispatched and the retained error is a failed result the model already
saw in a proven-settled batch (its name matches the batch's failed
results, or a fully settled successful batch proves the error is stale
from an earlier tool), the lastToolError veto alone is relaxed. Every
other skip guard stays fail-closed: unfinished work, async activity,
unattributed errors and replay-unsafe attempts still block, and the
continuation stays bounded to one.

Fixes openclaw#170522.
@clawsweeper

clawsweeper Bot commented Oct 13, 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.

@chatgpt-codex-connector

Copy link
Copy Markdown
Contributor

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Oct 13, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 13, 2026
@clawsweeper

clawsweeper Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: ready, awaiting a maintainer decision.

What this changes

Allows one malformed-call continuation after an earlier failed tool result has already reached the model, regardless of whether that tool started.

Example: An edit tool returns an error, then the model sends truncated JSON for a write call.

  • Before: The retained edit failure blocks continuation and the turn ends with an error.
  • After: The model gets one continuation from the existing transcript and can finish without repeating the edit.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Strong Gateway proof and a small coherent repair support correctness; acceptance of the expanded recovery policy remains an owner decision, and exact-head CI is not complete.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): Exact-head isolated Gateway logs exercise the production runner and real Anthropic transport against injected malformed arguments after an executed edit failure, showing successful chat and cron continuation, no repeated edit, unchanged successful-tool controls, and bounded persistent failure.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Complete
User problem: An agent abandons a progressing task after malformed tool arguments even though it has already consumed the preceding tool failure.
Reason: The repair has concrete user value and focused proof, but intentionally expands an owner-built, documented recovery boundary.

Merge readiness

⏳ Ready, awaiting maintainer decision

Keep this PR open: it repairs a demonstrated recovery gap with no concrete patch defect found, but broadens an intentionally restricted policy and still lacks a successful exact-head CI gate.

Priority: P2
Reviewed head: d00cf7aaede50ea5172c6d270f82fc17fef8ebb8
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should the malformed-call continuation admit consumed executed or unknown-start failures, replacing the deliberate no-start-only boundary from fix(agents): continue malformed calls after an earlier tool refusal #170615?
  • Recommendation: Accept consumed settled failures: Approve this narrow expansion because continuation uses the recorded transcript and does not replay the failed action.
  • Why: The production report and Gateway proof support the expansion, but the previous owner-authored implementation, tests, and documentation intentionally excluded these failures; collaborator repair and verification do not explicitly record acceptance of that broader policy.

Before merge

None.

Findings

None.

Agent review details

How this fits together

The embedded agent runner consumes provider responses, transcript ordering, and tool lifecycle facts to choose between bounded continuation and terminal completion.

flowchart TD
  A[Chat or scheduled turn] --> B[Provider response]
  B --> C[Tool execution and results]
  C --> D[Transcript and lifecycle facts]
  B --> E[Recovery eligibility]
  D --> E
  E --> F[One continuation or terminal result]
Loading

Technical review

Best possible solution:

Accept the transcript-based exception in the existing recovery owner while preserving failure records, lifecycle guards, and the single-continuation budget.

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

Current-main source deterministically blocks executed failures, and the supplied base-versus-head Gateway traces demonstrate that exact sequence; this read-only review ran no target code.

Is this the best way to solve the issue?

The smallest complete fix removes the execution-start distinction and receipt restriction from the existing consumed-failure check, retaining transcript attribution and bounded continuation without adding another owner.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 9d6f4a94adf5.

Provenance checked

  • Consumed-failure recovery eligibility and documentation changes intended behavior with a stated reason (e6ea3cf: Allow recovery after consumed refusals only when every failed result carries private evidence that execution never started, preventing a later refusal from masking an earlier uncertain failure.)
  • Malformed-call continuation and retry budget keeps the original intent (c5fcae2: Continue from the transcript after a rejected call without replaying completed tools, while bounding persistent malformed output.)
  • Scheduled-run rejection classification keeps the original intent (93ec0fe: Treat rejected-before-dispatch calls as provider errors rather than optional authored silence.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Eric Curtin: Raw commit 93ec0fe adds src/agents/embedded-agent-runner/run/incomplete-turn-recovery.ts:446 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 93ec0fe3567f; files: src/agents/embedded-agent-runner/run/incomplete-turn-recovery.ts)

PR surface

Source -13, Tests +11, Docs +1. Total -1 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 5 18 -13
Tests 1 26 15 +11
Docs 1 6 5 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 37 38 -1

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: A specific provider-error sequence interrupts otherwise progressing chat and scheduled tasks, with limited scope and no demonstrated urgent regression.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on maintainer: Only explicit maintainer approvals or decisions remain; merge is still blocked.
  • 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 execution lanes are retired.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-13T08:51:47.407Z sha 8f0aa81 :: needs real behavior proof before merge. :: none

Reviewed November 18, 2026, 7:26 AM ET / 12:26 UTC (Revision 2).

@jaxonparrott

Copy link
Copy Markdown
Contributor

Production proof for this gap, filed as #199537. On 2026.10.10, an MCP tool ran and returned isError: true, the model's next call streamed malformed JSON (malformed_tool_call_arguments, rejected before dispatch), and no continuation followed: the narrower executionStarted === false exemption doesn't cover a tool that actually ran. The v2026.11.3 source still has the same guard.

# Conflicts:
#	src/agents/embedded-agent-runner/run/incomplete-turn-recovery.ts
- A retained tool error no longer vetoes the single rejected-call continuation once its failed result precedes the rejected response in the current turn, whether or not the failed tool had started.
- Reconciles openclaw#170846 with the transcript check now on main; the settled-batch exemption it added is superseded.
- Folds the executed-failure cases into the existing rejected-call table and drops the duplicate block.
# Conflicts:
#	src/agents/embedded-agent-runner/run/incomplete-turn-recovery.ts
@obviyus

obviyus commented Nov 18, 2026

Copy link
Copy Markdown
Collaborator

Gateway proof for this head (d00cf7a) against main 93ec0fe (which already includes #201117): isolated Gateway from source, local Anthropic Messages fixture. An edit tool call runs and returns an error, then the next call has truncated JSON arguments (rejected before dispatch, malformed_tool_call_arguments).

FINAL HEAD d00cf7aaede5 (bugloop-170846 = 8f0aa81c18 + 562183e fix + merge of origin/main 93ec0fe, which contains #201117). Base: main 93ec0fe3567f (ocx base merge-base --src). Runs: runs/base-final, runs/cand-final.
  chat SCEN_ERR      base: toolResult(isError) then "Your request couldn't be completed.", no continuation request | cand: one continuation, assistant(stop) "RECOVERED SCEN_ERR", edit not repeated
  cron SCEN_ERR      base: status=error "⚠️ OpenClaw couldn't finish this reply.", no continuation request | cand: status=ok summary="RECOVERED SCEN_ERR", one continuation
  cron SCEN_ERRPERSIST base: status=error, no continuation | cand: "empty response detected ... retrying 1/1" once, then 3 empty-error-retry resubmits, then status=error (budget holds at one)
  chat SCEN_OK (control) base and cand: one continuation, "RECOVERED SCEN_OK" (unchanged)
  Gateway log "empty response detected": base 1 (chat SCEN_OK only); cand 4 (chat SCEN_ERR, chat SCEN_OK, cron SCEN_ERR, cron SCEN_ERRPERSIST), one per run.
  Focused tests on d00cf7a: rejected-tool-call + terminal-resolution + incomplete-turn-recovery + cron message-tool-policy: 101 passed (3 shards). oxlint core (incl. terminal-resolution.ts, no exceptions) and oxfmt clean. ocx build --dts: success (pueue 17057).

Provider request log, this head:

=== chat-SCEN_ERR
  assistant(stop): RECOVERED SCEN_ERR
  provider: 2026-11-18T12:19:55.008Z lane=chat SCEN_ERR first:edit continuations_in_history=0
  provider: 2026-11-18T12:19:55.139Z lane=chat SCEN_ERR after-tool(is_error=true):malformed continuations_in_history=0
  provider: 2026-11-18T12:19:55.315Z lane=chat SCEN_ERR continuation:final-answer continuations_in_history=1
=== cron-SCEN_ERR
  cron run: status=ok error=null summary="RECOVERED SCEN_ERR"
  provider: 2026-11-18T12:20:00.725Z lane=cron SCEN_ERR first:edit continuations_in_history=0
  provider: 2026-11-18T12:20:00.886Z lane=cron SCEN_ERR after-tool(is_error=true):malformed continuations_in_history=0
  provider: 2026-11-18T12:20:01.049Z lane=cron SCEN_ERR continuation:final-answer continuations_in_history=1
=== cron-SCEN_ERRPERSIST
  cron run: status=error error="⚠️ OpenClaw couldn't finish this reply."
  provider: 2026-11-18T12:20:07.389Z lane=cron SCEN_ERRPERSIST first:edit continuations_in_history=0
  provider: 2026-11-18T12:20:07.416Z lane=cron SCEN_ERRPERSIST after-tool(is_error=true):malformed continuations_in_history=0
  provider: 2026-11-18T12:20:07.508Z lane=cron SCEN_ERRPERSIST continuation:malformed-again continuations_in_history=1
  provider: 2026-11-18T12:20:07.611Z lane=cron SCEN_ERRPERSIST continuation:malformed-again continuations_in_history=2
  provider: 2026-11-18T12:20:07.702Z lane=cron SCEN_ERRPERSIST continuation:malformed-again continuations_in_history=3
  provider: 2026-11-18T12:20:07.789Z lane=cron SCEN_ERRPERSIST continuation:malformed-again continuations_in_history=4
=== chat-SCEN_OK
  assistant(stop): RECOVERED SCEN_OK
  provider: 2026-11-18T12:20:13.382Z lane=chat SCEN_OK first:write continuations_in_history=0
  provider: 2026-11-18T12:20:13.431Z lane=chat SCEN_OK after-tool(is_error=false):malformed continuations_in_history=0
  provider: 2026-11-18T12:20:13.508Z lane=chat SCEN_OK continuation:final-answer continuations_in_history=1

@obviyus obviyus changed the title fix(agents): continue a malformed tool call after a settled same-turn tool failure fix(agents): continue a malformed tool call after a consumed tool failure Nov 18, 2026
@openclaw-barnacle openclaw-barnacle Bot added the docs Improvements or additions to documentation label Nov 18, 2026
@obviyus

obviyus commented Nov 18, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Nov 18, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale after 7 days without qualifying human activity.
Without new human activity, Barnacle may close it as not planned 7 days after this message was posted. This is administrative inactivity cleanup, not a claim that the problem is fixed.
A human update restarts the inactivity clock; a new PR head also restarts it. A maintainer can add no-stale for a durable hold, or bad-barnacle to suppress Barnacle. Remove the hold when work can resume.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Nov 25, 2026

This branch has not been deployed

No deployments
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 P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S stale Marked as stale due to inactivity status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Malformed tool call is not continued when the previous tool ran and returned an error (executionStarted: true)

3 participants