Skip to content

fix(core): restore state signals without thread scans#18182

Merged
TylerBarnes merged 2 commits into
mainfrom
fix/core-state-signal-history-restore
Jun 18, 2026
Merged

fix(core): restore state signals without thread scans#18182
TylerBarnes merged 2 commits into
mainfrom
fix/core-state-signal-history-restore

Conversation

@TylerBarnes

@TylerBarnes TylerBarnes commented Jun 18, 2026

Copy link
Copy Markdown
Member

This fixes long-thread state signal restore by loading tracked signal messages directly by id instead of scanning thread history.

Before:

await memoryStore.listMessages({
  threadId,
  resourceId,
  perPage: false,
});

After:

await memoryStore.listMessagesById({ messageIds: trackedSignalIds });

If tracked ids or id-based lookup are unavailable, we now fall back to local in-memory state instead of doing an unbounded thread scan.

Verified with:
pnpm --filter ./packages/core test -- src/processors/runner.test.ts --bail 1 --reporter=dot
pnpm --filter ./packages/core check

ELI5

Imagine you have a very long list of messages and need to find a few specific ones. The old way was to look through every single message in the list one by one until you found what you needed. The new way is much smarter: it says "give me these specific messages by their ID" instead, skipping all the others. This makes it much faster when threads get really long.

Overview

This PR improves the performance of state signal restoration in long-running threads by eliminating expensive full-thread message scans. Instead of iterating through all messages in a thread's history, the system now uses a targeted ID-based lookup to fetch only the tracked signal messages it needs.

Changes

Core Logic Update (packages/core/src/agent/state-signals.ts)

  • Modified resolveStateSignalHistory to collect tracked signal message IDs from tracking.activeCopies and tracking.lastSnapshotSignalId upfront
  • Replaced memoryStore.listMessages({ threadId, resourceId, perPage: false }) (full thread scan) with memoryStore.listMessagesById({ messageIds }) (targeted lookup)
  • Removed the resourceId parameter from the function signature since it's no longer needed for the more efficient ID-based lookup
  • Graceful degradation: if listMessagesById is unavailable or tracking yields no IDs, the function returns the local in-memory state without attempting expensive fallbacks

Caller Update (packages/core/src/processors/runner.ts)

  • Removed the now-unnecessary resourceId argument from the resolveStateSignalHistory call

Test Updates (packages/core/src/processors/runner.test.ts)

  • Updated mock to provide both listMessages and listMessagesById methods
  • Changed test expectations to verify that only listMessagesById is called (with the specific message IDs) and listMessages is not called

Impact

This optimization prevents performance degradation as thread histories grow longer, especially in long-running conversation scenarios where state signals need to be restored. The changes were verified against existing test suites in the core package.

TylerBarnes and others added 2 commits June 18, 2026 15:40
Avoid scanning entire long thread histories when state signal tracking already has the message ids needed to restore active copies.

Co-Authored-By: Mastra Code (openai/gpt-5.5) <noreply@mastra.ai>
Remove the legacy full-thread fallback from state signal history restoration so missing tracked ids degrade to local state instead of scanning every message.

Co-Authored-By: Mastra Code (openai/gpt-5.5) <noreply@mastra.ai>
@vercel

vercel Bot commented Jun 18, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
mastra-playground-ui Ready Ready Preview, Comment Jun 18, 2026 11:04pm
1 Skipped Deployment
Project Deployment Actions Updated (UTC)
mastra-docs-1.x Skipped Skipped Jun 18, 2026 11:04pm

Request Review

@changeset-bot

changeset-bot Bot commented Jun 18, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: a343a76

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

@coderabbitai

coderabbitai Bot commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

resolveStateSignalHistory removes resourceId from its parameter type and replaces the listMessages full-thread scan with a targeted listMessagesById call, using IDs built from tracking.activeCopies and tracking.lastSnapshotSignalId. The runner call site drops resourceId, tests are updated to assert the new call pattern, and a patch changeset entry is added.

Changes

State Signal Resolution Refactor

Layer / File(s) Summary
resolveStateSignalHistory: drop resourceId, use listMessagesById
packages/core/src/agent/state-signals.ts, packages/core/src/processors/runner.ts
Removes resourceId from the destructured input type of resolveStateSignalHistory. Replaces the listMessages stored-history lookup with listMessagesById using IDs derived from tracking.activeCopies and tracking.lastSnapshotSignalId; falls back to local history when no IDs exist or the method is unavailable. runner.ts stops passing resourceId to the function.
Test and changeset updates
packages/core/src/processors/runner.test.ts, .changeset/cuddly-ears-grab.md
Extends the memory storage mock to expose listMessagesById, updates assertions to require listMessages is not called and listMessagesById is called with messageIds: ['stored-snapshot'], and adds the patch-level changeset entry for @mastra/core.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested labels

tests: green ✅, complexity: low

Suggested reviewers

  • wardpeet
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 accurately describes the main change: restoring state signals without thread scans, which directly addresses the performance fix eliminating expensive thread history scans.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/core-state-signal-history-restore

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

@superagent-security

Copy link
Copy Markdown

Superagent didn't find any vulnerabilities or security issues in this PR.

@dane-ai-mastra dane-ai-mastra Bot added the complexity: low Low-complexity PR label Jun 18, 2026
@dane-ai-mastra

Copy link
Copy Markdown
Contributor

PR triage

Linked issue check skipped for core contributor @TylerBarnes.


PR complexity score

Factor Value Score impact
Files changed 4 +8
Lines changed 33 +0
Author merged PRs 551 -20
Test files changed Yes -10
Final score -22

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/core/src/agent/state-signals.ts`:
- Around line 179-183: The call to memoryStore.listMessagesById on line 183
lacks error handling; if this async call rejects due to a transient database or
storage failure, the error propagates and the local-history fallback is skipped.
Wrap the await memoryStore.listMessagesById call in a try-catch block, catching
any errors and falling back to returning the localHistory with contextWindow
(the same fallback returned on line 180) when the call fails, ensuring
resilience against transient storage failures.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 0898238e-8f46-458e-83e9-da57ccd4387d

📥 Commits

Reviewing files that changed from the base of the PR and between f79daa2 and a343a76.

📒 Files selected for processing (4)
  • .changeset/cuddly-ears-grab.md
  • packages/core/src/agent/state-signals.ts
  • packages/core/src/processors/runner.test.ts
  • packages/core/src/processors/runner.ts
💤 Files with no reviewable changes (1)
  • packages/core/src/processors/runner.ts

Comment on lines +179 to +183
if (trackedSignalIds.size === 0 || typeof memoryStore.listMessagesById !== 'function') {
return { ...localHistory, contextWindow };
}

const storedMessages = await memoryStore.listMessagesById({ messageIds: [...trackedSignalIds] });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Preserve local fallback when ID lookup throws.

Line 183 calls storage directly; if listMessagesById rejects (transient DB/store failure), this path throws and skips the intended local-history fallback.

🔧 Suggested fix
-  const storedMessages = await memoryStore.listMessagesById({ messageIds: [...trackedSignalIds] });
+  let storedMessages: { messages: MastraDBMessage[] };
+  try {
+    storedMessages = await memoryStore.listMessagesById({ messageIds: [...trackedSignalIds] });
+  } catch {
+    return { ...localHistory, contextWindow };
+  }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/agent/state-signals.ts` around lines 179 - 183, The call to
memoryStore.listMessagesById on line 183 lacks error handling; if this async
call rejects due to a transient database or storage failure, the error
propagates and the local-history fallback is skipped. Wrap the await
memoryStore.listMessagesById call in a try-catch block, catching any errors and
falling back to returning the localHistory with contextWindow (the same fallback
returned on line 180) when the call fails, ensuring resilience against transient
storage failures.

@CalebBarnes CalebBarnes left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed — LGTM. Clean fix for the long-thread restore path.

Swapping the full-thread listMessages({ perPage: false }) scan for a targeted listMessagesById({ messageIds }) built from tracking.activeCopies + lastSnapshotSignalId is the right call, and the fallback to local history avoids any unbounded scan.

A few things I checked that hold up:

  • Ordering is preserved even though orderBy: createdAt ASC was dropped — mergeStateSignals and deriveStateSignalHistory both re-sort via sortStateSignals, so the id-lookup result is fine regardless of adapter return order (pg/libsql actually return DESC).
  • Dropping resourceId is safe: listMessagesById looks up purely by id, the var is still used elsewhere in runner.ts, and dbMessagesToStateSignals still gets threadId for scoping.
  • Adapter coverage: listMessagesById is an abstract method on MemoryStoreBase and is implemented across the storage adapters (confirmed real queries in pg + libsql), so the fast path engages in practice — the typeof !== 'function' guard is just defensive cover for old/custom stores.

One non-blocking nit: trackedSignalIds.size === 0 is effectively dead — the !tracking.lastSnapshotSignalId early-return above guarantees the set always has ≥1 entry. Harmless, just noting it.

Verified locally (HEAD a343a76f): runner.test.ts (75) passed with no type errors, tsc --noEmit clean, prettier clean on changed files.

@dane-ai-mastra dane-ai-mastra Bot added the tests: green ✅ Changed tests failed against base as expected label Jun 18, 2026
@TylerBarnes TylerBarnes merged commit 7c0d868 into main Jun 18, 2026
101 checks passed
@TylerBarnes TylerBarnes deleted the fix/core-state-signal-history-restore branch June 18, 2026 23:21
wardpeet pushed a commit that referenced this pull request Jun 19, 2026
This fixes long-thread state signal restore by loading tracked signal
messages directly by id instead of scanning thread history.

Before:
```ts
await memoryStore.listMessages({
  threadId,
  resourceId,
  perPage: false,
});
```

After:
```ts
await memoryStore.listMessagesById({ messageIds: trackedSignalIds });
```

If tracked ids or id-based lookup are unavailable, we now fall back to
local in-memory state instead of doing an unbounded thread scan.

Verified with:
`pnpm --filter ./packages/core test -- src/processors/runner.test.ts
--bail 1 --reporter=dot`
`pnpm --filter ./packages/core check`


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## ELI5

Imagine you have a very long list of messages and need to find a few
specific ones. The old way was to look through every single message in
the list one by one until you found what you needed. The new way is much
smarter: it says "give me these specific messages by their ID" instead,
skipping all the others. This makes it much faster when threads get
really long.

## Overview

This PR improves the performance of state signal restoration in
long-running threads by eliminating expensive full-thread message scans.
Instead of iterating through all messages in a thread's history, the
system now uses a targeted ID-based lookup to fetch only the tracked
signal messages it needs.

## Changes

**Core Logic Update** (`packages/core/src/agent/state-signals.ts`)
- Modified `resolveStateSignalHistory` to collect tracked signal message
IDs from `tracking.activeCopies` and `tracking.lastSnapshotSignalId`
upfront
- Replaced `memoryStore.listMessages({ threadId, resourceId, perPage:
false })` (full thread scan) with `memoryStore.listMessagesById({
messageIds })` (targeted lookup)
- Removed the `resourceId` parameter from the function signature since
it's no longer needed for the more efficient ID-based lookup
- Graceful degradation: if `listMessagesById` is unavailable or tracking
yields no IDs, the function returns the local in-memory state without
attempting expensive fallbacks

**Caller Update** (`packages/core/src/processors/runner.ts`)
- Removed the now-unnecessary `resourceId` argument from the
`resolveStateSignalHistory` call

**Test Updates** (`packages/core/src/processors/runner.test.ts`)
- Updated mock to provide both `listMessages` and `listMessagesById`
methods
- Changed test expectations to verify that only `listMessagesById` is
called (with the specific message IDs) and `listMessages` is not called

## Impact

This optimization prevents performance degradation as thread histories
grow longer, especially in long-running conversation scenarios where
state signals need to be restored. The changes were verified against
existing test suites in the core package.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Mastra Code (openai/gpt-5.5) <noreply@mastra.ai>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

complexity: low Low-complexity PR tests: green ✅ Changed tests failed against base as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants