Skip to content

fix(embedded-agent): recover thinking-signature rejection delivered a… - #94649

Closed
itsuzef wants to merge 1 commit into
openclaw:mainfrom
itsuzef:fix/anthropic-thinking-terminal-result-recovery
Closed

itsuzef wants to merge 1 commit into
openclaw:mainfrom
itsuzef:fix/anthropic-thinking-terminal-result-recovery

Conversation

@itsuzef

@itsuzef itsuzef commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Problem

A session can wedge and stop responding after an Anthropic invalid-thinking-signature error: every subsequent turn 400s on replay (replay_invalid) and never recovers until the gateway is manually restarted. The failing turn produces no visible output — the model call is rejected before anything streams.

Root cause

wrapAnthropicStreamWithRecovery already recovers an invalid-thinking-signature 400 when it arrives as an in-stream error event or as a thrown rejection — it retries once without thinking blocks and repairs the session.

But the same 400 can surface a third way: as a terminal result message. The stream resolves normally and result() returns an AssistantMessage with stopReason: "error" and an errorMessage carrying the invalid_request_error ("Invalid signature in thinking block"). No error event is emitted and nothing is thrown, so neither existing recovery branch fires and the wrapper returns the error result unchanged.

Because the latest-turn exemption in stripInvalidThinkingSignatures intentionally lets a corrupted latest thinking block flow through to this recovery path, a session that hits this carrier 400s on every replay and stays wedged.

Fix

Handle the terminal-result carrier in pumpStreamWithRecovery, the same way as the existing error-event branch: after result() resolves, if the turn produced no output and the result is a recoverable Anthropic thinking error, mark recoveredAnthropicThinking, log a [session-recovery] warning, and retry once without thinking blocks (retryStreamWithoutThinking).

  • Guarded by !yieldedOutput: a signature 400 is rejected before any content streams, so the branch only fires for a turn that produced no visible output — a turn that already streamed content is untouched.
  • Gated by the existing shouldRecoverAnthropicThinkingError(result, sessionMeta) predicate, so only invalid-thinking-signature errors trigger recovery; any other terminal error is returned unchanged.
  • Scoped to thinking.ts; no change to the streaming/error-event paths or to stripInvalidThinkingSignatures.

This is a narrow recovery-carrier follow-up within the open Anthropic invalid-thinking-signature cluster (canonical: #92201). It closes the terminal-result gap left by the error-event / raw-error recovery in #92916 and the durable transcript repair in #92286; it is not the create-side / replay-policy fix tracked by the canonical issue.

Testing

Adds a regression test in thinking.test.ts: "recovers a thinking-signature rejection delivered as a terminal result message". The provider 400 is delivered only via result() (stopReason: "error" + errorMessage) with no chunks streamed first. It asserts the wrapper retries once (callCount === 2), notifies recovery exactly once (onRecoveredAnthropicThinking), starts the retry context with the thinking block stripped (keeps the visible text), and resolves to the recovered final message. Reverting the fix makes the test fail — the error result is returned and the session wedges.

Real behavior proof

  • Behavior or issue addressed: An Anthropic invalid-thinking-signature error delivered as a terminal result (stopReason: error, no streamed content) previously left the session wedged — every replay re-hit replay_invalid and the turn produced no output until a manual gateway restart. After the fix, the recovery path strips the rejected thinking blocks and retries the turn once, and the session continues on its own.
  • Real environment tested: Live OpenClaw gateway on macOS (Apple Silicon, Node 24.14.1), provider Anthropic, model claude-opus-4-8, WhatsApp channel, sessionKey=agent:main:main. The running build is VE-816, an independent implementation of the same terminal-result-carrier recovery this PR adds (detect the recoverable thinking-signature error on a no-output terminal result → strip thinking blocks → retry once). It is a separate build, so the recovery log wording differs — see "What was not tested".
  • Exact steps or command run after this patch: Normal production traffic continued to encounter the provider Invalid signatureinthinking block rejection on real inbound turns; inspected the gateway's structured runtime logs with openclaw logs (file /tmp/openclaw/openclaw-2026-06-19.log) and cross-checked the self-hosted Langfuse trace store.
  • Evidence after fix: Redacted runtime logs captured via openclaw logs (phone numbers and message bodies removed; request_id is already runtime-hashed):
    2026-06-19T16:29:27.892Z embedded_run_agent_end runId=17b3656e… isError=true model=claude-opus-4-8 provider=anthropic providerRuntimeFailureKind=replay_invalid rawErrorPreview={"type":"error","error":{"type":"invalid_request_error","message":"messages.15.content.0: Invalid `signature` in `thinking` block"},"request_id":"sha256:2b0afdf2fea9"}
    2026-06-19T16:29:27.999Z [session-recovery] stripped thinking blocks after provider rejected replay: repaired=22 sessionKey=agent:main:main
    2026-06-19T16:29:28.024Z [session-recovery] repaired rejected thinking replay; retrying turn attempt=1/1 sessionKey=agent:main:main
    
    Three independent organic occurrences on 2026-06-19 (16:29Z repaired=22, 18:00Z repaired=32, 23:41Z repaired=69), each immediately followed by a successful reply on the same turn. Corroborated in Langfuse: the failing GENERATION carried stopReason: error with the invalid_request_error, and a clean retry GENERATION ran ~3.4s later in the same trace.
  • Observed result after fix: The wedge cleared automatically — after the strip-and-retry the model call succeeded and the session continued normally for ~3.5 hours with no manual restart. Contrast the same setup on the days before this recovery was deployed (2026-06-17 and 2026-06-18): the identical signature error recurred in 4× retry storms at a fixed message position (17, 24, and 12 rejected generations across three sessions) with zero [session-recovery] lines, and each wedged turn ended with empty assistant output.
  • What was not tested: The literal head build of this PR branch was not the running binary — the captured behavior comes from VE-816, an independent implementation of the same terminal-result recovery path (its log strings read stripped thinking blocks / repaired rejected thinking replay rather than this branch's phrasing). No synthetic or forced reproduction was used; every capture is an organic production occurrence.

…s a terminal result

stripInvalidThinkingSignatures intentionally exempts the latest assistant turn (providers reject a modified latest thinking block), expecting a corrupted latest block to flow through stream recovery instead. But when the provider rejects the replayed signature, the 400 can surface as a resolved result message (stopReason "error" + errorMessage) rather than an in-stream error event or a thrown rejection. pumpStreamWithRecovery only handled the error-event and throw carriers, so recovery never fired and the session was rejected on every replay until a manual restart.

Recover this carrier too: when the terminal result is a recoverable thinking error and no content has streamed, retry once without thinking blocks and notify, so the persisted transcript is repaired. Adds a regression test for the result-message carrier.
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. size: S labels Jun 18, 2026
@clawsweeper

clawsweeper Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed June 22, 2026, 12:38 AM ET / 04:38 UTC.

Summary
The PR adds a no-output terminal-result recovery branch for Anthropic invalid thinking-signature results and a focused regression test for one stripped-thinking retry.

PR surface: Source +21, Tests +68. Total +89 across 2 files.

Reproducibility: yes. at source level: current main drains the stream, awaits result(), and returns a recoverable terminal error assistant result unchanged. The PR adds a regression that resolves the first stream only through stream.end(errorResult) with no chunks and verifies a stripped-thinking retry.

Review metrics: 1 noteworthy metric.

  • Recovery Carrier Surface: 1 terminal-result carrier added. This carrier can now trigger stripped-thinking retry and durable session repair from a result shape current main returns unchanged.

Root-cause cluster
Relationship: partial_overlap
Canonical: #92201
Summary: This PR is a narrow terminal-result recovery-carrier follow-up inside the open Anthropic thinking-signature replay cluster, not the canonical issue or the full replay/create-side fix.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🐚 platinum hermit
Patch quality: 🦞 diamond lobster
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Maintainers should decide whether VE-816 same-behavior logs are enough exact-head proof for this session-state recovery path.

Risk before merge

  • [P1] Successful recovery through this new carrier can invoke the existing transcript repair hook and strip thinking blocks from persisted session history after a provider rejection and successful retry.
  • [P1] The real behavior proof is from VE-816, an independent same-behavior implementation with different log wording, not this exact PR head.
  • [P1] Merging this PR should not close the broader Anthropic thinking-signature investigation or replace adjacent review of the async-stream and completed-turn replay PRs.

Maintainer options:

  1. Accept the carrier mitigation (recommended)
    Maintainers can accept the regression test plus redacted VE-816 logs as enough proof that no-output terminal thinking-signature results should trigger the existing one-shot stripped-thinking retry and repair hook.
  2. Require exact-head proof
    Maintainers can require redacted logs or live output from this exact PR head before merge if same-behavior VE-816 proof is not enough for this session-state path.
  3. Coordinate recovery PR order
    Maintainers can pause until they choose merge order with the async-stream and completed-turn replay PRs in the same recovery cluster.

Next step before merge

  • [P2] The remaining action is maintainer review of the session-state repair tradeoff, VE-816 proof equivalence, and adjacent Anthropic recovery PR ordering rather than an automated repair.

Security
Cleared: No concrete security or supply-chain concern was found in this internal TypeScript recovery-and-test diff.

Review details

Best possible solution:

Merge this narrow terminal-result carrier fix after maintainers accept the session-state repair tradeoff and VE-816 proof equivalence, while keeping the broader Anthropic replay cluster open.

Do we have a high-confidence way to reproduce the issue?

Yes at source level: current main drains the stream, awaits result(), and returns a recoverable terminal error assistant result unchanged. The PR adds a regression that resolves the first stream only through stream.end(errorResult) with no chunks and verifies a stripped-thinking retry.

Is this the best way to solve the issue?

Yes for the terminal-result carrier: the existing recovery wrapper already owns one-shot Anthropic thinking replay recovery for stream-error and thrown-error carriers, so checking the no-output terminal result there is the narrowest maintainable fix. It is not the full solution for the broader Anthropic thinking-signature create/replay cluster.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against a594d2ce7325.

Label changes

Label justifications:

  • P1: The PR targets an embedded-agent Anthropic recovery failure that can wedge active sessions until operator intervention.
  • merge-risk: 🚨 session-state: The diff expands a recovery path that can strip thinking blocks and rewrite persisted session transcript state after a successful retry.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): The PR body provides redacted runtime logs showing after-fix terminal-result recovery and continued operation in a real OpenClaw/Anthropic setup, with the caveat that the running build was VE-816 rather than this exact head.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides redacted runtime logs showing after-fix terminal-result recovery and continued operation in a real OpenClaw/Anthropic setup, with the caveat that the running build was VE-816 rather than this exact head.
Evidence reviewed

PR surface:

Source +21, Tests +68. Total +89 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 21 0 +21
Tests 1 68 0 +68
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 89 0 +89

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs src/agents/embedded-agent-runner/thinking.test.ts.
  • [P1] Review current CI for the exact head SHA before merge.

What I checked:

Likely related people:

  • mmyzwl: Authored the merged genericized Anthropic thinking-error recovery work in the same wrapper and adjacent tests. (role: recent recovery contributor; confidence: high; commits: fbc3fa387637; files: src/agents/embedded-agent-runner/thinking.ts, src/agents/embedded-agent-runner/thinking.test.ts)
  • joshavant: Authored the merged durable rejected-thinking replay repair that runs after successful stripped-thinking recovery. (role: adjacent replay-repair contributor; confidence: high; commits: 652e616a297c; files: src/agents/embedded-agent-runner/thinking-replay-repair.ts, src/agents/embedded-agent-runner/run/attempt.ts, src/agents/embedded-agent-runner/thinking.ts)
  • Vincent Koc: Current shallow blame in this checkout carries the affected recovery wrapper and attempt wiring on current main, though feature-specific history points more strongly to the recovery PR authors. (role: recent area contributor; confidence: medium; commits: 095a44c8de4; files: src/agents/embedded-agent-runner/thinking.ts, src/agents/embedded-agent-runner/run/attempt.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. labels Jun 18, 2026
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. label Jun 19, 2026
@openclaw-barnacle openclaw-barnacle Bot added triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. and removed triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Jun 19, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. P1 High-priority user-facing bug, regression, or broken workflow. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. labels Jun 20, 2026
@vincentkoc vincentkoc self-assigned this Jun 23, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jul 16, 2026
@clawsweeper

clawsweeper Bot commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper status: review started.

I am starting a fresh review of this pull request: fix(embedded-agent): recover thinking-signature rejection delivered a… This is item 1/1 in the current shard. Shard 1/4.

This placeholder means the worker is alive and reading the current context. I will edit this same comment with the actual review when the claws are done clicking.

Crustacean status: shell secured, claws on keyboard, evidence pebbles being sorted.

@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #clawtributors on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S stale Marked as stale due to inactivity status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants