Skip to content

fix(agents): re-run tool_use/tool_result pairing repair after late me… - #37671

Closed
tonyzorin wants to merge 1 commit into
openclaw:mainfrom
tonyzorin:fix/repair-tool-pairing-after-late-mutations
Closed

tonyzorin wants to merge 1 commit into
openclaw:mainfrom
tonyzorin:fix/repair-tool-pairing-after-late-mutations

Conversation

@tonyzorin

@tonyzorin tonyzorin commented Mar 6, 2026 •

Copy link
Copy Markdown

Summary

Describe the problem and fix in 2–5 bullets:

  • Problem: After the initial sanitizeToolUseResultPairing() call at session setup (~line 1333 in attempt.ts), several operations mutate activeSession.messages via replaceMessages() without re-running the pairing repair: orphaned user-message removal and history image pruning (pruneProcessedHistoryImages).
  • Why it matters: If any of these late mutations orphans a tool_use block (one without a matching tool_result in the next message), the corrupted transcript is sent to the Anthropic API which rejects it with invalid_request_error. The error is then persisted in the session transcript, permanently breaking the session — every subsequent request fails with the same error.
  • What changed: Added a final sanitizeToolUseResultPairing() pass after all late-stage message mutations and before the prompt is sent to the LLM.
  • What did NOT change (scope boundary): No changes to the repair logic itself, no new dependencies, no config changes.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

User-visible / Behavior Changes

None. The change is a defensive no-op when tool_use/tool_result pairing is already correct (returns the same array reference). Users affected by the bug will no longer have their sessions permanently broken.

Security Impact (required)

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? No
  • New/changed network calls? No
  • Command/tool execution surface changed? No
  • Data access scope changed? No

Repro + Verification

Environment

  • OS: Debian 12 (bookworm)
  • Runtime/container: Node v22.22.0
  • Model/provider: Anthropic Claude
  • Integration/channel (if any): Gateway direct (CLI/WebChat)
  • Relevant config (redacted): Default gateway config with Anthropic provider

Steps

  1. Run a long gateway session (300+ messages) with Anthropic provider
  2. Session goes through compaction cycles
  3. A tool_use/tool_result pair gets orphaned during late-stage message manipulation (orphan removal or image pruning)
  4. Every subsequent request fails with: messages.N: tool_use ids were found without tool_result blocks immediately after: <id>
  5. Session becomes permanently broken — only manual session reset recovers it

Expected

Session continues working normally after compaction/pruning.

Actual

Session is permanently broken with invalid_request_error on every request.

Evidence

  • Patched the compiled dist/pi-embedded-CtM2Mrrj.js on a live gateway (v2026.3.2) and confirmed the fix resolved the issue for a session that had been broken for 2 days.
  • Full pnpm build && pnpm check && pnpm test pass on the source: 829 test files, 6823 tests, 0 failures.

Human Verification (required)

What you personally verified (not just CI), and how:

  • Verified scenarios: Applied the fix as a dist patch to a live gateway instance; a previously permanently broken session (300+ messages, call_68354307 orphan) resumed working immediately.
  • Edge cases checked: Verified the fix is a no-op when pairing is already correct (same array reference returned, no unnecessary replaceMessages call).
  • What you did not verify: Could not reproduce the exact orphaning trigger on demand — the bug is a race/sequence condition during compaction of very long sessions.

Compatibility / Migration

  • Backward compatible? Yes
  • Config/env changes? No
  • Migration needed? No

Failure Recovery (if this breaks)

  • How to disable/revert this change quickly: Revert this single commit. The added code is entirely additive — removing it restores the previous behavior.
  • Files/config to restore: src/agents/pi-embedded-runner/run/attempt.ts
  • Known bad symptoms reviewers should watch for: Unexpected replaceMessages calls (would show as log entries if verbose logging is enabled).

Risks and Mitigations

  • Risk: The extra sanitizeToolUseResultPairing() call adds a small amount of processing per run.
    • Mitigation: The function is O(n) on message count and returns immediately (same reference) when no repairs are needed. Cost is negligible compared to the LLM API call.

AI-assisted. Tested on a live gateway (v2026.3.2) by patching the compiled dist files. The fix resolved the immediate issue for a session that had been permanently broken for 2 days.

…ssage mutations

After the initial sanitizeToolUseResultPairing() call during session setup,
several operations mutate activeSession.messages without re-running the
pairing repair (orphan user-message removal, history image pruning).

If any of these steps orphans a tool_use block, the corrupted transcript is
sent to the Anthropic API which rejects it permanently, breaking the session.

Add a final sanitizeToolUseResultPairing() pass after all late-stage message
mutations and before the prompt is sent to the LLM.
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XS labels Mar 6, 2026
@tonyzorin
tonyzorin marked this pull request as draft March 6, 2026 11:03
@greptile-apps

greptile-apps Bot commented Mar 6, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds a final sanitizeToolUseResultPairing() pass immediately after all late-stage message mutations (orphaned user-message removal and history image pruning) and before the transcript is sent to the LLM API, preventing corrupted tool_use/tool_result sequences from reaching the Anthropic API and causing permanent session breakage.

  • The fix is correctly placed inside the existing try block, after both pruneProcessedHistoryImages (lines 1592–1598) and the orphan user-message removal (lines 1576–1590), and before detectAndLoadPromptImages (which does not mutate activeSession.messages).
  • The reference-equality guard (repaired !== activeSession.messages) is sound: sanitizeToolUseResultPairing explicitly returns the original reference when no changes are needed, so the guard correctly avoids an unnecessary replaceMessages call.
  • The transcriptPolicy.repairToolUseResultPairing flag check is consistent with every other call-site in the same file.
  • The underlying helper function is already well-tested in session-transcript-repair.test.ts.

Confidence Score: 4/5

  • This PR is safe to merge; the change is small, targeted, and logically sound with no risk of regressions to the happy path.
  • The fix is a single, well-scoped guard that mirrors an existing pattern used earlier in the same function. It calls an already well-tested helper (sanitizeToolUseResultPairing) in a new location to handle a specific mutation-ordering bug. The guard uses safe reference-equality checks to avoid unnecessary replaceMessages calls. The only limitation is the absence of a focused integration test for this specific mutation-ordering scenario, but this is not a blocker given the underlying helper's test coverage.
  • No files require special attention.

Last reviewed commit: 4629b79

@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

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

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #pr-thunderdome-dangerzone on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling size: XS stale Marked as stale due to inactivity

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant