Skip to content
Source
Sign inSign up
TanStack/ai

fix(ai): stop StreamProcessor holding a segment copy per text delta #2308

Opendante01yoon(GitHub profile, opens in a new tab)wants to merge 1 commit intomain fromrefs/pull/2308/headopened View on GitHub

Showing 3 changed files with 37 additions and 3 deletions.

x
0 of 3 viewed, 3 left
5 additions and 0 deletions.changeset/stream-processor-text-delta-memory.mdAdded
View file
@@ -0,0 +1,5 @@
+---
+'@tanstack/ai': patch
+---
+​
+`StreamProcessor` no longer appends a slice of the accumulated text segment to the message content for each `TEXT_MESSAGE_CONTENT` delta. In V8 such a slice can keep the segment's whole backing string alive, so memory grew with the square of the message length. 3,000 deltas of 16 characters retained about 69 MiB. They now retain about 0.4 MiB. The text that streams out is unchanged.
3 additions and 3 deletionspackages/ai/src/activities/chat/stream/processor.tsModified
View file
@@ -2375,10 +2375,10 @@
const delta = chunk.delta || ''
const nextText = delta !== '' ? currentText + delta : currentText
- // Calculate the delta for totalTextContent
- const textDelta = nextText.slice(currentText.length)
+ // Append `delta` itself: a slice of the accumulated text can keep that
+ // text's whole backing string alive, so memory grows with its square.
state.currentSegmentText = nextText
- state.totalTextContent += textDelta
+ state.totalTextContent += delta
const chunkPortion = chunk.delta || ''
const shouldEmit = this.chunkStrategy.shouldEmit(
29 additions and 0 deletionspackages/ai/tests/stream-processor.test.tsModified
View file
@@ -1,3 +1,4 @@
+import { Session } from 'node:inspector/promises'
import { describe, expect, it, vi } from 'vitest'
import {
StreamProcessor,