Skip to content

Bug: limitHistoryTurns breaks tool_use/tool_result pairs after sanitization #38370

Closed

Description

@Mani87-nq

Description

When sessions grow large (170K+ tokens), the message windowing code can break tool_use/tool_result pairs, causing the Claude API to reject requests.

Error Message

LLM request rejected: messages.434.content.1: unexpected tool_use_id found in tool_result blocks: toolu_01Vq6m4qpujG9jQqHVSseEBV. Each tool_result block must have a corresponding tool_use block in the previous message.

Root Cause

limitHistoryTurns() runs after sanitizeToolUseResultPairing(), which can break previously-repaired pairs.

Affected Files

  • dist/agents/pi-embedded-runner/compact.js (~line 280)
  • dist/agents/pi-embedded-runner/run/attempt.js (~line 386)

Bug Pattern (both files)

const prior = await sanitizeSessionHistory({...});      // repairs tool pairs
const validatedGemini = validateGeminiTurns(prior);
const validated = validateAnthropicTurns(validatedGemini);
const limited = limitHistoryTurns(validated, ...);      // CAN BREAK PAIRS AGAIN

Why It Breaks

limitHistoryTurns counts user turns from the end and slices at user turn boundaries. If the cut point lands between an assistant message containing tool_use and the following user message with tool_result, the API rejects it.

Proposed Fix

Option A: Quick Fix

Call sanitizeToolUseResultPairing again after limitHistoryTurns:

const limited = limitHistoryTurns(validated, ...);
const repaired = sanitizeToolUseResultPairing(limited);  // ADD THIS

Option B: Proper Fix

Make limitHistoryTurns tool-pair-aware so it never cuts inside a tool transaction (between tool_use and its matching tool_result).

Reproduction

  1. Long session with many tool calls (170K+ tokens, 400+ messages)
  2. Session approaches context limit
  3. limitHistoryTurns trims messages
  4. Cut happens between tool_use (assistant) and tool_result (user)
  5. API rejects

Notes

  • The memoryFlush feature exacerbates this by injecting tool calls at the compaction boundary
  • This affects ANY tool, not just specific ones
  • Workaround: Clear session with /new, but this loses context

Environment

  • Clawdbot version: 2026.1.24-3
  • Model: anthropic/claude-opus-4-5

Activity

  1. added a commit that references this issue on Mar 7, 2026
    e0c8551
  2. openclaw-barnacle commented on Apr 21, 2026

    @openclaw-barnacle

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

  3. added
    stale
    on Apr 21, 2026
  4. steipete commented on Apr 24, 2026

    @steipete
    Contributor

    Closing this as implemented after Codex review.

    Current main already repairs tool/result pairing after limitHistoryTurns in both embedded-runner paths, and the repair helper drops orphaned toolResult messages. The reported failure mode is therefore already implemented/fixed on main, and the same code is present in release v2026.4.22.

    What I checked:

    • Run attempt re-repairs after truncation: limitHistoryTurns(...) is immediately followed by sanitizeToolUseResultPairing(...), with an inline comment calling out orphaned tool_result blocks after truncation. (src/agents/pi-embedded-runner/run/attempt.ts:1615)
    • Compaction path re-repairs after truncation: The compaction flow applies the same post-limitHistoryTurns repair step, again explicitly covering orphaned tool/result pairs. (src/agents/pi-embedded-runner/compact.ts:953)
    • Repair helper drops orphan tool results: repairToolUseResultPairing removes free-floating toolResult messages when they are not directly attached to a matching assistant tool-call turn, which is the exact rejection path from the report. (src/agents/session-transcript-repair.ts:456)
    • Regression coverage for orphan tool results: Tests assert that orphan tool results are dropped when no matching tool call remains. (src/agents/session-transcript-repair.test.ts:126)
    • Release tag contains the fix: The v2026.4.22 tag already contains the post-limitHistoryTurns sanitizeToolUseResultPairing(...) calls in both source paths. (00bd2cf7a376)

    So I’m closing this as already implemented rather than keeping a duplicate issue open.

    Review notes: reviewed against 76a4c167f7ef; fix evidence: release v2026.4.22, commit 00bd2cf7a376.

  5. locked as resolved and limited conversation to collaborators on Apr 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stale

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions