Skip to content

feat(sdk): persist compaction and injected context through the transcript storage state - #4894

Draft
ericallam wants to merge 1 commit into
feat/transcript-storage-seam-tri-13667from
feat/transcript-storage-changesets-tri-13667
Draft

feat(sdk): persist compaction and injected context through the transcript storage state#4894
ericallam wants to merge 1 commit into
feat/transcript-storage-seam-tri-13667from
feat/transcript-storage-changesets-tri-13667

Conversation

@ericallam

Copy link
Copy Markdown
Member

Summary

Makes a compaction summary and chat.inject context survive a continuation run, for every storage including the default.

Until now the model lane after a compaction lived only in the running worker. When the next run booted it rebuilt the lane from the transcript, so every continuation re-read the whole conversation and summarised it again. The same applied to conversational messages added with chat.inject: they lived for the worker's life and vanished on a continuation.

Design

The runtime records what it cannot rebuild from the transcript in the storage's state slot: after a compaction, the compacted model lane together with the transcript id it covers and a fingerprint of that prefix; for injections, the messages anchored to the transcript message they followed. At boot the compacted lane is used when the covered prefix is unchanged, otherwise the lane is converted from the transcript as before, and injections are re-inserted after their anchors.

A rollback or edit that reconverts the lane clears the state in the same changeset as the truncateAfter, so a storage never holds a summary for a transcript it no longer matches. A mid-turn steering message reaches the storage as a put in that turn's changeset.

An in-memory storage that logs the changesets it receives, and a test-only override for the storage the runtime persists through, let the tests assert the exact changesets for a turn, a steer, a compaction, a rollback and an injection.

@changeset-bot

changeset-bot Bot commented Sep 5, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 1677c26

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

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

@coderabbitai

coderabbitai Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 111e41be-b4b9-4ae4-b1c8-174121d6aa0c

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Walkthrough

The change adds in-memory transcript storage and persisted runtime-state helpers. chat.agent now restores and saves compaction state and transcript-anchored injections. Model-lane rebuilds and history replacements reset runtime state. New tests cover turn changesets, steering messages, compaction continuation, rollback, and injection restoration.

Merge Risk: 🟡 Moderate · up to b986d

Conversational context injected during tool-result flows can affect the current model step but be missing from later transcript processing and continuation runs. This breaks the new persistence guarantee for a reachable injection path and should be fixed before merge.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the design and behavior in detail, but it omits the required issue reference, checklist, testing steps, changelog, and screenshots sections from the repository template. Add the required template sections. Include the closed issue number, complete the checklist, describe the tests that were run, add a short changelog entry, and provide screenshots or state that screenshots are not applicable.
Docstring Coverage ⚠️ Warning Docstring coverage is 36.36% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 2 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary change: persisting compaction and injected context through transcript storage.
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.
Full details: Docstring Coverage

Explanation

Docstring coverage is 36.36% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 2 files. (1 skipped: 1 too large.)

✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/transcript-storage-changesets-tri-13667

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.

@ericallam
ericallam force-pushed the feat/transcript-storage-changesets-tri-13667 branch from b986d19 to 92d04a8 Compare September 5, 2026 20:29
@pkg-pr-new

pkg-pr-new Bot commented Sep 5, 2026

Copy link
Copy Markdown

Open in StackBlitz

@trigger.dev/build

npm i https://pkg.pr.new/@trigger.dev/build@1677c26

trigger.dev

npm i https://pkg.pr.new/trigger.dev@1677c26

@trigger.dev/core

npm i https://pkg.pr.new/@trigger.dev/core@1677c26

@trigger.dev/python

npm i https://pkg.pr.new/@trigger.dev/python@1677c26

@trigger.dev/react-hooks

npm i https://pkg.pr.new/@trigger.dev/react-hooks@1677c26

@trigger.dev/redis-worker

npm i https://pkg.pr.new/@trigger.dev/redis-worker@1677c26

@trigger.dev/rsc

npm i https://pkg.pr.new/@trigger.dev/rsc@1677c26

@trigger.dev/schema-to-json

npm i https://pkg.pr.new/@trigger.dev/schema-to-json@1677c26

@trigger.dev/sdk

npm i https://pkg.pr.new/@trigger.dev/sdk@1677c26

commit: 1677c26

…ript storage state

The model lane after a compaction cannot be rebuilt from the transcript, so every continuation used to re-read the whole conversation and summarise it again. The runtime now records the compacted lane in the storage's state slot, with the transcript id it covers and a fingerprint of that prefix, and rebuilds from it at boot when the prefix is unchanged. A rollback or edit that reconverts the lane clears the state in the same changeset as the truncate.

Conversational messages added with chat.inject are recorded the same way, anchored to the transcript message they followed, so they survive a continuation instead of living only in the worker that received them.

Adds an in-memory storage that logs the changesets it receives, and a test-only override for the storage the runtime persists through, so the exact changesets for a turn, a mid-turn steer, a compaction, a rollback and an injection are asserted.
@ericallam
ericallam force-pushed the feat/transcript-storage-changesets-tri-13667 branch from 92d04a8 to 1677c26 Compare September 5, 2026 20:38

@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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 1ca0ff6a-b54c-4e6f-90a9-42e719cf45df

📥 Commits

Reviewing files that changed from the base of the PR and between 4c91a95 and b986d19.

📒 Files selected for processing (3)
  • packages/trigger-sdk/src/v3/ai.ts
  • packages/trigger-sdk/src/v3/transcriptStorage.ts
  • packages/trigger-sdk/test/transcript-changesets.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.

📜 Review details
🧰 Additional context used
📓 Path-based instructions (9)
Always import from `@trigger.dev/sdk`.

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • packages/trigger-sdk/test/transcript-changesets.test.ts
  • packages/trigger-sdk/src/v3/ai.ts
  • packages/trigger-sdk/src/v3/transcriptStorage.ts
We use vitest exclusively.

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • packages/trigger-sdk/test/transcript-changesets.test.ts
**Prefer static imports over dynamic imports.**

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • packages/trigger-sdk/test/transcript-changesets.test.ts
  • packages/trigger-sdk/src/v3/ai.ts
  • packages/trigger-sdk/src/v3/transcriptStorage.ts
Add crumbs as you write code — not just when debugging.

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • packages/trigger-sdk/test/transcript-changesets.test.ts
  • packages/trigger-sdk/src/v3/ai.ts
  • packages/trigger-sdk/src/v3/transcriptStorage.ts
In the Trigger.dev SDK (packages/trigger-sdk), prefer isomorphic code like fetch and ReadableStream instead of Node.js-specific code

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Files:

  • packages/trigger-sdk/test/transcript-changesets.test.ts
  • packages/trigger-sdk/src/v3/ai.ts
  • packages/trigger-sdk/src/v3/transcriptStorage.ts
Use vitest for all tests in the Trigger.dev repository

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Files:

  • packages/trigger-sdk/test/transcript-changesets.test.ts
Use function declarations instead of default exports

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Files:

  • packages/trigger-sdk/test/transcript-changesets.test.ts
  • packages/trigger-sdk/src/v3/ai.ts
  • packages/trigger-sdk/src/v3/transcriptStorage.ts
Use types over interfaces for TypeScript Avoid using enums; prefer string unions or const objects instead

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Files:

  • packages/trigger-sdk/test/transcript-changesets.test.ts
  • packages/trigger-sdk/src/v3/ai.ts
  • packages/trigger-sdk/src/v3/transcriptStorage.ts
When creating or editing OTEL metrics (counters, histograms, gauges), ensure metric attributes have low cardinality by using only enums, booleans, bounded error codes, or bounded shard IDs Do not use high-cardinality attributes in OTEL metr...

📄 CodeRabbit inference engine (.cursor/rules/otel-metrics.mdc)

Files:

  • packages/trigger-sdk/test/transcript-changesets.test.ts
  • packages/trigger-sdk/src/v3/ai.ts
  • packages/trigger-sdk/src/v3/transcriptStorage.ts
🧠 Learnings (2)
📚 Learning: 2026-08-16T18:36:58.179Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 4537
File: packages/trigger-sdk/test/normalizeKeyString.test.ts:1-2
Timestamp: 2026-08-16T18:36:58.179Z
Learning: For related SDK `chat.agent` tests in the Trigger.dev repository—including chat channels, handover, snapshot, and transport-event coverage—keep new test files under `packages/trigger-sdk/test/` rather than colocating them with the `packages/trigger-sdk/src/v3/` source files.

Applied to files:

  • packages/trigger-sdk/test/transcript-changesets.test.ts
📚 Learning: 2026-06-04T18:16:35.386Z
Learnt from: nicktrn
Repo: triggerdotdev/trigger.dev PR: 3836
File: apps/supervisor/src/backpressure/backpressureMonitor.ts:3-5
Timestamp: 2026-06-04T18:16:35.386Z
Learning: When reviewing TypeScript in this repo, apply the rule “prefer type aliases over interfaces” only to data/object shapes and union/intersection type modeling. If an interface is being used as a behavioral contract for collaborators to implement (e.g., method-shape interfaces that define required behavior, such as `BackpressureLogger` / `BackpressureSignalSource` in `apps/supervisor/src/backpressure/backpressureMonitor.ts`), keep it as an `interface` and do not flag it as a type-alias-vs-interface violation.

Applied to files:

  • packages/trigger-sdk/src/v3/transcriptStorage.ts
🔇 Additional comments (12)
packages/trigger-sdk/src/v3/transcriptStorage.ts (4)

237-237: LGTM!

Also applies to: 263-279


281-324: LGTM!


326-373: LGTM!


380-447: LGTM!

packages/trigger-sdk/src/v3/ai.ts (7)

89-101: LGTM!


6892-6903: LGTM!


6951-6967: LGTM!

Also applies to: 6988-6988


7073-7074: LGTM!


7419-7426: LGTM!


8098-8099: LGTM!

Also applies to: 8137-8138, 8271-8272, 8322-8323, 8377-8378, 8560-8561, 8825-8826, 8946-8947, 9174-9175, 9235-9236, 9601-9602


8852-8853: LGTM!

Also applies to: 9067-9068

packages/trigger-sdk/test/transcript-changesets.test.ts (1)

1-333: LGTM!

Source: Learnings

Comment on lines +8627 to +8632
const injected = bgQueue.splice(0);
accumulatedMessages.push(...injected);
laneInjections.push({
afterId: accumulatedUIMessages.at(-1)?.id ?? "",
messages: injected,
});

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.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Background injections drained through the inner-loop prepareStep path are never tracked, so they are silently lost from accumulatedMessages and never persisted.

This drain only runs when the last accumulated model message is not a tool message. The comment on this block states the fallback: when the tail is a tool message, the queued messages are picked up instead by toStreamTextOptions()'s own auto-injected prepareStep (the background-context-injection step further up in this file). That sibling drain returns the injected content only inside resultMessages for the current streamText step. It does not push into accumulatedMessages and does not push an entry into laneInjections.

Two consequences follow from the missing sync:

  • Within the same run, accumulatedMessages no longer reflects what the model actually saw for that step. Outer-loop compaction, onTurnComplete.messages/newMessages, and any later reconversion checkpoint all operate on a lane that is missing the injected content.
  • On a continuation boot, restoreModelLane has no record of that injection (it was never added to laneInjections, and it is not part of the transcript, so it cannot be recovered by reconverting UI messages either). This directly contradicts the PR's stated goal that "Injected messages are stored with anchors to the transcript messages they followed and reinserted on continuation" — for this specific, already-documented fallback case, they are not.

This is reachable whenever a chat.inject() call queues conversational content while the accumulator's last model message is a tool message (for example, right after a HITL tool-result exchange), and the agent's turn involves multiple streamText steps (tool calls).

Fix this by reconciling the inner-loop background-injection drain the same way drainSteeringQueue/reconcilePendingSteer reconcile steering messages: record what was actually drained and its anchor, then merge it back into accumulatedMessages and laneInjections once the turn's userRun/streamText call returns (before the turn's snapshot is written). For example, in the toStreamTextOptions() prepareStep step handling background context (around the block that does const injected = bgQueue.splice(0); resultMessages = [...(resultMessages ?? messages), ...injected];), also stash injected alongside the current tail id so the caller can merge it back:

// toStreamTextOptions()'s prepareStep, background-context step:
const bgQueue = locals.get(chatBackgroundQueueKey);
if (bgQueue && bgQueue.length > 0) {
  const injected = bgQueue.splice(0);
  resultMessages = [...(resultMessages ?? messages), ...injected];
  const pendingBg = locals.get(chatPendingBackgroundInjectionKey) ?? [];
  pendingBg.push({ afterId: <current UI tail id>, messages: injected });
  locals.set(chatPendingBackgroundInjectionKey, pendingBg);
}

Then, after userRun/streamText returns, merge chatPendingBackgroundInjectionKey into accumulatedMessages and laneInjections the same way the existing pre-run drain does at lines 8627-8632.

None of the new tests exercise this fallback (they only cover the pre-run drain, triggered from onTurnComplete). Consider adding a test that forces the accumulator's tail to be a tool message before queuing a chat.inject() call, to lock in the fix.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant