anthropic-sdk-python icon indicating copy to clipboard operation
anthropic-sdk-python copied to clipboard

[Bug] API returns 400 'Invalid signature in thinking block' when replaying conversation history — no recovery path

Open craigderrick opened this issue 6 months ago • 2 comments

Bug Description

When using extended thinking with claude-sonnet-4.x/claude-opus-4.x in a multi-turn conversation, the API begins returning 400: Invalid signatureinthinking block after N turns. Once triggered, every subsequent message in the session fails permanently — there is no recovery without manually stripping thinking blocks from history.

Reproduction

  1. Enable extended thinking on claude-sonnet-4-6 or claude-opus-4
  2. Run a long multi-turn conversation (20+ turns with tool use)
  3. Pass full conversation history on each turn (including type: "thinking" blocks from prior assistant messages)
  4. At some turn, the API begins rejecting with 400: messages.X.content.Y: Invalid signatureinthinking block
  5. The position (X, Y) is consistent — the same thinking block triggers it every time
  6. The session cannot recover — every subsequent call with that history fails

Error

{
  "type": "error",
  "error": {
    "type": "invalid_request_error",
    "message": "messages.27.content.0: Invalid `signature` in `thinking` block"
  }
}

Questions / Issues

  1. What invalidates a signature? The API docs say to pass thinking blocks back unmodified. If signatures expire or become invalidated server-side, clients have no way to know without trying.
  2. No recovery path — the error is a hard 400, not retryable. Clients must strip thinking blocks from history to continue, but the API docs don't describe this scenario or recommend this workaround.
  3. Cascading failure — subagents or forked sessions that inherit the conversation history also fail immediately.

Environment

  • SDK: used via OpenClaw gateway (direct Anthropic REST API)
  • Model: claude-sonnet-4-6
  • Platform: macOS 26.4.1, Node.js 22.x

Related

  • anthropics/claude-code#21726 (session resume fails with same error)
  • anthropics/claude-code#10627

Requested

  1. Document under what conditions a thinking block signature becomes invalid
  2. Provide a recommended recovery path (e.g., strip thinking blocks from history on 400, retry)
  3. Ideally: return a more specific error type so clients can handle it programmatically

craigderrick avatar May 23 '26 23:05 craigderrick

This is exactly the kind of failure mode that's hard to handle gracefully — the API contract ("pass thinking blocks back unmodified") discourages exactly the defensive code that would save you here. The "no recovery path" framing is the killer.

A workaround that's been working for teams hitting similar signature-expiry issues, in case it helps anyone else mid-incident:

Catch + strip pattern

def strip_thinking_blocks(messages: list[dict]) -> list[dict]:
    """Remove all `thinking` content blocks from assistant messages.

    Used to recover from `Invalid signature in thinking block` 400s
    by replaying without prior thinking blocks. Model loses chain-of-thought
    continuity from prior turns but the conversation can continue.
    """
    cleaned = []
    for msg in messages:
        if msg["role"] != "assistant" or not isinstance(msg.get("content"), list):
            cleaned.append(msg)
            continue
        new_content = [c for c in msg["content"] if c.get("type") != "thinking"]
        if new_content:
            cleaned.append({**msg, "content": new_content})
    return cleaned


try:
    response = client.messages.create(model=..., messages=history, thinking={...})
except anthropic.BadRequestError as e:
    if "Invalid `signature` in `thinking` block" in str(e):
        log.warning("thinking-block signature invalidated; stripping history + retrying")
        history = strip_thinking_blocks(history)
        response = client.messages.create(model=..., messages=history, thinking={...})
    else:
        raise

Cost: lose chain-of-thought continuity from prior turns. The model still gets extended thinking for the current turn — just no historical thinking context to draw from.

Open questions that might help root-cause this (Anthropic engineers, would love your read):

  1. Is the signature tied to a server-side cache that has TTL (e.g. eviction)? That would explain why position (X,Y) is reproducible in the OP's repro — same TTL window for that block.
  2. Could there be a request-level flag like thinking_blocks: "strip_invalid_signatures" where the API silently drops invalidated blocks instead of 400'ing the whole call?
  3. Or even a signature_expires_at field on outgoing thinking blocks so clients can preemptively strip before resending?

For anyone hitting this RIGHT NOW: the strip-and-retry pattern is the only recovery I've found referenced. Loses chain-of-thought but at least the conversation doesn't permanently brick.

I track conversation state + error recovery patterns in a streaming starter I've been shipping (YorickLane/claude-streaming-starter) — happy to fold a worked example for this thinking-block recovery into the README if it'd be useful as a reference for others.

XavierZhao1989 avatar May 28 '26 08:05 XavierZhao1989

Hey @craigderrick — sorry for the delay on this. Signatures don't expire; the check fails when a thinking/redacted_thinking block reaching the API differs in any way from what was originally returned (edited or re-serialized thinking/signature text, blocks reordered or merged, or blocks generated by a different model replayed into the conversation). Two questions to narrow it down: does anything between your code and the API rewrite or re-encode message history (a proxy/gateway, a persistence layer that round-trips the blocks through its own schema)? And could you share a request-id from one of the failing 400s, or the raw JSON of the assistant turn at the failing index as you sent it — that would let us check exactly what differed.

dtmeadows-ant avatar Aug 05 '26 14:08 dtmeadows-ant