Skip to content

fix(core): preserve Anthropic signed thinking across memory replay#17602

Open
Akash504-ai wants to merge 2 commits into
mastra-ai:mainfrom
Akash504-ai:fix/anthropic-thinking-roundtrip
Open

fix(core): preserve Anthropic signed thinking across memory replay#17602
Akash504-ai wants to merge 2 commits into
mastra-ai:mainfrom
Akash504-ai:fix/anthropic-thinking-roundtrip

Conversation

@Akash504-ai

@Akash504-ai Akash504-ai commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

Description

Fixes an issue where Anthropic signed thinking blocks could lose their reasoning text during persistence/replay while retaining the original signature.

When replayed in a multi-turn conversation, Anthropic validates the signature against the original thinking content and rejects modified blocks with:

thinking blocks cannot be modified

This change:

  • Preserves Anthropic signed reasoning text during persistence/replay
  • Rehydrates reasoning text from either reasoning or details for backward compatibility
  • Adds a defensive compatibility rule that strips invalid signed reasoning blocks with empty text before Anthropic replay
  • Adds regression tests covering round-trip persistence and replay behavior

Related issue(s)

Fixes #17457

Type of change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update
  • Code refactoring
  • Performance improvement
  • Test update

Checklist

  • I have linked the related issue(s) in the description above
  • I have made corresponding changes to the documentation (if applicable)
  • I have added tests that prove my fix is effective or that my feature works
  • I have addressed all Coderabbit comments on this PR

ELI5

Imagine you're having a multi-turn conversation with an AI that thinks out loud (shows its reasoning). When you save that conversation and continue it later, the AI's reasoning was being saved with a special seal (signature) but without the actual thoughts. When you tried to replay that conversation, the AI would reject it because the seal didn't match the empty reasoning—like opening a sealed envelope that's supposed to have a letter inside, but finding it empty. This PR fixes it so the thinking and the seal travel together correctly, and also cleans up old conversations that already have this problem.


Changes Overview

This PR addresses issue #17457 where Anthropic signed thinking blocks lost their reasoning text during persistence/replay cycles while retaining their signatures, causing validation failures. The fix ensures that thinking blocks round-trip correctly through memory and handles legacy data that may already be in a broken state.

Core Fix: Preserving Thinking Text

In AIV5Adapter.ts:

  • Added helper functions to detect Anthropic provider signatures and extract reasoning text from either the reasoning field or details fragments
  • Modified fromUIMessage and fromModelMessage methods to preserve thinking text in the reasoning field when an Anthropic signature is present (previously always stored empty strings)
  • Modified toUIMessage to use the new extraction logic for computing text content

In build-messages-from-chunks.ts:

  • Added helper functions to detect Anthropic signatures in provider metadata
  • Updated reasoning-span finalization to populate the reasoning field with aggregated text from details when an Anthropic signature is present

Backwards Compatibility & Defensive Sanitization

In provider-history-compat.ts:

  • Added new compat rule anthropicStripEmptySignedReasoningContent that detects legacy assistant reasoning blocks where the Anthropic signature exists but the text is empty
  • This rule strips invalid reasoning parts from outbound prompts before sending to Anthropic (without modifying stored history), preventing signature validation failures
  • Added to DEFAULT_COMPAT_RULES for automatic application

Testing

New test coverage added:

  • anthropic-thinking-roundtrip.test.ts: Comprehensive test suite validating signed thinking round-trip through adapters and ProviderHistoryCompat
  • build-messages-from-chunks.test.ts: New test asserting Anthropic signed reasoning text is preserved in the primary reasoning field

Changeset

  • Added .changeset/signed-thinking-memory.md documenting the patch release for @mastra/core

@changeset-bot

changeset-bot Bot commented Jun 5, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: a0c1b3e

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 23 packages
Name Type
@mastra/core Patch
mastracode Patch
@mastra/mcp-docs-server Patch
@internal/playground Patch
@mastra/client-js Patch
@mastra/opencode Patch
@mastra/longmemeval Patch
mastra Patch
@mastra/deployer-cloud Patch
@mastra/deployer-vercel Patch
@mastra/playground-ui Patch
@mastra/react Patch
@mastra/server Patch
@mastra/deployer Patch
create-mastra Patch
@mastra/express Patch
@mastra/fastify Patch
@mastra/hono Patch
@mastra/koa Patch
@mastra/nestjs Patch
@mastra/deployer-cloudflare Patch
@mastra/deployer-netlify Patch
@mastra/temporal Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@vercel

vercel Bot commented Jun 5, 2026

Copy link
Copy Markdown

@Akash504-ai is attempting to deploy a commit to the Mastra Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 8645245d-af0c-4f02-9d97-865a44b56da8

📥 Commits

Reviewing files that changed from the base of the PR and between b3e9781 and a0c1b3e.

📒 Files selected for processing (6)
  • .changeset/signed-thinking-memory.md
  • packages/core/src/agent/message-list/adapters/AIV5Adapter.ts
  • packages/core/src/agent/message-list/tests/anthropic-thinking-roundtrip.test.ts
  • packages/core/src/loop/workflows/agentic-execution/build-messages-from-chunks.test.ts
  • packages/core/src/loop/workflows/agentic-execution/build-messages-from-chunks.ts
  • packages/core/src/processors/provider-history-compat.ts

Walkthrough

This PR fixes Anthropic "signed thinking" round-trip behavior in multi-turn conversations backed by Memory. When persisted assistant reasoning blocks are replayed, the thinking text and signature now both restore correctly, and invalid legacy blocks (signature present but empty text) are sanitized before forwarding to Anthropic.

Changes

Anthropic signed thinking replay and sanitization

Layer / File(s) Summary
AIV5 adapter signature-aware reasoning population
packages/core/src/agent/message-list/adapters/AIV5Adapter.ts
AIV5Adapter adds hasAnthropicSignature and getReasoningText helpers to detect Anthropic signatures and extract reasoning text from either the reasoning field or concatenated details. These helpers are used in toUIMessage, fromUIMessage, and fromModelMessage to conditionally populate reasoning only for signed Anthropic paths.
Chunk assembly signed reasoning population
packages/core/src/loop/workflows/agentic-execution/build-messages-from-chunks.ts, packages/core/src/loop/workflows/agentic-execution/build-messages-from-chunks.test.ts
Build-messages-from-chunks adds hasAnthropicSignature and getReasoningDetailText helpers and updates reasoning-end handling to populate the reasoning field when an Anthropic signature is present, with a test validating signed reasoning preservation from streaming chunks.
Provider history compat sanitization for legacy empty signed reasoning
packages/core/src/processors/provider-history-compat.ts
Provider history compat adds metadata inspection helpers and a new anthropicStripEmptySignedReasoningContent rule that removes assistant reasoning parts where Anthropic signature is present but text is empty/missing. The rule is registered in defaults and documented.
Round-trip regression test suite
packages/core/src/agent/message-list/tests/anthropic-thinking-roundtrip.test.ts
New test suite validates that signed thinking reasoning parts are preserved and replayed exactly, remain valid across multi-turn history processing, invalid legacy signed reasoning is suppressed, and non-Anthropic (Gemini) metadata is unaffected.
Release notes
.changeset/signed-thinking-memory.md
Changeset documents the fix to restore thinking text and signature from memory on replay, and sanitize legacy history to prevent invalid/empty signed-thinking blocks.

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

tests: green ✅

Suggested reviewers

  • TylerBarnes
  • abhiaiyer91
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 9.09% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is fully related to the main change: it clearly describes the core fix of preserving Anthropic signed thinking during memory replay.
Linked Issues check ✅ Passed The PR implementation aligns with all key objectives from issue #17457: persisting reasoning text with signatures, defensive stripping of invalid blocks, and comprehensive test coverage.
Out of Scope Changes check ✅ Passed All changes are directly related to fixing the Anthropic signed thinking round-trip issue; no unrelated modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@dane-ai-mastra

dane-ai-mastra Bot commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

PR triage

Linked issue check passed (#17457).

Mastra uses CodeRabbit for automated code reviews. Please address all feedback from CodeRabbit by either making changes to your PR or leaving a comment explaining why you disagree with the feedback. Since CodeRabbit is an AI, it may occasionally provide incorrect feedback.


PR complexity score

Factor Value Score impact
Files changed 6 +12
Lines changed 252 +15
Author merged PRs 11 -11
Test files changed Yes -10
Final score 6

Applied label: complexity: low


Changed test gate

Changed Test Gate is pending. The Changed Test Gate / changed-tests check will update the test label when it completes.

@dane-ai-mastra dane-ai-mastra Bot added the complexity: low Low-complexity PR label Jun 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

complexity: low Low-complexity PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Opus 4.8 + adaptive thinking: replayed thinking blocks lose text but keep signature → 400 "thinking blocks cannot be modified" on multi-turn

1 participant