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
- Start a Claude Code session
- Perform many tool calls (100+ over an extended session)
- Context compaction triggers automatically when context size grows
- API error occurs when the compacted conversation contains orphaned
tool_resultblocks
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_resultwithout its correspondingtool_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:
- Start a new session (
/clearor restart) - Use memory persistence systems to preserve state between sessions
- Keep sessions shorter to avoid triggering compaction
Suggested Fix
Modify the context compaction algorithm to:
- Identify all
tool_use/tool_resultpairs bytool_use_id - Treat each pair as an atomic unit during summarization decisions
- If space constraints require removal, remove the entire pair, not just one half
---
Reported via Claude Code session
This issue has 3 comments on GitHub. Read the full discussion on GitHub ↗