fix(ai): stop StreamProcessor holding a segment copy per text delta #2308
main fromrefs/pull/2308/head·opened View on GitHubStreamProcessor held memory in proportion to the square of a streamed text message's length. 3,000 text deltas of 16 characters kept about 69 MiB on the heap. This PR appends each delta to the message content directly, and the same stream now keeps about 0.4 MiB. This is part 1 of #1963. Part 2 (tool-call arguments) is not in this PR.
🎯 Changes#
handleTextMessageContentEventinpackages/ai/src/activities/chat/stream/processor.tsappendsdeltatototalTextContent. Before, it appendednextText.slice(currentText.length). That value always equalsdelta.- A new test in
packages/ai/tests/stream-processor.test.tsstreams 3,000 deltas and fails if the heap grows by 10 MiB or more. It forces GC through annode:inspectorsession, so it does not turn on--expose-gcfor other tests. - A patch changeset for
@tanstack/ai.
No docs change: the streamed text and the public API do not change.
✅ Checklist#
- I have followed the steps in the Contributing guide.
- I have tested code changes locally with
pnpm run test:pr, or these tests do not apply to this pull request. - I fully understand the code in this pull request, including any code generated with AI assistance.
- Docs: I updated
docs/for this change, or this change is not user-facing. - Changeset: I added a changeset (
pnpm changeset), or this PR does not change a published package.
I did not run pnpm run test:pr. I ran the @tanstack/ai unit tests, type check, oxlint, and oxfmt (see Testing).
🚀 Release Impact#
- This change affects published code, and I have generated a changeset.
- This change is docs/CI/dev-only (no release).
Root cause#
Issue. A client or server that streams a long assistant text message through StreamProcessor keeps far more memory than the text needs. The cost grows with the square of the message length.
Cause. handleTextMessageContentEvent built nextText = currentText + delta, then took nextText.slice(currentText.length) and appended it to totalTextContent. In V8, slice flattens the concatenated string first. For a result of 13 characters or more, it returns a sliced string that points into that flattened buffer. Each delta therefore kept one full copy of the segment alive through totalTextContent.
Fix. Append delta itself. The slice always equals delta on every path: an empty delta, a missing chunk.delta, and a new segment after tool calls. The removed local had no other reader.
Possible alternatives#
- Flatten
totalTextContentperiodically. For example,totalTextContent = totalTextContent.split('').join(''). This hides the retention but keeps the extra slice and adds work. The slice has no purpose, so this PR deletes it. - Build
totalTextContentfrom an array of parts. This changes more code and every read site oftotalTextContentfor the same result.
Testing#
Commands run (Node 24.14.1, pnpm 11.9.0)
pnpm exec vitest run tests/stream-processor.test.ts -t 1963inpackages/ai:- On unchanged
main, 3 runs: fail,expected 69.0016098022461 to be less than 10. - On this branch, 3 runs: pass.
- On unchanged
pnpm exec vitest runinpackages/ai: 171 files, 2888 tests passed.pnpm test:typesandpnpm test:oxlintinpackages/ai: pass, 0 oxlint errors.oxfmt --checkon the changed files: pass.- Not run:
pnpm run test:prand the Playwright E2E suite.
Manual test
- On
main, runpnpm exec vitest run tests/stream-processor.test.ts -t 1963inpackages/ai. The test fails with about 69 MiB of heap growth. - On this branch, run the same command. The test passes.
- Compare the text: the test also asserts that
getState().contenthas all 48,000 characters.
How this PR makes testing easy
The new test is the reproduction. It fails on main and passes on this branch.
Why no E2E test
The bug is heap retention, and the streamed text does not change. An E2E test cannot see heap retention, and an E2E text assertion passes on main too. tests/chat-client-stream-processing.spec.ts already streams 2,000 text chunks through this path and checks the full text. #1962 and #2086 fixed the same kind of memory bug with a unit test only.
Linked issues#
Refs #1963 (part 1 only, text deltas). The tool-call argument re-parse in part 2 changes when parsedArguments is available, so it needs a separate decision.
Risk / rollback#
Low. The fix changes one expression to an equal value. To undo, revert the PR. The heap test has a large margin (10 MiB limit, 0.4 MiB on this branch, 69 MiB on main).
- 1
tanstack-source added labelsbug
Useful. This change matches the text-delta part of #1963. The PR already links that issue. No open pull request does the same work.
TanStack Source bot, value agent
No actionable comments were generated in the recent review.
Walkthrough
-
The stream processor now appends each incoming text delta directly to accumulated content. A regression test checks the final text length and heap growth while processing 3,000 deltas.
Changes: Text-delta memory handling
Layer / File(s) Summary Direct delta append and memory regression
packages/ai/src/activities/chat/stream/processor.ts,packages/ai/tests/stream-processor.test.ts,.changeset/stream-processor-text-delta-memory.mdThe processor appends each incoming delta directly instead of slicing accumulated text. The test checks for 48,000 accumulated characters and less than 10 MiB of heap growth. The changeset documents the patch. Estimated code review effort: 2 (Simple) | ~10 minutes
Change: Bug fix
Possibly related issues
TanStack/ai#1963— The described issue includes the text-delta memory behavior changed here. Its separate tool-call argument re-parsing issue is not addressed.
Suggested reviewers:
thruflo,alemtuzlak,tombeckenham
Merge Risk:
Minimal · up tod368c-
This change stops the stream processor from retaining a copy of each text segment as a message grows, which lowers memory use during long streams. Streamed text output is unchanged. No merge-blocking risk was found.
Pre-merge checks:
4-
Check name Status Explanation Title check The title "fix(ai): stop StreamProcessor holding a segment copy per text delta" names the main change: StreamProcessor no longer keeps a segment copy per text delta. The changeset, processor.ts edit, … Linked Issues check Check skipped because no linked issues were found for this pull request. Out of Scope Changes check Check skipped because no linked issues were found for this pull request. Description check The description covers the required template sections. It explains the change and its reason (memory retention in StreamProcessor, with measured before and after heap numbers), lists the changed files… Full details: Title check
-
Explanation
The title "fix(ai): stop StreamProcessor holding a segment copy per text delta" names the main change: StreamProcessor no longer keeps a segment copy per text delta. The changeset, processor.ts edit, and regression test all match this. The title is specific and concise.
Full details: Description check
-
Explanation
The description covers the required template sections. It explains the change and its reason (memory retention in StreamProcessor, with measured before and after heap numbers), lists the changed files, and gives the root cause, fix, alternatives, testing, and risk. The checklist is filled in, and the changeset is noted in the release impact section. The unchecked box for test:pr is explained: the author did not run pnpm run test:pr and lists the commands run instead. The description has no docs update, which the author justifies as no user-facing change. The description is thorough and mostly complete. Some items are optional extras beyond the template, which does not reduce completeness.
-
Finishing Touches
-
Generate unit tests (beta)
-
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
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.
Recent review info-
Run configuration-
- Source mode: Auto
- Repository: TanStack/ai
- Branch: main
- File: .coderabbit.yaml
- Commit: 840ea56
- Layers: Repository YAML
- Review profile: CHILL
- Plan: Advanced
- Run ID:
e1aee90b-f784-4017-a394-9cefe3e35af7
Commits-
Reviewing files that changed from the base of the PR and between 840ea56621f4c32de4359849a0beaa343db60fe3 and d368c4875e4e618cfc17ee4ceda412936bd68eab.
Files selected for processing: 3-
.changeset/stream-processor-text-delta-memory.mdpackages/ai/src/activities/chat/stream/processor.tspackages/ai/tests/stream-processor.test.ts
Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.
-
-
github-actions[bot](GitHub profile, opens in a new tab) assignedtombeckenham
Thanks for the PR, @dante01yoon! 🙌 @tombeckenham will take a look.
Automated pre-review checks
- ✅ CI passing
- ✅ No merge conflicts
- ✅ Changeset present
- ⚠️ No E2E test changes detected — behavior changes need coverage under
testing/e2e/(see CONTRIBUTING)
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer
Sign in to join this conversation.
🦋 Changeset detected#
Latest commit: d368c4875e4e618cfc17ee4ceda412936bd68eab
The changes in this PR will be included in the next version bump.
This PR includes changesets to release 2 packages
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