Context compaction breaks tool_use/tool_result pairing causing API errors

Resolved 💬 3 comments Opened Dec 18, 2025 by adambkovacs Closed Feb 14, 2026

Bug Description

During automatic context compaction in long sessions, Claude Code sometimes removes a tool_use block while keeping its corresponding tool_result block. This breaks the required API pairing and causes the conversation to become corrupted.

Error Message

API Error: 400 {"type":"error","error":{"type":"invalid_request_error","message":"messages.44.content.1: unexpected `tool_use_id` found in `tool_result` blocks: toolu_01KczKp1RFJ7iagyYRDGUPYS. Each `tool_result` block must have a corresponding `tool_use` block in the previous message."}}

Steps to Reproduce

  1. Start a Claude Code session
  2. Perform many tool calls (100+ over an extended session)
  3. Context compaction triggers automatically when context size grows
  4. API error occurs when the compacted conversation contains orphaned tool_result blocks

Expected Behavior

Context compaction should treat tool_use and tool_result blocks as atomic pairs:

  • Either keep both blocks together
  • Or remove both blocks together
  • Never orphan a tool_result without its corresponding tool_use

Actual Behavior

The compaction algorithm sometimes removes the tool_use block but keeps the tool_result, creating an invalid conversation structure that the API rejects.

Impact

  • Session becomes unusable and must be restarted
  • User loses conversation context
  • No way to recover the session without starting fresh

Environment

  • Claude Code CLI
  • macOS (Darwin 25.1.0)
  • Long sessions with many tool calls

Workarounds

Currently, the only workaround is to:

  1. Start a new session (/clear or restart)
  2. Use memory persistence systems to preserve state between sessions
  3. Keep sessions shorter to avoid triggering compaction

Suggested Fix

Modify the context compaction algorithm to:

  1. Identify all tool_use/tool_result pairs by tool_use_id
  2. Treat each pair as an atomic unit during summarization decisions
  3. If space constraints require removal, remove the entire pair, not just one half

---
Reported via Claude Code session

View original on GitHub ↗

This issue has 3 comments on GitHub. Read the full discussion on GitHub ↗