From 3134ca6f8e201eeeff29a06fed91b5c0c7eb487a Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 30 Aug 2026 14:44:24 +0000 Subject: [PATCH] stream: update broadcast to retain buffered data with zero consumers While the Broadcast is still open, maintain buffered data when consumer count reaches zero Signed-off-by: James M Snell Assisted-by: Opencode PR-URL: https://github.com/nodejs/node/pull/66028 Reviewed-By: Filip Skokan Reviewed-By: Tim Perry --- lib/internal/streams/iter/broadcast.js | 2 ++ test/parallel/test-stream-iter-broadcast-basic.js | 13 +++++++++++++ 2 files changed, 15 insertions(+) diff --git a/lib/internal/streams/iter/broadcast.js b/lib/internal/streams/iter/broadcast.js index ddce0d12d42..b78aa5377eb 100644 --- a/lib/internal/streams/iter/broadcast.js +++ b/lib/internal/streams/iter/broadcast.js @@ -444,6 +444,8 @@ class BroadcastImpl { } #tryTrimBuffer() { + // Retain buffered data for consumers that attach while none are active. + if (this.#consumers.size === 0) return; if (this.#cachedMinCursorConsumers === 0) { this.#recomputeMinCursor(); } diff --git a/test/parallel/test-stream-iter-broadcast-basic.js b/test/parallel/test-stream-iter-broadcast-basic.js index 3dbd3ce9751..4135aea6d97 100644 --- a/test/parallel/test-stream-iter-broadcast-basic.js +++ b/test/parallel/test-stream-iter-broadcast-basic.js @@ -350,6 +350,18 @@ async function testLateJoinerSeesBufferedData() { assert.strictEqual(result, 'before-join'); } +async function testLateJoinerAfterDetachSeesBufferedData() { + const { writer, broadcast: bc } = broadcast({ budget: 16384 }); + const first = bc.push()[Symbol.asyncIterator](); + + writer.writeSync('before-detach'); + await first.return(); + + const second = bc.push(); + writer.endSync(); + assert.strictEqual(await text(second), 'before-detach'); +} + async function testOverlappingNextKeepsEarlierRead() { const { writer, broadcast: bc } = broadcast(); const it = bc.push()[Symbol.asyncIterator](); @@ -403,5 +415,6 @@ Promise.all([ testFailDetachesConsumers(), testWriterFailIdempotent(), testLateJoinerSeesBufferedData(), + testLateJoinerAfterDetachSeesBufferedData(), testOverlappingNextKeepsEarlierRead(), ]).then(common.mustCall());