Repository navigation
Description
Summary
Orphaned tool_use blocks (without matching tool_result) cause permanent session corruption. Once corrupted, every subsequent interaction fails with the same error, creating an infinite failure loop that silently burns tokens until a human manually runs /new.
Related to #33621 (compaction root cause) and #44473 (infinite loop). This issue provides large-scale production data and proposes a concrete auto-recovery mechanism.
Production Impact (Real Data)
Over 11 days (March 5–16, 2026), we observed:
| Metric | Value |
|---|---|
| Unique corruption events | 10 |
| Total failed retries | 164 |
| Worst single day (3/9) | 113 failures from 1 corrupted session |
| Affected agents | main + lasercat (multi-agent setup) |
| Tool types corrupted | exec, process, read, message, cron |
| Time to human detection | Hours to days |
Corruption Events
| Date | Failures | Corrupted tool_use ID | Type |
|---|---|---|---|
| 3/5–3/6 | 13 | message1772734859015242 | message |
| 3/6 | 3 | cron1772760242370387 | cron |
| 3/6 | 4 | exec17728006830743 | exec |
| 3/9 | 117 | exec1773056336198292 | exec |
| 3/9 | 2 | exec1773050538494257 | exec |
| 3/10 | 17 | exec177316403392084 | exec |
| 3/10 | 2 | exec1773198623679279 | exec |
| 3/11–3/12 | 4 | read177329349052866 | read |
| 3/12 | 1 | exec1773308974430250 | exec |
| 3/16 | 2 | process17736695423061694 | process |
Root Cause
When a tool call is initiated but the tool_result is never written back to the session (timeout / abort / process crash / API overload), the session .jsonl ends up with an unpaired tool_use block. The existing repairToolUseResultPairing() does not catch:
- Content-block level mismatches within messages (noted in Bug: Anthropic rejects history with dangling tool_use blocks after compaction #33621)
- Compaction that strips
tool_resultbut preservestool_use - Mid-execution crashes where
tool_resultwas never generated
Proposed Fix (Two-Layer)
Layer 1: Prevention — Improve validateAnthropicTurns()
As proposed in #33621, add stripDanglingAnthropicToolUses() to remove orphaned tool_use blocks before sending to the API.
Layer 2: Recovery — Auto-detect and self-heal
When the same tool_use ID causes repeated failures (≥3 consecutive), the gateway should:
- Detect: Pattern-match the error to extract the orphaned tool_use ID
- Repair: Inject a synthetic
tool_resultwith an error message, or strip the orphaned block - Log: Record the auto-repair event
- Alert: Optionally notify the user
This mirrors how databases handle WAL corruption — detect, repair, continue.
Layer 3: Reference Monitoring Script
We built a user-side monitoring script that scans gateway.err.log and auto-resets corrupted sessions. Happy to contribute as reference implementation.
Error Pattern (for detection)
LLM request rejected: messages.N: \`tool_use\` ids were found without \`tool_result\` blocks immediately after: <TOOL_ID>
Same <TOOL_ID> appearing repeatedly = session is permanently stuck. Needs reset or repair, not retry.
Environment
- OpenClaw: latest (npm)
- OS: macOS (Apple Silicon, Darwin 25.2.0)
- Provider: Anthropic (Claude Opus 4 / Sonnet 4)
- Setup: Multi-agent (main + lasercat), 30+ active cron jobs
- Session mode: Persistent long-running sessions with compaction
Workaround
Manual /new to reset the session. We also built an external monitoring script that auto-detects and resets corrupted sessions.
Metadata
Metadata
Assignees
Labels
Type
Fields
Priority
Activity
Ryce commentedon Mar 16, 2026
Hollychou924 commentedon Mar 16, 2026
100yenadmin commentedon Mar 17, 2026
Audit Findings + Upstream Cross-Reference (evaOS incident 2026-03-16)
We hit this in production — 164 tool_use failures, orphaned blocks causing infinite retry loops after Opus timeouts. Ran a full red/blue audit against
dist/auth-profiles-DDVivXkv.js.Root Cause Chain
tool_useblockstripDanglingAnthropicToolUses()should catch this but is a no-op — see Bug: stripDanglingAnthropicToolUses checks wrong type ("toolUse" vs "toolCall") and empty assistant messages stored on LLM failure cause session corruption with thinking blocks #41571 / PR fix: check "toolCall" instead of "toolUse" in stripDanglingAnthropicToolUses (closes #41571) #46866block.type !== "toolUse"(line 40300) but pi-agent-core stores blocks astype: "toolCall""toolCall" !== "toolUse"is always true → filter keeps every block → nothing strippedtool_use→ Anthropic rejects → retry → same broken state → infinite loopTwo Required Fixes
Fix 1 — PR #46866 (prerequisite): Change
"toolUse"→"toolCall"instripDanglingAnthropicToolUses. Without this, the function is dead code. Note: the function also has a blind spot — only checksassistant[i] → user[i+1]pairs, misses end-of-conversation orphans (the last assistant message with no following user message). PR #45393 addresses this.Fix 2 —
repairToolUseResultPairinghardening: This function at line ~99265 usesextractToolCallsFromAssistant()which checksTOOL_CALL_TYPESSet (includes both"toolCall"and"toolUse"), so it actually works. But it skips messages withstopReason === "error" || "aborted"— exactly the messages most likely to have orphaned tool calls. Stripping tool_use blocks from error/aborted messages prevents the retry loop.Blast Radius (verified)
validateAnthropicTurns→ Anthropic-only path. No cross-provider impact.sanitizeToolUseResultPairing→ called from Anthropic, Google, and compaction paths. All callers benefit.Related PRs
toolUse→toolCalltype fix (3 reviews, stalled)We have a dist-level patch validated by an Opus red/blue audit at 92% confidence. Happy to share patch details if maintainers want to cross-reference.
steipete commentedon Apr 25, 2026
Closing this as implemented after Codex review.
Current
mainalready repairs orphaned tool-call/result transcript corruption before provider dispatch and strips dangling Anthropic tool-use blocks during validation, with regression coverage for the failure shapes described here.What I checked:
repairToolUseResultPairing()moves matching tool results next to the assistant tool-call turn, inserts synthetic missing results, and drops duplicate/orphan tool results, which directly addresses corrupted sessions poisoning later requests. (src/agents/session-transcript-repair.ts:416, b45329334965)sanitizeToolUseResultPairing(..., { erroredAssistantResultPolicy: "drop" })before stripping tool-result details and before Anthropic validation, so persisted corrupted transcripts are repaired on read/replay. (src/agents/pi-embedded-runner/replay-history.ts:489, b45329334965)stripDanglingAnthropicToolUses()scans ahead for matching tool results before the next assistant turn and removes unresolved tool-call blocks while preserving safe fallback text/empty aborted turns. (src/agents/pi-embedded-helpers/turns.ts:172, b45329334965)sanitizeToolUseResultPairing(), and then re-appliesvalidateAnthropicTurns(), covering another path where orphaned pairs could previously survive. (src/agents/pi-embedded-runner/run/attempt.tool-call-normalization.ts:841, b45329334965)tool_useblocks, preserving valid pairs, fallback text for tool-only turns, aborted/error behavior, and synthetic repair of missing tool results. (src/agents/pi-embedded-helpers.validate-turns.test.ts:377, b45329334965)So I’m closing this as already implemented rather than keeping a duplicate issue open.
Review notes: reviewed against b45329334965; fix evidence: commit b45329334965.