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());