Skip to content

Commit c35e05d

Browse files
jasnelladuh95
authored andcommitted
stream: do not retain a promise per read in stream/iter share()
share() read its source by racing the source's next() with a promise that cancel() resolves, created once for the share. That promise does not settle until the share is cancelled, so every race added reactions to it that were kept for as long as the share was in use: about 720 bytes per batch read, including three promises, two promise reactions and six closures. Sharing a source of 800,000 16-byte chunks between two consumers kept 574 MiB alive after garbage collection by the end. Instead, keep the resolver of the pending read in a field, and have cancel() settle that read with the same result as before. A read still settles as soon as the share is cancelled, without waiting for the source. What a share keeps alive no longer grows with the batches read: the peak heap sharing 200,000 16-byte chunks between two consumers drops from 180 MB to 9 MB, and the share is about 3 times faster. Assisted-by: OpenCode Signed-off-by: James M Snell <jasnell@gmail.com> PR-URL: #66504 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
1 parent a7f059a commit c35e05d

2 files changed

Lines changed: 77 additions & 12 deletions

File tree

‎lib/internal/streams/iter/share.js‎

Lines changed: 30 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ const {
1212
PromisePrototypeThen,
1313
PromiseResolve,
1414
PromiseWithResolvers,
15-
SafePromiseRace,
1615
SafeSet,
1716
Symbol,
1817
SymbolAsyncIterator,
@@ -89,8 +88,9 @@ class ShareImpl {
8988
#cancelled = false;
9089
#pulling = false;
9190
#pullWaiters = [];
92-
#cancelPromise;
93-
#resolveCancel;
91+
// Settles the pending read of the source with kShareCancelled when the
92+
// share is cancelled, or null if no read is pending.
93+
#cancelPendingRead = null;
9494
#cancelError = kNoShareError;
9595
#cachedMinCursor = 0;
9696
#cachedMinCursorConsumers = 0;
@@ -101,9 +101,6 @@ class ShareImpl {
101101
constructor(source, options) {
102102
this.#source = source;
103103
this.#options = options;
104-
const { promise, resolve } = PromiseWithResolvers();
105-
this.#cancelPromise = promise;
106-
this.#resolveCancel = resolve;
107104
}
108105

109106
get consumerCount() {
@@ -280,8 +277,11 @@ class ShareImpl {
280277
this.#cancelError = reason;
281278
}
282279

283-
this.#resolveCancel(kShareCancelled);
284-
this.#resolveCancel = null;
280+
const cancelPendingRead = this.#cancelPendingRead;
281+
if (cancelPendingRead !== null) {
282+
this.#cancelPendingRead = null;
283+
cancelPendingRead(kShareCancelled);
284+
}
285285

286286
try {
287287
const returnMethod = this.#sourceIterator?.return;
@@ -416,10 +416,7 @@ class ShareImpl {
416416
}
417417
}
418418

419-
const result = await SafePromiseRace([
420-
this.#sourceIterator.next(),
421-
this.#cancelPromise,
422-
]);
419+
const result = await this.#readSource();
423420

424421
if (this.#cancelled || result === kShareCancelled) return;
425422

@@ -444,6 +441,27 @@ class ShareImpl {
444441
})();
445442
}
446443

444+
// Read the next result of the source, settling early with kShareCancelled
445+
// if the share is cancelled first. Racing the read with a promise settled
446+
// by cancel() would add reactions to that promise on every read, which
447+
// would be kept until the share is cancelled or collected.
448+
#readSource() {
449+
const next = this.#sourceIterator.next();
450+
const { promise, resolve, reject } = PromiseWithResolvers();
451+
this.#cancelPendingRead = resolve;
452+
PromisePrototypeThen(
453+
PromiseResolve(next),
454+
(result) => {
455+
if (this.#cancelPendingRead === resolve) this.#cancelPendingRead = null;
456+
resolve(result);
457+
},
458+
(error) => {
459+
if (this.#cancelPendingRead === resolve) this.#cancelPendingRead = null;
460+
reject(error);
461+
});
462+
return promise;
463+
}
464+
447465
#bufferBatch(batch) {
448466
const entry = createBatchEntry(batch);
449467
// 'drop-oldest' evicts whole entries. A single pulled batch can be much
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Flags: --experimental-stream-iter --expose-gc --no-warnings
2+
'use strict';
3+
4+
// Reading the source of a share() must not leave objects behind for every
5+
// read: what a share keeps alive must not grow with the number of batches
6+
// read from its source.
7+
8+
const common = require('../common');
9+
const assert = require('assert');
10+
const { queryObjects } = require('v8');
11+
const { share } = require('stream/iter');
12+
13+
async function test() {
14+
const reads = 4000;
15+
const chunk = new Uint8Array(1);
16+
let i = 0;
17+
const source = {
18+
[Symbol.asyncIterator]() { return this; },
19+
async next() {
20+
return i++ < reads ?
21+
{ done: false, value: [chunk] } :
22+
{ done: true, value: undefined };
23+
},
24+
};
25+
const shared = share(source, { backpressure: 'unbounded' });
26+
const a = shared.pull()[Symbol.asyncIterator]();
27+
const b = shared.pull()[Symbol.asyncIterator]();
28+
29+
const promises = [];
30+
for (let n = 0; n < reads; n++) {
31+
assert.strictEqual((await a.next()).done, false);
32+
assert.strictEqual((await b.next()).done, false);
33+
if (n === 1000 || n === 3000) {
34+
globalThis.gc();
35+
promises.push(queryObjects(Promise, { format: 'count' }));
36+
}
37+
}
38+
assert.strictEqual((await a.next()).done, true);
39+
assert.strictEqual((await b.next()).done, true);
40+
41+
// 2000 reads happened between the two counts. Retaining even one promise
42+
// per read would add 2000.
43+
const growth = promises[1] - promises[0];
44+
assert.ok(growth < 200, `${growth} promises retained across 2000 reads`);
45+
}
46+
47+
test().then(common.mustCall());

0 commit comments

Comments
 (0)