Skip to content

Session corruption: 164 failures from orphaned tool_use blocks — need auto-recovery + repair in validateAnthropicTurns #48354

Closed

Description

@mike2024-dev

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:

  1. Content-block level mismatches within messages (noted in Bug: Anthropic rejects history with dangling tool_use blocks after compaction #33621)
  2. Compaction that strips tool_result but preserves tool_use
  3. Mid-execution crashes where tool_result was 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:

  1. Detect: Pattern-match the error to extract the orphaned tool_use ID
  2. Repair: Inject a synthetic tool_result with an error message, or strip the orphaned block
  3. Log: Record the auto-repair event
  4. 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.

/cc #33621 #44473 #42607

Activity

  1. Ryce commented on Mar 16, 2026

    @Ryce
  2. Hollychou924 commented on Mar 16, 2026

    @Hollychou924
  3. 100yenadmin commented on Mar 17, 2026

    @100yenadmin
    Contributor

    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

    1. Opus times out mid-tool-call → session has orphaned tool_use block
    2. stripDanglingAnthropicToolUses() 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) #46866
    3. Function checks block.type !== "toolUse" (line 40300) but pi-agent-core stores blocks as type: "toolCall"
    4. "toolCall" !== "toolUse" is always true → filter keeps every block → nothing stripped
    5. Next API call sends orphaned tool_use → Anthropic rejects → retry → same broken state → infinite loop

    Two Required Fixes

    Fix 1 — PR #46866 (prerequisite): Change "toolUse" → "toolCall" in stripDanglingAnthropicToolUses. Without this, the function is dead code. Note: the function also has a blind spot — only checks assistant[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 — repairToolUseResultPairing hardening: This function at line ~99265 uses extractToolCallsFromAssistant() which checks TOOL_CALL_TYPES Set (includes both "toolCall" and "toolUse"), so it actually works. But it skips messages with stopReason === "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)

    • Fix 1: Only reachable via validateAnthropicTurns → Anthropic-only path. No cross-provider impact.
    • Fix 2: Reachable via sanitizeToolUseResultPairing → called from Anthropic, Google, and compaction paths. All callers benefit.

    Related PRs

    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.

  4. steipete commented on Apr 25, 2026

    @steipete
    Contributor

    Closing this as implemented after Codex review.

    Current main already 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:

    • Transcript auto-repair now inserts/moves/drops tool results: 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)
    • Replay path applies repair before provider calls: The embedded runner replay sanitizer calls 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)
    • Anthropic validation strips dangling tool-use blocks: 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)
    • Stream normalization also re-runs repair and validation: The stream wrapper sanitizes malformed tool calls, re-runs sanitizeToolUseResultPairing(), and then re-applies validateAnthropicTurns(), covering another path where orphaned pairs could previously survive. (src/agents/pi-embedded-runner/run/attempt.tool-call-normalization.ts:841, b45329334965)
    • Regression tests cover dangling-tool and repair cases: Tests now cover stripping dangling tool_use blocks, 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.

  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

    No labels
    No labels

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions