stream: speed up async iteration of Readable - #64447

Merged
nodejs-github-bot merged 4 commits into
nodejs:mainfrom
mcollina:stream-async-iterator-perf
Aug 14, 2026
Merged

stream: speed up async iteration of Readable#64447
nodejs-github-bot merged 4 commits into
nodejs:mainfrom
mcollina:stream-async-iterator-perf

Conversation

@mcollina

@mcollinamcollina commented Jul 12, 2026

Copy link
Copy Markdown
Member

Replace the async generator backing Readable.prototype[Symbol.asyncIterator] (and .iterator()) with a hand-rolled iterator.

The generator machinery costs several extra promise allocations and microtask hops per chunk: yield awaits the yielded value and resolves the pending request through separate promises, and every next() goes through the async generator request queue. The hand-rolled iterator delivers buffered chunks as an already-resolved promise.

The observable semantics are preserved:

  • thenable chunks (object mode) are still awaited before delivery, and a rejected thenable still tears down the iterator and the stream;
  • next()/return()/throw() calls received while a request is outstanding are queued and processed in order — including return() while waiting for data, which still completes only once the pending read settles;
  • return()/throw() before the first next() complete the iterator without attaching listeners or destroying the stream;
  • the finally teardown logic (destroyOnReturn, autoDestroy, half-open duplex preservation) is unchanged;
  • error aggregation via aggregateTwoErrors is unchanged.

The one observable difference is that buffered chunks are delivered one microtask sooner than before, since the generator's yield performed an implicit Await on the yielded value. This is visible to code racing an abort against the first chunk. The flatMap AbortSignal test relied on such a race (a queueMicrotask'd abort beating the first chunk); it is reworked to be deterministic and timer-free: two mappers block until their signal aborts, the abort fires while both are in flight, and the test asserts the concurrency limit is respected (exactly two mappers start), in-flight mappers are cancelled through their signal, and iteration rejects with AbortError. The reworked test passes against both the old and the new implementation.

New regression tests cover the subtler iterator behaviors (thenable unwrapping, rejected thenables, throw(), pre-start throw(), concurrent next() ordering, and return() queued behind a pending next()); they also pass against both implementations.

Benchmark (benchmark/compare.js, 30 runs):

 confidence improvement accuracy (*) (**) (***)
streams/readable-async-iterator.js sync='no' n=100000 *** 9.84 % ±3.04% ±4.05% ±5.27%
streams/readable-async-iterator.js sync='yes' n=100000 *** 32.59 % ±5.49% ±7.34% ±9.62%

No changes on pipe.js / readable-readall.js.

🤖 Generated with Claude Code

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Review requested:

  • @nodejs/streams

@nodejs-github-botnodejs-github-bot added needs-ci PRs that need a full CI run. stream Issues and PRs related to Node.js streams. labels Jul 12, 2026
Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.
Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.
The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.
streams/readable-async-iterator.js sync='yes': +32.59% (***)
streams/readable-async-iterator.js sync='no': +9.84% (***)
Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
@mcollina
mcollinaforce-pushed the stream-async-iterator-perf branch from 2307152 to 6f9a2f3CompareJuly 12, 2026 08:36
Comment threadlib/internal/streams/readable.js Outdated
Comment on lines +1486 to +1497
if (typeof chunk.then === 'function') {
PromisePrototypeThen(PromiseResolve(chunk), (value) => {
inFlight = false;
resolve({ done: false, value });
if (queue !== null) drain();
}, (err) => {
inFlight = false;
settleError(err, reject);
if (queue !== null) drain();
});
return;
}

@aduh95aduh95Jul 12, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If then is a getter that e.g. throws on the second access, this code might throw when previously it wouldn't have. We can protect against that by storing the initial value we're getting (that might also avoid an additional promise allocation).

Suggested change
if(typeofchunk.then==='function'){
PromisePrototypeThen(PromiseResolve(chunk),(value)=>{
inFlight=false;
resolve({done: false, value });
if(queue!==null)drain();
},(err)=>{
inFlight=false;
settleError(err,reject);
if(queue!==null)drain();
});
return;
}
const{ then }=chunk;
if(typeofthen==='function'){
FunctionPrototypeCall(then,chunk,(value)=>{
inFlight=false;
resolve({done: false, value });
if(queue!==null)drain();
},(err)=>{
inFlight=false;
settleError(err,reject);
if(queue!==null)drain();
});
return;
}

Comment threadlib/internal/streams/readable.js Outdated
Comment on lines +1555 to +1558
if (typeof chunk.then === 'function') {
inFlight = true;
return PromisePrototypeThen(
PromiseResolve(chunk), onChunkFulfilled, onChunkRejected);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here

Suggested change
if(typeofchunk.then==='function'){
inFlight=true;
returnPromisePrototypeThen(
PromiseResolve(chunk),onChunkFulfilled,onChunkRejected);
const{then }=chunk;
if(typeofthen==='function'){
inFlight=true;
returnFunctionPrototypeCall(then,chunk,onChunkFulfilled,onChunkRejected);

settleError(err, reject);
}

return {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This object should ideally have a prototype of AsyncIteratorPrototype.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure it should if the sprecs doesn't require it – it does add a @@asyncDispose method which may or may not be desirable – it also adds a @@asyncIterator, which begs the question whether we should re-implement the method (re-implementing it ourselves means we're not subject to prototype tampering; otherwise, letting the built-in method be inherited would saves a bit of memory maybe?)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current implementation derives from AsyncIteratorPrototype (as a generator) so if we're trying to minimise observability then this is a fairly free move. (While the language currently only provides for the two well-known symbol methods, once we get into async iterator helpers territory, there will be significant advantages to keeping this inheritance.)

@codecov

codecovBot commented Jul 12, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.23256% with 21 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.29%. Comparing base (8a3b11c) to head (873a47e).
⚠️ Report is 472 commits behind head on main.

Files with missing linesPatch %Lines
lib/internal/streams/readable.js90.23%20 Missing and 1 partial ⚠️
Additional details and impacted files
@@ Coverage Diff @@## main #64447 +/- ##
==========================================
+ Coverage 90.24% 90.29% +0.04% 
==========================================
Files 741 760 +19 Lines 241384 247324 +5940 Branches 45480 46652 +1172 ==========================================
+ Hits 217844 223310 +5466 - Misses 15097 15477 +380 - Partials 8443 8537 +94 
Files with missing linesCoverage Δ
lib/internal/streams/readable.js96.55% <90.23%> (-0.72%)⬇️

... and 209 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Comment threadlib/internal/streams/readable.js Outdated
return new Promise((resolve, reject) => {
if (inFlight) {
queue ??= [];
queue.push({ type: 'return', value, resolve, reject });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
queue.push({type: 'return', value, resolve, reject });
queue.push({__proto__: null,type: 'return', value, resolve, reject });

Comment threadlib/internal/streams/readable.js Outdated
return new Promise((resolve, reject) => {
if (inFlight) {
queue ??= [];
queue.push({ type: 'next', value: undefined, resolve, reject });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
queue.push({type: 'next',value: undefined, resolve, reject });
queue.push({__proto__: null,type: 'next',value: undefined, resolve, reject });

Comment threadlib/internal/streams/readable.js Outdated
return new Promise((resolve, reject) => {
if (inFlight) {
queue ??= [];
queue.push({ type: 'throw', value: err, resolve, reject });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
queue.push({type: 'throw',value: err, resolve, reject });
queue.push({__proto__: null,type: 'throw',value: err, resolve, reject });

Comment threadlib/internal/streams/readable.js Outdated

function drain() {
while (!inFlight && queue.length > 0) {
const req = queue.shift();

@mertcanaltinmertcanaltinJul 12, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we replace queue.shift(); with an index-based queue for high throughput?

Comment threadlib/internal/streams/readable.js Outdated
Comment threadlib/internal/streams/readable.js Outdated
Comment threadtest/parallel/test-stream-flatMap.js Outdated
Comment on lines +84 to +89
await new Promise((resolve, reject) => {
if (signal.aborted) {
reject(signal.reason);
return;
}
signal.addEventListener('abort', () => reject(signal.reason), { once: true });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
awaitnewPromise((resolve,reject)=>{
if(signal.aborted){
reject(signal.reason);
return;
}
signal.addEventListener('abort',()=>reject(signal.reason),{once: true});
const{ promise, reject }=Promise.withResolvers();
if(signal.aborted){
reject(signal.reason);
}
signal.addEventListener('abort',()=>reject(signal.reason),{once: true});
// Promise is expected to reject.
awaitpromise;

Signed-off-by: Matteo Collina <hello@matteocollina.com>

@gurgundaygurgunday left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@mcollinamcollina added the request-ci Add this label to start a Jenkins CI on a PR. label Jul 13, 2026
@github-actionsgithub-actionsBot removed the request-ci Add this label to start a Jenkins CI on a PR. label Jul 13, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Comment threadlib/internal/streams/readable.js Outdated
Signed-off-by: Matteo Collina <hello@matteocollina.com>
@mcollina

Copy link
Copy Markdown
MemberAuthor

@MattiasBuelens updated

@gurgundaygurgunday left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

Signed-off-by: Matteo Collina <hello@matteocollina.com>
@ronagronag added request-ci Add this label to start a Jenkins CI on a PR. author ready PRs with CI started, the required approvals, and no outstanding review comments. labels Aug 6, 2026
@github-actionsgithub-actionsBot removed the request-ci Add this label to start a Jenkins CI on a PR. label Aug 6, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@mcollinamcollina added the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 14, 2026
@nodejs-github-botnodejs-github-bot added commit-queue-failed PRs whose Commit Queue landing failed and need manual intervention before retrying. and removed commit-queue PRs queued for automated landing through the Commit Queue. labels Aug 14, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator
Commit Queue failed
- Loading data for nodejs/node/pull/64447
✔ Done loading data for nodejs/node/pull/64447
----------------------------------- PR info ------------------------------------
Title stream: speed up async iteration of Readable (#64447)
Author Matteo Collina <matteo.collina@gmail.com> (@mcollina)
Branch mcollina:stream-async-iterator-perf -> nodejs:main
Labels stream, author ready, needs-ci, commit-queue
Commits 4
- stream: speed up async iteration of Readable
- fixup: address review comments
- fixup: remove [SymbolAsyncIterator]
- stream: fix lint in readable async iterator
Committers 1
- Matteo Collina <hello@matteocollina.com>
PR-URL: https://github.com/nodejs/node/pull/64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
------------------------------ Generated metadata ------------------------------
PR-URL: https://github.com/nodejs/node/pull/64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
--------------------------------------------------------------------------------
ℹ This PR was created on Sun, 12 Jul 2026 08:27:10 GMT
✔ Approvals: 3
✔ - Gürgün Dayıoğlu (@gurgunday): https://github.com/nodejs/node/pull/64447#pullrequestreview-4707049635
✔ - Mattias Buelens (@MattiasBuelens): https://github.com/nodejs/node/pull/64447#pullrequestreview-4706259826
✔ - Robert Nagy (@ronag) (TSC): https://github.com/nodejs/node/pull/64447#pullrequestreview-4838491319
✔ Last GitHub CI successful
ℹ Last Full PR CI on 2026-08-06T13:07:45Z: https://ci.nodejs.org/job/node-test-pull-request/75563/
- Querying data for job/node-test-pull-request/75563/
✔ Build data downloaded
✔ Last Jenkins CI successful
--------------------------------------------------------------------------------
✔ No git cherry-pick in progress
✔ No git am in progress
✔ No git rebase in progress
--------------------------------------------------------------------------------
- Bringing origin/main up to date...
From https://github.com/nodejs/node
* branch main -> FETCH_HEAD
✔ origin/main is now up-to-date
- Downloading patch for 64447
From https://github.com/nodejs/node
* branch refs/pull/64447/merge -> FETCH_HEAD
✔ Fetched commits as 9e23066b8af4..873a47ef6ae8
--------------------------------------------------------------------------------
Auto-merging lib/internal/streams/readable.js
[main 0a0be7f763] stream: speed up async iteration of Readable
Author: Matteo Collina <hello@matteocollina.com>
Date: Sat Jul 11 23:41:55 2026 +0200
3 files changed, 307 insertions(+), 35 deletions(-)
Auto-merging lib/internal/streams/readable.js
[main 22401b1cb5] fixup: address review comments
Author: Matteo Collina <hello@matteocollina.com>
Date: Mon Jul 13 10:00:44 2026 +0200
3 files changed, 73 insertions(+), 26 deletions(-)
Auto-merging lib/internal/streams/readable.js
[main 0b186829dd] fixup: remove [SymbolAsyncIterator]
Author: Matteo Collina <hello@matteocollina.com>
Date: Wed Jul 15 17:34:22 2026 +0200
1 file changed, 1 insertion(+), 4 deletions(-)
Auto-merging lib/internal/streams/readable.js
[main 656bc697b3] stream: fix lint in readable async iterator
Author: Matteo Collina <hello@matteocollina.com>
Date: Sun Aug 2 09:08:31 2026 +0000
1 file changed, 1 insertion(+), 1 deletion(-)
✔ Patches applied
There are 4 commits in the PR. Attempting autorebase.
(node:388) [DEP0190] DeprecationWarning: Passing args to a child process with shell option true can lead to security vulnerabilities, as the arguments are not escaped, only concatenated.
(Use `node --trace-deprecation ...` to show where the warning was created)
Rebasing (2/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
stream: speed up async iteration of Readable

Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.

Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.

The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.

streams/readable-async-iterator.js sync='yes': +32.59% ()
streams/readable-async-iterator.js sync='no': +9.84% (
)

Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD 6e6bcb4f2f] stream: speed up async iteration of Readable
Author: Matteo Collina <hello@matteocollina.com>
Date: Sat Jul 11 23:41:55 2026 +0200
3 files changed, 307 insertions(+), 35 deletions(-)
Rebasing (3/8)
Rebasing (4/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
fixup: address review comments

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD a9e0e0ad92] fixup: address review comments
Author: Matteo Collina <hello@matteocollina.com>
Date: Mon Jul 13 10:00:44 2026 +0200
3 files changed, 73 insertions(+), 26 deletions(-)
Rebasing (5/8)
Rebasing (6/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
fixup: remove [SymbolAsyncIterator]

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD 0ea470ea7b] fixup: remove [SymbolAsyncIterator]
Author: Matteo Collina <hello@matteocollina.com>
Date: Wed Jul 15 17:34:22 2026 +0200
1 file changed, 1 insertion(+), 4 deletions(-)
Rebasing (7/8)
Rebasing (8/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
stream: fix lint in readable async iterator

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD 0d2b7c1daf] stream: fix lint in readable async iterator
Author: Matteo Collina <hello@matteocollina.com>
Date: Sun Aug 2 09:08:31 2026 +0000
1 file changed, 1 insertion(+), 1 deletion(-)
Successfully rebased and updated refs/heads/main.

ℹ Add commit-queue-squash label to land the PR as one commit, or commit-queue-rebase to land as separate commits.

https://github.com/nodejs/node/actions/runs/31846615170

@mcollinamcollina added commit-queue PRs queued for automated landing through the Commit Queue. commit-queue-squash PRs the Commit Queue should land as one squashed commit. and removed commit-queue-failed PRs whose Commit Queue landing failed and need manual intervention before retrying. labels Aug 14, 2026
@nodejs-github-bot
nodejs-github-bot merged commit 4551732 into nodejs:mainAug 14, 2026
86 checks passed
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Landed in 4551732

@nodejs-github-botnodejs-github-bot removed the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 14, 2026
aduh95 pushed a commit that referenced this pull request Aug 25, 2026
Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.
Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.
The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.
streams/readable-async-iterator.js sync='yes': +32.59% (***)
streams/readable-async-iterator.js sync='no': +9.84% (***)
Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
aduh95 pushed a commit that referenced this pull request Aug 25, 2026
Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.
Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.
The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.
streams/readable-async-iterator.js sync='yes': +32.59% (***)
streams/readable-async-iterator.js sync='no': +9.84% (***)
Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

author readyPRs with CI started, the required approvals, and no outstanding review comments.commit-queue-squashPRs the Commit Queue should land as one squashed commit.needs-ciPRs that need a full CI run.streamIssues and PRs related to Node.js streams.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants

@mcollina@nodejs-github-bot@jasnell@MattiasBuelens@ronag@Renegade334@aduh95@mertcanaltin@gurgunday
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

stream: speed up async iteration of Readable - #64447

Merged
nodejs-github-bot merged 4 commits into
nodejs:mainfrom
mcollina:stream-async-iterator-perf
Aug 14, 2026
Merged

stream: speed up async iteration of Readable#64447
nodejs-github-bot merged 4 commits into
nodejs:mainfrom
mcollina:stream-async-iterator-perf

Conversation

@mcollina

@mcollinamcollina commented Jul 12, 2026

Copy link
Copy Markdown
Member

Replace the async generator backing Readable.prototype[Symbol.asyncIterator] (and .iterator()) with a hand-rolled iterator.

The generator machinery costs several extra promise allocations and microtask hops per chunk: yield awaits the yielded value and resolves the pending request through separate promises, and every next() goes through the async generator request queue. The hand-rolled iterator delivers buffered chunks as an already-resolved promise.

The observable semantics are preserved:

  • thenable chunks (object mode) are still awaited before delivery, and a rejected thenable still tears down the iterator and the stream;
  • next()/return()/throw() calls received while a request is outstanding are queued and processed in order — including return() while waiting for data, which still completes only once the pending read settles;
  • return()/throw() before the first next() complete the iterator without attaching listeners or destroying the stream;
  • the finally teardown logic (destroyOnReturn, autoDestroy, half-open duplex preservation) is unchanged;
  • error aggregation via aggregateTwoErrors is unchanged.

The one observable difference is that buffered chunks are delivered one microtask sooner than before, since the generator's yield performed an implicit Await on the yielded value. This is visible to code racing an abort against the first chunk. The flatMap AbortSignal test relied on such a race (a queueMicrotask'd abort beating the first chunk); it is reworked to be deterministic and timer-free: two mappers block until their signal aborts, the abort fires while both are in flight, and the test asserts the concurrency limit is respected (exactly two mappers start), in-flight mappers are cancelled through their signal, and iteration rejects with AbortError. The reworked test passes against both the old and the new implementation.

New regression tests cover the subtler iterator behaviors (thenable unwrapping, rejected thenables, throw(), pre-start throw(), concurrent next() ordering, and return() queued behind a pending next()); they also pass against both implementations.

Benchmark (benchmark/compare.js, 30 runs):

 confidence improvement accuracy (*) (**) (***)
streams/readable-async-iterator.js sync='no' n=100000 *** 9.84 % ±3.04% ±4.05% ±5.27%
streams/readable-async-iterator.js sync='yes' n=100000 *** 32.59 % ±5.49% ±7.34% ±9.62%

No changes on pipe.js / readable-readall.js.

🤖 Generated with Claude Code

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Review requested:

  • @nodejs/streams

@nodejs-github-botnodejs-github-bot added needs-ci PRs that need a full CI run. stream Issues and PRs related to Node.js streams. labels Jul 12, 2026
Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.
Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.
The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.
streams/readable-async-iterator.js sync='yes': +32.59% (***)
streams/readable-async-iterator.js sync='no': +9.84% (***)
Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
@mcollina
mcollinaforce-pushed the stream-async-iterator-perf branch from 2307152 to 6f9a2f3CompareJuly 12, 2026 08:36
Comment threadlib/internal/streams/readable.js Outdated
Comment on lines +1486 to +1497
if (typeof chunk.then === 'function') {
PromisePrototypeThen(PromiseResolve(chunk), (value) => {
inFlight = false;
resolve({ done: false, value });
if (queue !== null) drain();
}, (err) => {
inFlight = false;
settleError(err, reject);
if (queue !== null) drain();
});
return;
}

@aduh95aduh95Jul 12, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If then is a getter that e.g. throws on the second access, this code might throw when previously it wouldn't have. We can protect against that by storing the initial value we're getting (that might also avoid an additional promise allocation).

Suggested change
if(typeofchunk.then==='function'){
PromisePrototypeThen(PromiseResolve(chunk),(value)=>{
inFlight=false;
resolve({done: false, value });
if(queue!==null)drain();
},(err)=>{
inFlight=false;
settleError(err,reject);
if(queue!==null)drain();
});
return;
}
const{ then }=chunk;
if(typeofthen==='function'){
FunctionPrototypeCall(then,chunk,(value)=>{
inFlight=false;
resolve({done: false, value });
if(queue!==null)drain();
},(err)=>{
inFlight=false;
settleError(err,reject);
if(queue!==null)drain();
});
return;
}

Comment threadlib/internal/streams/readable.js Outdated
Comment on lines +1555 to +1558
if (typeof chunk.then === 'function') {
inFlight = true;
return PromisePrototypeThen(
PromiseResolve(chunk), onChunkFulfilled, onChunkRejected);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here

Suggested change
if(typeofchunk.then==='function'){
inFlight=true;
returnPromisePrototypeThen(
PromiseResolve(chunk),onChunkFulfilled,onChunkRejected);
const{then }=chunk;
if(typeofthen==='function'){
inFlight=true;
returnFunctionPrototypeCall(then,chunk,onChunkFulfilled,onChunkRejected);

settleError(err, reject);
}

return {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This object should ideally have a prototype of AsyncIteratorPrototype.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure it should if the sprecs doesn't require it – it does add a @@asyncDispose method which may or may not be desirable – it also adds a @@asyncIterator, which begs the question whether we should re-implement the method (re-implementing it ourselves means we're not subject to prototype tampering; otherwise, letting the built-in method be inherited would saves a bit of memory maybe?)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current implementation derives from AsyncIteratorPrototype (as a generator) so if we're trying to minimise observability then this is a fairly free move. (While the language currently only provides for the two well-known symbol methods, once we get into async iterator helpers territory, there will be significant advantages to keeping this inheritance.)

@codecov

codecovBot commented Jul 12, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.23256% with 21 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.29%. Comparing base (8a3b11c) to head (873a47e).
⚠️ Report is 472 commits behind head on main.

Files with missing linesPatch %Lines
lib/internal/streams/readable.js90.23%20 Missing and 1 partial ⚠️
Additional details and impacted files
@@ Coverage Diff @@## main #64447 +/- ##
==========================================
+ Coverage 90.24% 90.29% +0.04% 
==========================================
Files 741 760 +19 Lines 241384 247324 +5940 Branches 45480 46652 +1172 ==========================================
+ Hits 217844 223310 +5466 - Misses 15097 15477 +380 - Partials 8443 8537 +94 
Files with missing linesCoverage Δ
lib/internal/streams/readable.js96.55% <90.23%> (-0.72%)⬇️

... and 209 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Comment threadlib/internal/streams/readable.js Outdated
return new Promise((resolve, reject) => {
if (inFlight) {
queue ??= [];
queue.push({ type: 'return', value, resolve, reject });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
queue.push({type: 'return', value, resolve, reject });
queue.push({__proto__: null,type: 'return', value, resolve, reject });

Comment threadlib/internal/streams/readable.js Outdated
return new Promise((resolve, reject) => {
if (inFlight) {
queue ??= [];
queue.push({ type: 'next', value: undefined, resolve, reject });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
queue.push({type: 'next',value: undefined, resolve, reject });
queue.push({__proto__: null,type: 'next',value: undefined, resolve, reject });

Comment threadlib/internal/streams/readable.js Outdated
return new Promise((resolve, reject) => {
if (inFlight) {
queue ??= [];
queue.push({ type: 'throw', value: err, resolve, reject });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
queue.push({type: 'throw',value: err, resolve, reject });
queue.push({__proto__: null,type: 'throw',value: err, resolve, reject });

Comment threadlib/internal/streams/readable.js Outdated

function drain() {
while (!inFlight && queue.length > 0) {
const req = queue.shift();

@mertcanaltinmertcanaltinJul 12, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we replace queue.shift(); with an index-based queue for high throughput?

Comment threadlib/internal/streams/readable.js Outdated
Comment threadlib/internal/streams/readable.js Outdated
Comment threadtest/parallel/test-stream-flatMap.js Outdated
Comment on lines +84 to +89
await new Promise((resolve, reject) => {
if (signal.aborted) {
reject(signal.reason);
return;
}
signal.addEventListener('abort', () => reject(signal.reason), { once: true });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
awaitnewPromise((resolve,reject)=>{
if(signal.aborted){
reject(signal.reason);
return;
}
signal.addEventListener('abort',()=>reject(signal.reason),{once: true});
const{ promise, reject }=Promise.withResolvers();
if(signal.aborted){
reject(signal.reason);
}
signal.addEventListener('abort',()=>reject(signal.reason),{once: true});
// Promise is expected to reject.
awaitpromise;

Signed-off-by: Matteo Collina <hello@matteocollina.com>

@gurgundaygurgunday left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@mcollinamcollina added the request-ci Add this label to start a Jenkins CI on a PR. label Jul 13, 2026
@github-actionsgithub-actionsBot removed the request-ci Add this label to start a Jenkins CI on a PR. label Jul 13, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Comment threadlib/internal/streams/readable.js Outdated
Signed-off-by: Matteo Collina <hello@matteocollina.com>
@mcollina

Copy link
Copy Markdown
MemberAuthor

@MattiasBuelens updated

@gurgundaygurgunday left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

Signed-off-by: Matteo Collina <hello@matteocollina.com>
@ronagronag added request-ci Add this label to start a Jenkins CI on a PR. author ready PRs with CI started, the required approvals, and no outstanding review comments. labels Aug 6, 2026
@github-actionsgithub-actionsBot removed the request-ci Add this label to start a Jenkins CI on a PR. label Aug 6, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@mcollinamcollina added the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 14, 2026
@nodejs-github-botnodejs-github-bot added commit-queue-failed PRs whose Commit Queue landing failed and need manual intervention before retrying. and removed commit-queue PRs queued for automated landing through the Commit Queue. labels Aug 14, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator
Commit Queue failed
- Loading data for nodejs/node/pull/64447
✔ Done loading data for nodejs/node/pull/64447
----------------------------------- PR info ------------------------------------
Title stream: speed up async iteration of Readable (#64447)
Author Matteo Collina <matteo.collina@gmail.com> (@mcollina)
Branch mcollina:stream-async-iterator-perf -> nodejs:main
Labels stream, author ready, needs-ci, commit-queue
Commits 4
- stream: speed up async iteration of Readable
- fixup: address review comments
- fixup: remove [SymbolAsyncIterator]
- stream: fix lint in readable async iterator
Committers 1
- Matteo Collina <hello@matteocollina.com>
PR-URL: https://github.com/nodejs/node/pull/64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
------------------------------ Generated metadata ------------------------------
PR-URL: https://github.com/nodejs/node/pull/64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
--------------------------------------------------------------------------------
ℹ This PR was created on Sun, 12 Jul 2026 08:27:10 GMT
✔ Approvals: 3
✔ - Gürgün Dayıoğlu (@gurgunday): https://github.com/nodejs/node/pull/64447#pullrequestreview-4707049635
✔ - Mattias Buelens (@MattiasBuelens): https://github.com/nodejs/node/pull/64447#pullrequestreview-4706259826
✔ - Robert Nagy (@ronag) (TSC): https://github.com/nodejs/node/pull/64447#pullrequestreview-4838491319
✔ Last GitHub CI successful
ℹ Last Full PR CI on 2026-08-06T13:07:45Z: https://ci.nodejs.org/job/node-test-pull-request/75563/
- Querying data for job/node-test-pull-request/75563/
✔ Build data downloaded
✔ Last Jenkins CI successful
--------------------------------------------------------------------------------
✔ No git cherry-pick in progress
✔ No git am in progress
✔ No git rebase in progress
--------------------------------------------------------------------------------
- Bringing origin/main up to date...
From https://github.com/nodejs/node
* branch main -> FETCH_HEAD
✔ origin/main is now up-to-date
- Downloading patch for 64447
From https://github.com/nodejs/node
* branch refs/pull/64447/merge -> FETCH_HEAD
✔ Fetched commits as 9e23066b8af4..873a47ef6ae8
--------------------------------------------------------------------------------
Auto-merging lib/internal/streams/readable.js
[main 0a0be7f763] stream: speed up async iteration of Readable
Author: Matteo Collina <hello@matteocollina.com>
Date: Sat Jul 11 23:41:55 2026 +0200
3 files changed, 307 insertions(+), 35 deletions(-)
Auto-merging lib/internal/streams/readable.js
[main 22401b1cb5] fixup: address review comments
Author: Matteo Collina <hello@matteocollina.com>
Date: Mon Jul 13 10:00:44 2026 +0200
3 files changed, 73 insertions(+), 26 deletions(-)
Auto-merging lib/internal/streams/readable.js
[main 0b186829dd] fixup: remove [SymbolAsyncIterator]
Author: Matteo Collina <hello@matteocollina.com>
Date: Wed Jul 15 17:34:22 2026 +0200
1 file changed, 1 insertion(+), 4 deletions(-)
Auto-merging lib/internal/streams/readable.js
[main 656bc697b3] stream: fix lint in readable async iterator
Author: Matteo Collina <hello@matteocollina.com>
Date: Sun Aug 2 09:08:31 2026 +0000
1 file changed, 1 insertion(+), 1 deletion(-)
✔ Patches applied
There are 4 commits in the PR. Attempting autorebase.
(node:388) [DEP0190] DeprecationWarning: Passing args to a child process with shell option true can lead to security vulnerabilities, as the arguments are not escaped, only concatenated.
(Use `node --trace-deprecation ...` to show where the warning was created)
Rebasing (2/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
stream: speed up async iteration of Readable

Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.

Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.

The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.

streams/readable-async-iterator.js sync='yes': +32.59% ()
streams/readable-async-iterator.js sync='no': +9.84% (
)

Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD 6e6bcb4f2f] stream: speed up async iteration of Readable
Author: Matteo Collina <hello@matteocollina.com>
Date: Sat Jul 11 23:41:55 2026 +0200
3 files changed, 307 insertions(+), 35 deletions(-)
Rebasing (3/8)
Rebasing (4/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
fixup: address review comments

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD a9e0e0ad92] fixup: address review comments
Author: Matteo Collina <hello@matteocollina.com>
Date: Mon Jul 13 10:00:44 2026 +0200
3 files changed, 73 insertions(+), 26 deletions(-)
Rebasing (5/8)
Rebasing (6/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
fixup: remove [SymbolAsyncIterator]

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD 0ea470ea7b] fixup: remove [SymbolAsyncIterator]
Author: Matteo Collina <hello@matteocollina.com>
Date: Wed Jul 15 17:34:22 2026 +0200
1 file changed, 1 insertion(+), 4 deletions(-)
Rebasing (7/8)
Rebasing (8/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
stream: fix lint in readable async iterator

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD 0d2b7c1daf] stream: fix lint in readable async iterator
Author: Matteo Collina <hello@matteocollina.com>
Date: Sun Aug 2 09:08:31 2026 +0000
1 file changed, 1 insertion(+), 1 deletion(-)
Successfully rebased and updated refs/heads/main.

ℹ Add commit-queue-squash label to land the PR as one commit, or commit-queue-rebase to land as separate commits.

https://github.com/nodejs/node/actions/runs/31846615170

@mcollinamcollina added commit-queue PRs queued for automated landing through the Commit Queue. commit-queue-squash PRs the Commit Queue should land as one squashed commit. and removed commit-queue-failed PRs whose Commit Queue landing failed and need manual intervention before retrying. labels Aug 14, 2026
@nodejs-github-bot
nodejs-github-bot merged commit 4551732 into nodejs:mainAug 14, 2026
86 checks passed
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Landed in 4551732

@nodejs-github-botnodejs-github-bot removed the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 14, 2026
aduh95 pushed a commit that referenced this pull request Aug 25, 2026
Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.
Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.
The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.
streams/readable-async-iterator.js sync='yes': +32.59% (***)
streams/readable-async-iterator.js sync='no': +9.84% (***)
Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
aduh95 pushed a commit that referenced this pull request Aug 25, 2026
Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.
Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.
The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.
streams/readable-async-iterator.js sync='yes': +32.59% (***)
streams/readable-async-iterator.js sync='no': +9.84% (***)
Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

author readyPRs with CI started, the required approvals, and no outstanding review comments.commit-queue-squashPRs the Commit Queue should land as one squashed commit.needs-ciPRs that need a full CI run.streamIssues and PRs related to Node.js streams.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants

@mcollina@nodejs-github-bot@jasnell@MattiasBuelens@ronag@Renegade334@aduh95@mertcanaltin@gurgunday
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

stream: speed up async iteration of Readable - #64447

Merged
nodejs-github-bot merged 4 commits into
nodejs:mainfrom
mcollina:stream-async-iterator-perf
Aug 14, 2026
Merged

stream: speed up async iteration of Readable#64447
nodejs-github-bot merged 4 commits into
nodejs:mainfrom
mcollina:stream-async-iterator-perf

Conversation

@mcollina

@mcollinamcollina commented Jul 12, 2026

Copy link
Copy Markdown
Member

Replace the async generator backing Readable.prototype[Symbol.asyncIterator] (and .iterator()) with a hand-rolled iterator.

The generator machinery costs several extra promise allocations and microtask hops per chunk: yield awaits the yielded value and resolves the pending request through separate promises, and every next() goes through the async generator request queue. The hand-rolled iterator delivers buffered chunks as an already-resolved promise.

The observable semantics are preserved:

  • thenable chunks (object mode) are still awaited before delivery, and a rejected thenable still tears down the iterator and the stream;
  • next()/return()/throw() calls received while a request is outstanding are queued and processed in order — including return() while waiting for data, which still completes only once the pending read settles;
  • return()/throw() before the first next() complete the iterator without attaching listeners or destroying the stream;
  • the finally teardown logic (destroyOnReturn, autoDestroy, half-open duplex preservation) is unchanged;
  • error aggregation via aggregateTwoErrors is unchanged.

The one observable difference is that buffered chunks are delivered one microtask sooner than before, since the generator's yield performed an implicit Await on the yielded value. This is visible to code racing an abort against the first chunk. The flatMap AbortSignal test relied on such a race (a queueMicrotask'd abort beating the first chunk); it is reworked to be deterministic and timer-free: two mappers block until their signal aborts, the abort fires while both are in flight, and the test asserts the concurrency limit is respected (exactly two mappers start), in-flight mappers are cancelled through their signal, and iteration rejects with AbortError. The reworked test passes against both the old and the new implementation.

New regression tests cover the subtler iterator behaviors (thenable unwrapping, rejected thenables, throw(), pre-start throw(), concurrent next() ordering, and return() queued behind a pending next()); they also pass against both implementations.

Benchmark (benchmark/compare.js, 30 runs):

 confidence improvement accuracy (*) (**) (***)
streams/readable-async-iterator.js sync='no' n=100000 *** 9.84 % ±3.04% ±4.05% ±5.27%
streams/readable-async-iterator.js sync='yes' n=100000 *** 32.59 % ±5.49% ±7.34% ±9.62%

No changes on pipe.js / readable-readall.js.

🤖 Generated with Claude Code

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Review requested:

  • @nodejs/streams

@nodejs-github-botnodejs-github-bot added needs-ci PRs that need a full CI run. stream Issues and PRs related to Node.js streams. labels Jul 12, 2026
Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.
Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.
The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.
streams/readable-async-iterator.js sync='yes': +32.59% (***)
streams/readable-async-iterator.js sync='no': +9.84% (***)
Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
@mcollina
mcollinaforce-pushed the stream-async-iterator-perf branch from 2307152 to 6f9a2f3CompareJuly 12, 2026 08:36
Comment threadlib/internal/streams/readable.js Outdated
Comment on lines +1486 to +1497
if (typeof chunk.then === 'function') {
PromisePrototypeThen(PromiseResolve(chunk), (value) => {
inFlight = false;
resolve({ done: false, value });
if (queue !== null) drain();
}, (err) => {
inFlight = false;
settleError(err, reject);
if (queue !== null) drain();
});
return;
}

@aduh95aduh95Jul 12, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If then is a getter that e.g. throws on the second access, this code might throw when previously it wouldn't have. We can protect against that by storing the initial value we're getting (that might also avoid an additional promise allocation).

Suggested change
if(typeofchunk.then==='function'){
PromisePrototypeThen(PromiseResolve(chunk),(value)=>{
inFlight=false;
resolve({done: false, value });
if(queue!==null)drain();
},(err)=>{
inFlight=false;
settleError(err,reject);
if(queue!==null)drain();
});
return;
}
const{ then }=chunk;
if(typeofthen==='function'){
FunctionPrototypeCall(then,chunk,(value)=>{
inFlight=false;
resolve({done: false, value });
if(queue!==null)drain();
},(err)=>{
inFlight=false;
settleError(err,reject);
if(queue!==null)drain();
});
return;
}

Comment threadlib/internal/streams/readable.js Outdated
Comment on lines +1555 to +1558
if (typeof chunk.then === 'function') {
inFlight = true;
return PromisePrototypeThen(
PromiseResolve(chunk), onChunkFulfilled, onChunkRejected);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here

Suggested change
if(typeofchunk.then==='function'){
inFlight=true;
returnPromisePrototypeThen(
PromiseResolve(chunk),onChunkFulfilled,onChunkRejected);
const{then }=chunk;
if(typeofthen==='function'){
inFlight=true;
returnFunctionPrototypeCall(then,chunk,onChunkFulfilled,onChunkRejected);

settleError(err, reject);
}

return {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This object should ideally have a prototype of AsyncIteratorPrototype.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure it should if the sprecs doesn't require it – it does add a @@asyncDispose method which may or may not be desirable – it also adds a @@asyncIterator, which begs the question whether we should re-implement the method (re-implementing it ourselves means we're not subject to prototype tampering; otherwise, letting the built-in method be inherited would saves a bit of memory maybe?)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current implementation derives from AsyncIteratorPrototype (as a generator) so if we're trying to minimise observability then this is a fairly free move. (While the language currently only provides for the two well-known symbol methods, once we get into async iterator helpers territory, there will be significant advantages to keeping this inheritance.)

@codecov

codecovBot commented Jul 12, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.23256% with 21 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.29%. Comparing base (8a3b11c) to head (873a47e).
⚠️ Report is 472 commits behind head on main.

Files with missing linesPatch %Lines
lib/internal/streams/readable.js90.23%20 Missing and 1 partial ⚠️
Additional details and impacted files
@@ Coverage Diff @@## main #64447 +/- ##
==========================================
+ Coverage 90.24% 90.29% +0.04% 
==========================================
Files 741 760 +19 Lines 241384 247324 +5940 Branches 45480 46652 +1172 ==========================================
+ Hits 217844 223310 +5466 - Misses 15097 15477 +380 - Partials 8443 8537 +94 
Files with missing linesCoverage Δ
lib/internal/streams/readable.js96.55% <90.23%> (-0.72%)⬇️

... and 209 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Comment threadlib/internal/streams/readable.js Outdated
return new Promise((resolve, reject) => {
if (inFlight) {
queue ??= [];
queue.push({ type: 'return', value, resolve, reject });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
queue.push({type: 'return', value, resolve, reject });
queue.push({__proto__: null,type: 'return', value, resolve, reject });

Comment threadlib/internal/streams/readable.js Outdated
return new Promise((resolve, reject) => {
if (inFlight) {
queue ??= [];
queue.push({ type: 'next', value: undefined, resolve, reject });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
queue.push({type: 'next',value: undefined, resolve, reject });
queue.push({__proto__: null,type: 'next',value: undefined, resolve, reject });

Comment threadlib/internal/streams/readable.js Outdated
return new Promise((resolve, reject) => {
if (inFlight) {
queue ??= [];
queue.push({ type: 'throw', value: err, resolve, reject });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
queue.push({type: 'throw',value: err, resolve, reject });
queue.push({__proto__: null,type: 'throw',value: err, resolve, reject });

Comment threadlib/internal/streams/readable.js Outdated

function drain() {
while (!inFlight && queue.length > 0) {
const req = queue.shift();

@mertcanaltinmertcanaltinJul 12, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we replace queue.shift(); with an index-based queue for high throughput?

Comment threadlib/internal/streams/readable.js Outdated
Comment threadlib/internal/streams/readable.js Outdated
Comment threadtest/parallel/test-stream-flatMap.js Outdated
Comment on lines +84 to +89
await new Promise((resolve, reject) => {
if (signal.aborted) {
reject(signal.reason);
return;
}
signal.addEventListener('abort', () => reject(signal.reason), { once: true });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
awaitnewPromise((resolve,reject)=>{
if(signal.aborted){
reject(signal.reason);
return;
}
signal.addEventListener('abort',()=>reject(signal.reason),{once: true});
const{ promise, reject }=Promise.withResolvers();
if(signal.aborted){
reject(signal.reason);
}
signal.addEventListener('abort',()=>reject(signal.reason),{once: true});
// Promise is expected to reject.
awaitpromise;

Signed-off-by: Matteo Collina <hello@matteocollina.com>

@gurgundaygurgunday left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@mcollinamcollina added the request-ci Add this label to start a Jenkins CI on a PR. label Jul 13, 2026
@github-actionsgithub-actionsBot removed the request-ci Add this label to start a Jenkins CI on a PR. label Jul 13, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Comment threadlib/internal/streams/readable.js Outdated
Signed-off-by: Matteo Collina <hello@matteocollina.com>
@mcollina

Copy link
Copy Markdown
MemberAuthor

@MattiasBuelens updated

@gurgundaygurgunday left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

Signed-off-by: Matteo Collina <hello@matteocollina.com>
@ronagronag added request-ci Add this label to start a Jenkins CI on a PR. author ready PRs with CI started, the required approvals, and no outstanding review comments. labels Aug 6, 2026
@github-actionsgithub-actionsBot removed the request-ci Add this label to start a Jenkins CI on a PR. label Aug 6, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@mcollinamcollina added the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 14, 2026
@nodejs-github-botnodejs-github-bot added commit-queue-failed PRs whose Commit Queue landing failed and need manual intervention before retrying. and removed commit-queue PRs queued for automated landing through the Commit Queue. labels Aug 14, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator
Commit Queue failed
- Loading data for nodejs/node/pull/64447
✔ Done loading data for nodejs/node/pull/64447
----------------------------------- PR info ------------------------------------
Title stream: speed up async iteration of Readable (#64447)
Author Matteo Collina <matteo.collina@gmail.com> (@mcollina)
Branch mcollina:stream-async-iterator-perf -> nodejs:main
Labels stream, author ready, needs-ci, commit-queue
Commits 4
- stream: speed up async iteration of Readable
- fixup: address review comments
- fixup: remove [SymbolAsyncIterator]
- stream: fix lint in readable async iterator
Committers 1
- Matteo Collina <hello@matteocollina.com>
PR-URL: https://github.com/nodejs/node/pull/64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
------------------------------ Generated metadata ------------------------------
PR-URL: https://github.com/nodejs/node/pull/64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
--------------------------------------------------------------------------------
ℹ This PR was created on Sun, 12 Jul 2026 08:27:10 GMT
✔ Approvals: 3
✔ - Gürgün Dayıoğlu (@gurgunday): https://github.com/nodejs/node/pull/64447#pullrequestreview-4707049635
✔ - Mattias Buelens (@MattiasBuelens): https://github.com/nodejs/node/pull/64447#pullrequestreview-4706259826
✔ - Robert Nagy (@ronag) (TSC): https://github.com/nodejs/node/pull/64447#pullrequestreview-4838491319
✔ Last GitHub CI successful
ℹ Last Full PR CI on 2026-08-06T13:07:45Z: https://ci.nodejs.org/job/node-test-pull-request/75563/
- Querying data for job/node-test-pull-request/75563/
✔ Build data downloaded
✔ Last Jenkins CI successful
--------------------------------------------------------------------------------
✔ No git cherry-pick in progress
✔ No git am in progress
✔ No git rebase in progress
--------------------------------------------------------------------------------
- Bringing origin/main up to date...
From https://github.com/nodejs/node
* branch main -> FETCH_HEAD
✔ origin/main is now up-to-date
- Downloading patch for 64447
From https://github.com/nodejs/node
* branch refs/pull/64447/merge -> FETCH_HEAD
✔ Fetched commits as 9e23066b8af4..873a47ef6ae8
--------------------------------------------------------------------------------
Auto-merging lib/internal/streams/readable.js
[main 0a0be7f763] stream: speed up async iteration of Readable
Author: Matteo Collina <hello@matteocollina.com>
Date: Sat Jul 11 23:41:55 2026 +0200
3 files changed, 307 insertions(+), 35 deletions(-)
Auto-merging lib/internal/streams/readable.js
[main 22401b1cb5] fixup: address review comments
Author: Matteo Collina <hello@matteocollina.com>
Date: Mon Jul 13 10:00:44 2026 +0200
3 files changed, 73 insertions(+), 26 deletions(-)
Auto-merging lib/internal/streams/readable.js
[main 0b186829dd] fixup: remove [SymbolAsyncIterator]
Author: Matteo Collina <hello@matteocollina.com>
Date: Wed Jul 15 17:34:22 2026 +0200
1 file changed, 1 insertion(+), 4 deletions(-)
Auto-merging lib/internal/streams/readable.js
[main 656bc697b3] stream: fix lint in readable async iterator
Author: Matteo Collina <hello@matteocollina.com>
Date: Sun Aug 2 09:08:31 2026 +0000
1 file changed, 1 insertion(+), 1 deletion(-)
✔ Patches applied
There are 4 commits in the PR. Attempting autorebase.
(node:388) [DEP0190] DeprecationWarning: Passing args to a child process with shell option true can lead to security vulnerabilities, as the arguments are not escaped, only concatenated.
(Use `node --trace-deprecation ...` to show where the warning was created)
Rebasing (2/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
stream: speed up async iteration of Readable

Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.

Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.

The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.

streams/readable-async-iterator.js sync='yes': +32.59% ()
streams/readable-async-iterator.js sync='no': +9.84% (
)

Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD 6e6bcb4f2f] stream: speed up async iteration of Readable
Author: Matteo Collina <hello@matteocollina.com>
Date: Sat Jul 11 23:41:55 2026 +0200
3 files changed, 307 insertions(+), 35 deletions(-)
Rebasing (3/8)
Rebasing (4/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
fixup: address review comments

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD a9e0e0ad92] fixup: address review comments
Author: Matteo Collina <hello@matteocollina.com>
Date: Mon Jul 13 10:00:44 2026 +0200
3 files changed, 73 insertions(+), 26 deletions(-)
Rebasing (5/8)
Rebasing (6/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
fixup: remove [SymbolAsyncIterator]

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD 0ea470ea7b] fixup: remove [SymbolAsyncIterator]
Author: Matteo Collina <hello@matteocollina.com>
Date: Wed Jul 15 17:34:22 2026 +0200
1 file changed, 1 insertion(+), 4 deletions(-)
Rebasing (7/8)
Rebasing (8/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
stream: fix lint in readable async iterator

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD 0d2b7c1daf] stream: fix lint in readable async iterator
Author: Matteo Collina <hello@matteocollina.com>
Date: Sun Aug 2 09:08:31 2026 +0000
1 file changed, 1 insertion(+), 1 deletion(-)
Successfully rebased and updated refs/heads/main.

ℹ Add commit-queue-squash label to land the PR as one commit, or commit-queue-rebase to land as separate commits.

https://github.com/nodejs/node/actions/runs/31846615170

@mcollinamcollina added commit-queue PRs queued for automated landing through the Commit Queue. commit-queue-squash PRs the Commit Queue should land as one squashed commit. and removed commit-queue-failed PRs whose Commit Queue landing failed and need manual intervention before retrying. labels Aug 14, 2026
@nodejs-github-bot
nodejs-github-bot merged commit 4551732 into nodejs:mainAug 14, 2026
86 checks passed
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Landed in 4551732

@nodejs-github-botnodejs-github-bot removed the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 14, 2026
aduh95 pushed a commit that referenced this pull request Aug 25, 2026
Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.
Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.
The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.
streams/readable-async-iterator.js sync='yes': +32.59% (***)
streams/readable-async-iterator.js sync='no': +9.84% (***)
Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
aduh95 pushed a commit that referenced this pull request Aug 25, 2026
Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.
Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.
The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.
streams/readable-async-iterator.js sync='yes': +32.59% (***)
streams/readable-async-iterator.js sync='no': +9.84% (***)
Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

author readyPRs with CI started, the required approvals, and no outstanding review comments.commit-queue-squashPRs the Commit Queue should land as one squashed commit.needs-ciPRs that need a full CI run.streamIssues and PRs related to Node.js streams.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants

@mcollina@nodejs-github-bot@jasnell@MattiasBuelens@ronag@Renegade334@aduh95@mertcanaltin@gurgunday
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

stream: speed up async iteration of Readable - #64447

Merged
nodejs-github-bot merged 4 commits into
nodejs:mainfrom
mcollina:stream-async-iterator-perf
Aug 14, 2026
Merged

stream: speed up async iteration of Readable#64447
nodejs-github-bot merged 4 commits into
nodejs:mainfrom
mcollina:stream-async-iterator-perf

Conversation

@mcollina

@mcollinamcollina commented Jul 12, 2026

Copy link
Copy Markdown
Member

Replace the async generator backing Readable.prototype[Symbol.asyncIterator] (and .iterator()) with a hand-rolled iterator.

The generator machinery costs several extra promise allocations and microtask hops per chunk: yield awaits the yielded value and resolves the pending request through separate promises, and every next() goes through the async generator request queue. The hand-rolled iterator delivers buffered chunks as an already-resolved promise.

The observable semantics are preserved:

  • thenable chunks (object mode) are still awaited before delivery, and a rejected thenable still tears down the iterator and the stream;
  • next()/return()/throw() calls received while a request is outstanding are queued and processed in order — including return() while waiting for data, which still completes only once the pending read settles;
  • return()/throw() before the first next() complete the iterator without attaching listeners or destroying the stream;
  • the finally teardown logic (destroyOnReturn, autoDestroy, half-open duplex preservation) is unchanged;
  • error aggregation via aggregateTwoErrors is unchanged.

The one observable difference is that buffered chunks are delivered one microtask sooner than before, since the generator's yield performed an implicit Await on the yielded value. This is visible to code racing an abort against the first chunk. The flatMap AbortSignal test relied on such a race (a queueMicrotask'd abort beating the first chunk); it is reworked to be deterministic and timer-free: two mappers block until their signal aborts, the abort fires while both are in flight, and the test asserts the concurrency limit is respected (exactly two mappers start), in-flight mappers are cancelled through their signal, and iteration rejects with AbortError. The reworked test passes against both the old and the new implementation.

New regression tests cover the subtler iterator behaviors (thenable unwrapping, rejected thenables, throw(), pre-start throw(), concurrent next() ordering, and return() queued behind a pending next()); they also pass against both implementations.

Benchmark (benchmark/compare.js, 30 runs):

 confidence improvement accuracy (*) (**) (***)
streams/readable-async-iterator.js sync='no' n=100000 *** 9.84 % ±3.04% ±4.05% ±5.27%
streams/readable-async-iterator.js sync='yes' n=100000 *** 32.59 % ±5.49% ±7.34% ±9.62%

No changes on pipe.js / readable-readall.js.

🤖 Generated with Claude Code

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Review requested:

  • @nodejs/streams

@nodejs-github-botnodejs-github-bot added needs-ci PRs that need a full CI run. stream Issues and PRs related to Node.js streams. labels Jul 12, 2026
Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.
Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.
The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.
streams/readable-async-iterator.js sync='yes': +32.59% (***)
streams/readable-async-iterator.js sync='no': +9.84% (***)
Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
@mcollina
mcollinaforce-pushed the stream-async-iterator-perf branch from 2307152 to 6f9a2f3CompareJuly 12, 2026 08:36
Comment threadlib/internal/streams/readable.js Outdated
Comment on lines +1486 to +1497
if (typeof chunk.then === 'function') {
PromisePrototypeThen(PromiseResolve(chunk), (value) => {
inFlight = false;
resolve({ done: false, value });
if (queue !== null) drain();
}, (err) => {
inFlight = false;
settleError(err, reject);
if (queue !== null) drain();
});
return;
}

@aduh95aduh95Jul 12, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If then is a getter that e.g. throws on the second access, this code might throw when previously it wouldn't have. We can protect against that by storing the initial value we're getting (that might also avoid an additional promise allocation).

Suggested change
if(typeofchunk.then==='function'){
PromisePrototypeThen(PromiseResolve(chunk),(value)=>{
inFlight=false;
resolve({done: false, value });
if(queue!==null)drain();
},(err)=>{
inFlight=false;
settleError(err,reject);
if(queue!==null)drain();
});
return;
}
const{ then }=chunk;
if(typeofthen==='function'){
FunctionPrototypeCall(then,chunk,(value)=>{
inFlight=false;
resolve({done: false, value });
if(queue!==null)drain();
},(err)=>{
inFlight=false;
settleError(err,reject);
if(queue!==null)drain();
});
return;
}

Comment threadlib/internal/streams/readable.js Outdated
Comment on lines +1555 to +1558
if (typeof chunk.then === 'function') {
inFlight = true;
return PromisePrototypeThen(
PromiseResolve(chunk), onChunkFulfilled, onChunkRejected);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here

Suggested change
if(typeofchunk.then==='function'){
inFlight=true;
returnPromisePrototypeThen(
PromiseResolve(chunk),onChunkFulfilled,onChunkRejected);
const{then }=chunk;
if(typeofthen==='function'){
inFlight=true;
returnFunctionPrototypeCall(then,chunk,onChunkFulfilled,onChunkRejected);

settleError(err, reject);
}

return {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This object should ideally have a prototype of AsyncIteratorPrototype.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure it should if the sprecs doesn't require it – it does add a @@asyncDispose method which may or may not be desirable – it also adds a @@asyncIterator, which begs the question whether we should re-implement the method (re-implementing it ourselves means we're not subject to prototype tampering; otherwise, letting the built-in method be inherited would saves a bit of memory maybe?)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current implementation derives from AsyncIteratorPrototype (as a generator) so if we're trying to minimise observability then this is a fairly free move. (While the language currently only provides for the two well-known symbol methods, once we get into async iterator helpers territory, there will be significant advantages to keeping this inheritance.)

@codecov

codecovBot commented Jul 12, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.23256% with 21 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.29%. Comparing base (8a3b11c) to head (873a47e).
⚠️ Report is 472 commits behind head on main.

Files with missing linesPatch %Lines
lib/internal/streams/readable.js90.23%20 Missing and 1 partial ⚠️
Additional details and impacted files
@@ Coverage Diff @@## main #64447 +/- ##
==========================================
+ Coverage 90.24% 90.29% +0.04% 
==========================================
Files 741 760 +19 Lines 241384 247324 +5940 Branches 45480 46652 +1172 ==========================================
+ Hits 217844 223310 +5466 - Misses 15097 15477 +380 - Partials 8443 8537 +94 
Files with missing linesCoverage Δ
lib/internal/streams/readable.js96.55% <90.23%> (-0.72%)⬇️

... and 209 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Comment threadlib/internal/streams/readable.js Outdated
return new Promise((resolve, reject) => {
if (inFlight) {
queue ??= [];
queue.push({ type: 'return', value, resolve, reject });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
queue.push({type: 'return', value, resolve, reject });
queue.push({__proto__: null,type: 'return', value, resolve, reject });

Comment threadlib/internal/streams/readable.js Outdated
return new Promise((resolve, reject) => {
if (inFlight) {
queue ??= [];
queue.push({ type: 'next', value: undefined, resolve, reject });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
queue.push({type: 'next',value: undefined, resolve, reject });
queue.push({__proto__: null,type: 'next',value: undefined, resolve, reject });

Comment threadlib/internal/streams/readable.js Outdated
return new Promise((resolve, reject) => {
if (inFlight) {
queue ??= [];
queue.push({ type: 'throw', value: err, resolve, reject });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
queue.push({type: 'throw',value: err, resolve, reject });
queue.push({__proto__: null,type: 'throw',value: err, resolve, reject });

Comment threadlib/internal/streams/readable.js Outdated

function drain() {
while (!inFlight && queue.length > 0) {
const req = queue.shift();

@mertcanaltinmertcanaltinJul 12, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we replace queue.shift(); with an index-based queue for high throughput?

Comment threadlib/internal/streams/readable.js Outdated
Comment threadlib/internal/streams/readable.js Outdated
Comment threadtest/parallel/test-stream-flatMap.js Outdated
Comment on lines +84 to +89
await new Promise((resolve, reject) => {
if (signal.aborted) {
reject(signal.reason);
return;
}
signal.addEventListener('abort', () => reject(signal.reason), { once: true });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
awaitnewPromise((resolve,reject)=>{
if(signal.aborted){
reject(signal.reason);
return;
}
signal.addEventListener('abort',()=>reject(signal.reason),{once: true});
const{ promise, reject }=Promise.withResolvers();
if(signal.aborted){
reject(signal.reason);
}
signal.addEventListener('abort',()=>reject(signal.reason),{once: true});
// Promise is expected to reject.
awaitpromise;

Signed-off-by: Matteo Collina <hello@matteocollina.com>

@gurgundaygurgunday left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@mcollinamcollina added the request-ci Add this label to start a Jenkins CI on a PR. label Jul 13, 2026
@github-actionsgithub-actionsBot removed the request-ci Add this label to start a Jenkins CI on a PR. label Jul 13, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Comment threadlib/internal/streams/readable.js Outdated
Signed-off-by: Matteo Collina <hello@matteocollina.com>
@mcollina

Copy link
Copy Markdown
MemberAuthor

@MattiasBuelens updated

@gurgundaygurgunday left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

Signed-off-by: Matteo Collina <hello@matteocollina.com>
@ronagronag added request-ci Add this label to start a Jenkins CI on a PR. author ready PRs with CI started, the required approvals, and no outstanding review comments. labels Aug 6, 2026
@github-actionsgithub-actionsBot removed the request-ci Add this label to start a Jenkins CI on a PR. label Aug 6, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@mcollinamcollina added the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 14, 2026
@nodejs-github-botnodejs-github-bot added commit-queue-failed PRs whose Commit Queue landing failed and need manual intervention before retrying. and removed commit-queue PRs queued for automated landing through the Commit Queue. labels Aug 14, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator
Commit Queue failed
- Loading data for nodejs/node/pull/64447
✔ Done loading data for nodejs/node/pull/64447
----------------------------------- PR info ------------------------------------
Title stream: speed up async iteration of Readable (#64447)
Author Matteo Collina <matteo.collina@gmail.com> (@mcollina)
Branch mcollina:stream-async-iterator-perf -> nodejs:main
Labels stream, author ready, needs-ci, commit-queue
Commits 4
- stream: speed up async iteration of Readable
- fixup: address review comments
- fixup: remove [SymbolAsyncIterator]
- stream: fix lint in readable async iterator
Committers 1
- Matteo Collina <hello@matteocollina.com>
PR-URL: https://github.com/nodejs/node/pull/64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
------------------------------ Generated metadata ------------------------------
PR-URL: https://github.com/nodejs/node/pull/64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
--------------------------------------------------------------------------------
ℹ This PR was created on Sun, 12 Jul 2026 08:27:10 GMT
✔ Approvals: 3
✔ - Gürgün Dayıoğlu (@gurgunday): https://github.com/nodejs/node/pull/64447#pullrequestreview-4707049635
✔ - Mattias Buelens (@MattiasBuelens): https://github.com/nodejs/node/pull/64447#pullrequestreview-4706259826
✔ - Robert Nagy (@ronag) (TSC): https://github.com/nodejs/node/pull/64447#pullrequestreview-4838491319
✔ Last GitHub CI successful
ℹ Last Full PR CI on 2026-08-06T13:07:45Z: https://ci.nodejs.org/job/node-test-pull-request/75563/
- Querying data for job/node-test-pull-request/75563/
✔ Build data downloaded
✔ Last Jenkins CI successful
--------------------------------------------------------------------------------
✔ No git cherry-pick in progress
✔ No git am in progress
✔ No git rebase in progress
--------------------------------------------------------------------------------
- Bringing origin/main up to date...
From https://github.com/nodejs/node
* branch main -> FETCH_HEAD
✔ origin/main is now up-to-date
- Downloading patch for 64447
From https://github.com/nodejs/node
* branch refs/pull/64447/merge -> FETCH_HEAD
✔ Fetched commits as 9e23066b8af4..873a47ef6ae8
--------------------------------------------------------------------------------
Auto-merging lib/internal/streams/readable.js
[main 0a0be7f763] stream: speed up async iteration of Readable
Author: Matteo Collina <hello@matteocollina.com>
Date: Sat Jul 11 23:41:55 2026 +0200
3 files changed, 307 insertions(+), 35 deletions(-)
Auto-merging lib/internal/streams/readable.js
[main 22401b1cb5] fixup: address review comments
Author: Matteo Collina <hello@matteocollina.com>
Date: Mon Jul 13 10:00:44 2026 +0200
3 files changed, 73 insertions(+), 26 deletions(-)
Auto-merging lib/internal/streams/readable.js
[main 0b186829dd] fixup: remove [SymbolAsyncIterator]
Author: Matteo Collina <hello@matteocollina.com>
Date: Wed Jul 15 17:34:22 2026 +0200
1 file changed, 1 insertion(+), 4 deletions(-)
Auto-merging lib/internal/streams/readable.js
[main 656bc697b3] stream: fix lint in readable async iterator
Author: Matteo Collina <hello@matteocollina.com>
Date: Sun Aug 2 09:08:31 2026 +0000
1 file changed, 1 insertion(+), 1 deletion(-)
✔ Patches applied
There are 4 commits in the PR. Attempting autorebase.
(node:388) [DEP0190] DeprecationWarning: Passing args to a child process with shell option true can lead to security vulnerabilities, as the arguments are not escaped, only concatenated.
(Use `node --trace-deprecation ...` to show where the warning was created)
Rebasing (2/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
stream: speed up async iteration of Readable

Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.

Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.

The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.

streams/readable-async-iterator.js sync='yes': +32.59% ()
streams/readable-async-iterator.js sync='no': +9.84% (
)

Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD 6e6bcb4f2f] stream: speed up async iteration of Readable
Author: Matteo Collina <hello@matteocollina.com>
Date: Sat Jul 11 23:41:55 2026 +0200
3 files changed, 307 insertions(+), 35 deletions(-)
Rebasing (3/8)
Rebasing (4/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
fixup: address review comments

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD a9e0e0ad92] fixup: address review comments
Author: Matteo Collina <hello@matteocollina.com>
Date: Mon Jul 13 10:00:44 2026 +0200
3 files changed, 73 insertions(+), 26 deletions(-)
Rebasing (5/8)
Rebasing (6/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
fixup: remove [SymbolAsyncIterator]

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD 0ea470ea7b] fixup: remove [SymbolAsyncIterator]
Author: Matteo Collina <hello@matteocollina.com>
Date: Wed Jul 15 17:34:22 2026 +0200
1 file changed, 1 insertion(+), 4 deletions(-)
Rebasing (7/8)
Rebasing (8/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
stream: fix lint in readable async iterator

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD 0d2b7c1daf] stream: fix lint in readable async iterator
Author: Matteo Collina <hello@matteocollina.com>
Date: Sun Aug 2 09:08:31 2026 +0000
1 file changed, 1 insertion(+), 1 deletion(-)
Successfully rebased and updated refs/heads/main.

ℹ Add commit-queue-squash label to land the PR as one commit, or commit-queue-rebase to land as separate commits.

https://github.com/nodejs/node/actions/runs/31846615170

@mcollinamcollina added commit-queue PRs queued for automated landing through the Commit Queue. commit-queue-squash PRs the Commit Queue should land as one squashed commit. and removed commit-queue-failed PRs whose Commit Queue landing failed and need manual intervention before retrying. labels Aug 14, 2026
@nodejs-github-bot
nodejs-github-bot merged commit 4551732 into nodejs:mainAug 14, 2026
86 checks passed
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Landed in 4551732

@nodejs-github-botnodejs-github-bot removed the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 14, 2026
aduh95 pushed a commit that referenced this pull request Aug 25, 2026
Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.
Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.
The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.
streams/readable-async-iterator.js sync='yes': +32.59% (***)
streams/readable-async-iterator.js sync='no': +9.84% (***)
Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
aduh95 pushed a commit that referenced this pull request Aug 25, 2026
Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.
Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.
The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.
streams/readable-async-iterator.js sync='yes': +32.59% (***)
streams/readable-async-iterator.js sync='no': +9.84% (***)
Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

author readyPRs with CI started, the required approvals, and no outstanding review comments.commit-queue-squashPRs the Commit Queue should land as one squashed commit.needs-ciPRs that need a full CI run.streamIssues and PRs related to Node.js streams.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants

@mcollina@nodejs-github-bot@jasnell@MattiasBuelens@ronag@Renegade334@aduh95@mertcanaltin@gurgunday
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

stream: speed up async iteration of Readable - #64447

Merged
nodejs-github-bot merged 4 commits into
nodejs:mainfrom
mcollina:stream-async-iterator-perf
Aug 14, 2026
Merged

stream: speed up async iteration of Readable#64447
nodejs-github-bot merged 4 commits into
nodejs:mainfrom
mcollina:stream-async-iterator-perf

Conversation

@mcollina

@mcollinamcollina commented Jul 12, 2026

Copy link
Copy Markdown
Member

Replace the async generator backing Readable.prototype[Symbol.asyncIterator] (and .iterator()) with a hand-rolled iterator.

The generator machinery costs several extra promise allocations and microtask hops per chunk: yield awaits the yielded value and resolves the pending request through separate promises, and every next() goes through the async generator request queue. The hand-rolled iterator delivers buffered chunks as an already-resolved promise.

The observable semantics are preserved:

  • thenable chunks (object mode) are still awaited before delivery, and a rejected thenable still tears down the iterator and the stream;
  • next()/return()/throw() calls received while a request is outstanding are queued and processed in order — including return() while waiting for data, which still completes only once the pending read settles;
  • return()/throw() before the first next() complete the iterator without attaching listeners or destroying the stream;
  • the finally teardown logic (destroyOnReturn, autoDestroy, half-open duplex preservation) is unchanged;
  • error aggregation via aggregateTwoErrors is unchanged.

The one observable difference is that buffered chunks are delivered one microtask sooner than before, since the generator's yield performed an implicit Await on the yielded value. This is visible to code racing an abort against the first chunk. The flatMap AbortSignal test relied on such a race (a queueMicrotask'd abort beating the first chunk); it is reworked to be deterministic and timer-free: two mappers block until their signal aborts, the abort fires while both are in flight, and the test asserts the concurrency limit is respected (exactly two mappers start), in-flight mappers are cancelled through their signal, and iteration rejects with AbortError. The reworked test passes against both the old and the new implementation.

New regression tests cover the subtler iterator behaviors (thenable unwrapping, rejected thenables, throw(), pre-start throw(), concurrent next() ordering, and return() queued behind a pending next()); they also pass against both implementations.

Benchmark (benchmark/compare.js, 30 runs):

 confidence improvement accuracy (*) (**) (***)
streams/readable-async-iterator.js sync='no' n=100000 *** 9.84 % ±3.04% ±4.05% ±5.27%
streams/readable-async-iterator.js sync='yes' n=100000 *** 32.59 % ±5.49% ±7.34% ±9.62%

No changes on pipe.js / readable-readall.js.

🤖 Generated with Claude Code

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Review requested:

  • @nodejs/streams

@nodejs-github-botnodejs-github-bot added needs-ci PRs that need a full CI run. stream Issues and PRs related to Node.js streams. labels Jul 12, 2026
Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.
Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.
The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.
streams/readable-async-iterator.js sync='yes': +32.59% (***)
streams/readable-async-iterator.js sync='no': +9.84% (***)
Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
@mcollina
mcollinaforce-pushed the stream-async-iterator-perf branch from 2307152 to 6f9a2f3CompareJuly 12, 2026 08:36
Comment threadlib/internal/streams/readable.js Outdated
Comment on lines +1486 to +1497
if (typeof chunk.then === 'function') {
PromisePrototypeThen(PromiseResolve(chunk), (value) => {
inFlight = false;
resolve({ done: false, value });
if (queue !== null) drain();
}, (err) => {
inFlight = false;
settleError(err, reject);
if (queue !== null) drain();
});
return;
}

@aduh95aduh95Jul 12, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If then is a getter that e.g. throws on the second access, this code might throw when previously it wouldn't have. We can protect against that by storing the initial value we're getting (that might also avoid an additional promise allocation).

Suggested change
if(typeofchunk.then==='function'){
PromisePrototypeThen(PromiseResolve(chunk),(value)=>{
inFlight=false;
resolve({done: false, value });
if(queue!==null)drain();
},(err)=>{
inFlight=false;
settleError(err,reject);
if(queue!==null)drain();
});
return;
}
const{ then }=chunk;
if(typeofthen==='function'){
FunctionPrototypeCall(then,chunk,(value)=>{
inFlight=false;
resolve({done: false, value });
if(queue!==null)drain();
},(err)=>{
inFlight=false;
settleError(err,reject);
if(queue!==null)drain();
});
return;
}

Comment threadlib/internal/streams/readable.js Outdated
Comment on lines +1555 to +1558
if (typeof chunk.then === 'function') {
inFlight = true;
return PromisePrototypeThen(
PromiseResolve(chunk), onChunkFulfilled, onChunkRejected);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here

Suggested change
if(typeofchunk.then==='function'){
inFlight=true;
returnPromisePrototypeThen(
PromiseResolve(chunk),onChunkFulfilled,onChunkRejected);
const{then }=chunk;
if(typeofthen==='function'){
inFlight=true;
returnFunctionPrototypeCall(then,chunk,onChunkFulfilled,onChunkRejected);

settleError(err, reject);
}

return {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This object should ideally have a prototype of AsyncIteratorPrototype.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure it should if the sprecs doesn't require it – it does add a @@asyncDispose method which may or may not be desirable – it also adds a @@asyncIterator, which begs the question whether we should re-implement the method (re-implementing it ourselves means we're not subject to prototype tampering; otherwise, letting the built-in method be inherited would saves a bit of memory maybe?)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current implementation derives from AsyncIteratorPrototype (as a generator) so if we're trying to minimise observability then this is a fairly free move. (While the language currently only provides for the two well-known symbol methods, once we get into async iterator helpers territory, there will be significant advantages to keeping this inheritance.)

@codecov

codecovBot commented Jul 12, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.23256% with 21 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.29%. Comparing base (8a3b11c) to head (873a47e).
⚠️ Report is 472 commits behind head on main.

Files with missing linesPatch %Lines
lib/internal/streams/readable.js90.23%20 Missing and 1 partial ⚠️
Additional details and impacted files
@@ Coverage Diff @@## main #64447 +/- ##
==========================================
+ Coverage 90.24% 90.29% +0.04% 
==========================================
Files 741 760 +19 Lines 241384 247324 +5940 Branches 45480 46652 +1172 ==========================================
+ Hits 217844 223310 +5466 - Misses 15097 15477 +380 - Partials 8443 8537 +94 
Files with missing linesCoverage Δ
lib/internal/streams/readable.js96.55% <90.23%> (-0.72%)⬇️

... and 209 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Comment threadlib/internal/streams/readable.js Outdated
return new Promise((resolve, reject) => {
if (inFlight) {
queue ??= [];
queue.push({ type: 'return', value, resolve, reject });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
queue.push({type: 'return', value, resolve, reject });
queue.push({__proto__: null,type: 'return', value, resolve, reject });

Comment threadlib/internal/streams/readable.js Outdated
return new Promise((resolve, reject) => {
if (inFlight) {
queue ??= [];
queue.push({ type: 'next', value: undefined, resolve, reject });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
queue.push({type: 'next',value: undefined, resolve, reject });
queue.push({__proto__: null,type: 'next',value: undefined, resolve, reject });

Comment threadlib/internal/streams/readable.js Outdated
return new Promise((resolve, reject) => {
if (inFlight) {
queue ??= [];
queue.push({ type: 'throw', value: err, resolve, reject });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
queue.push({type: 'throw',value: err, resolve, reject });
queue.push({__proto__: null,type: 'throw',value: err, resolve, reject });

Comment threadlib/internal/streams/readable.js Outdated

function drain() {
while (!inFlight && queue.length > 0) {
const req = queue.shift();

@mertcanaltinmertcanaltinJul 12, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we replace queue.shift(); with an index-based queue for high throughput?

Comment threadlib/internal/streams/readable.js Outdated
Comment threadlib/internal/streams/readable.js Outdated
Comment threadtest/parallel/test-stream-flatMap.js Outdated
Comment on lines +84 to +89
await new Promise((resolve, reject) => {
if (signal.aborted) {
reject(signal.reason);
return;
}
signal.addEventListener('abort', () => reject(signal.reason), { once: true });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
awaitnewPromise((resolve,reject)=>{
if(signal.aborted){
reject(signal.reason);
return;
}
signal.addEventListener('abort',()=>reject(signal.reason),{once: true});
const{ promise, reject }=Promise.withResolvers();
if(signal.aborted){
reject(signal.reason);
}
signal.addEventListener('abort',()=>reject(signal.reason),{once: true});
// Promise is expected to reject.
awaitpromise;

Signed-off-by: Matteo Collina <hello@matteocollina.com>

@gurgundaygurgunday left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@mcollinamcollina added the request-ci Add this label to start a Jenkins CI on a PR. label Jul 13, 2026
@github-actionsgithub-actionsBot removed the request-ci Add this label to start a Jenkins CI on a PR. label Jul 13, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Comment threadlib/internal/streams/readable.js Outdated
Signed-off-by: Matteo Collina <hello@matteocollina.com>
@mcollina

Copy link
Copy Markdown
MemberAuthor

@MattiasBuelens updated

@gurgundaygurgunday left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

Signed-off-by: Matteo Collina <hello@matteocollina.com>
@ronagronag added request-ci Add this label to start a Jenkins CI on a PR. author ready PRs with CI started, the required approvals, and no outstanding review comments. labels Aug 6, 2026
@github-actionsgithub-actionsBot removed the request-ci Add this label to start a Jenkins CI on a PR. label Aug 6, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@mcollinamcollina added the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 14, 2026
@nodejs-github-botnodejs-github-bot added commit-queue-failed PRs whose Commit Queue landing failed and need manual intervention before retrying. and removed commit-queue PRs queued for automated landing through the Commit Queue. labels Aug 14, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator
Commit Queue failed
- Loading data for nodejs/node/pull/64447
✔ Done loading data for nodejs/node/pull/64447
----------------------------------- PR info ------------------------------------
Title stream: speed up async iteration of Readable (#64447)
Author Matteo Collina <matteo.collina@gmail.com> (@mcollina)
Branch mcollina:stream-async-iterator-perf -> nodejs:main
Labels stream, author ready, needs-ci, commit-queue
Commits 4
- stream: speed up async iteration of Readable
- fixup: address review comments
- fixup: remove [SymbolAsyncIterator]
- stream: fix lint in readable async iterator
Committers 1
- Matteo Collina <hello@matteocollina.com>
PR-URL: https://github.com/nodejs/node/pull/64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
------------------------------ Generated metadata ------------------------------
PR-URL: https://github.com/nodejs/node/pull/64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
--------------------------------------------------------------------------------
ℹ This PR was created on Sun, 12 Jul 2026 08:27:10 GMT
✔ Approvals: 3
✔ - Gürgün Dayıoğlu (@gurgunday): https://github.com/nodejs/node/pull/64447#pullrequestreview-4707049635
✔ - Mattias Buelens (@MattiasBuelens): https://github.com/nodejs/node/pull/64447#pullrequestreview-4706259826
✔ - Robert Nagy (@ronag) (TSC): https://github.com/nodejs/node/pull/64447#pullrequestreview-4838491319
✔ Last GitHub CI successful
ℹ Last Full PR CI on 2026-08-06T13:07:45Z: https://ci.nodejs.org/job/node-test-pull-request/75563/
- Querying data for job/node-test-pull-request/75563/
✔ Build data downloaded
✔ Last Jenkins CI successful
--------------------------------------------------------------------------------
✔ No git cherry-pick in progress
✔ No git am in progress
✔ No git rebase in progress
--------------------------------------------------------------------------------
- Bringing origin/main up to date...
From https://github.com/nodejs/node
* branch main -> FETCH_HEAD
✔ origin/main is now up-to-date
- Downloading patch for 64447
From https://github.com/nodejs/node
* branch refs/pull/64447/merge -> FETCH_HEAD
✔ Fetched commits as 9e23066b8af4..873a47ef6ae8
--------------------------------------------------------------------------------
Auto-merging lib/internal/streams/readable.js
[main 0a0be7f763] stream: speed up async iteration of Readable
Author: Matteo Collina <hello@matteocollina.com>
Date: Sat Jul 11 23:41:55 2026 +0200
3 files changed, 307 insertions(+), 35 deletions(-)
Auto-merging lib/internal/streams/readable.js
[main 22401b1cb5] fixup: address review comments
Author: Matteo Collina <hello@matteocollina.com>
Date: Mon Jul 13 10:00:44 2026 +0200
3 files changed, 73 insertions(+), 26 deletions(-)
Auto-merging lib/internal/streams/readable.js
[main 0b186829dd] fixup: remove [SymbolAsyncIterator]
Author: Matteo Collina <hello@matteocollina.com>
Date: Wed Jul 15 17:34:22 2026 +0200
1 file changed, 1 insertion(+), 4 deletions(-)
Auto-merging lib/internal/streams/readable.js
[main 656bc697b3] stream: fix lint in readable async iterator
Author: Matteo Collina <hello@matteocollina.com>
Date: Sun Aug 2 09:08:31 2026 +0000
1 file changed, 1 insertion(+), 1 deletion(-)
✔ Patches applied
There are 4 commits in the PR. Attempting autorebase.
(node:388) [DEP0190] DeprecationWarning: Passing args to a child process with shell option true can lead to security vulnerabilities, as the arguments are not escaped, only concatenated.
(Use `node --trace-deprecation ...` to show where the warning was created)
Rebasing (2/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
stream: speed up async iteration of Readable

Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.

Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.

The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.

streams/readable-async-iterator.js sync='yes': +32.59% ()
streams/readable-async-iterator.js sync='no': +9.84% (
)

Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD 6e6bcb4f2f] stream: speed up async iteration of Readable
Author: Matteo Collina <hello@matteocollina.com>
Date: Sat Jul 11 23:41:55 2026 +0200
3 files changed, 307 insertions(+), 35 deletions(-)
Rebasing (3/8)
Rebasing (4/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
fixup: address review comments

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD a9e0e0ad92] fixup: address review comments
Author: Matteo Collina <hello@matteocollina.com>
Date: Mon Jul 13 10:00:44 2026 +0200
3 files changed, 73 insertions(+), 26 deletions(-)
Rebasing (5/8)
Rebasing (6/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
fixup: remove [SymbolAsyncIterator]

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD 0ea470ea7b] fixup: remove [SymbolAsyncIterator]
Author: Matteo Collina <hello@matteocollina.com>
Date: Wed Jul 15 17:34:22 2026 +0200
1 file changed, 1 insertion(+), 4 deletions(-)
Rebasing (7/8)
Rebasing (8/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
stream: fix lint in readable async iterator

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD 0d2b7c1daf] stream: fix lint in readable async iterator
Author: Matteo Collina <hello@matteocollina.com>
Date: Sun Aug 2 09:08:31 2026 +0000
1 file changed, 1 insertion(+), 1 deletion(-)
Successfully rebased and updated refs/heads/main.

ℹ Add commit-queue-squash label to land the PR as one commit, or commit-queue-rebase to land as separate commits.

https://github.com/nodejs/node/actions/runs/31846615170

@mcollinamcollina added commit-queue PRs queued for automated landing through the Commit Queue. commit-queue-squash PRs the Commit Queue should land as one squashed commit. and removed commit-queue-failed PRs whose Commit Queue landing failed and need manual intervention before retrying. labels Aug 14, 2026
@nodejs-github-bot
nodejs-github-bot merged commit 4551732 into nodejs:mainAug 14, 2026
86 checks passed
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Landed in 4551732

@nodejs-github-botnodejs-github-bot removed the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 14, 2026
aduh95 pushed a commit that referenced this pull request Aug 25, 2026
Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.
Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.
The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.
streams/readable-async-iterator.js sync='yes': +32.59% (***)
streams/readable-async-iterator.js sync='no': +9.84% (***)
Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
aduh95 pushed a commit that referenced this pull request Aug 25, 2026
Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.
Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.
The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.
streams/readable-async-iterator.js sync='yes': +32.59% (***)
streams/readable-async-iterator.js sync='no': +9.84% (***)
Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

author readyPRs with CI started, the required approvals, and no outstanding review comments.commit-queue-squashPRs the Commit Queue should land as one squashed commit.needs-ciPRs that need a full CI run.streamIssues and PRs related to Node.js streams.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants

@mcollina@nodejs-github-bot@jasnell@MattiasBuelens@ronag@Renegade334@aduh95@mertcanaltin@gurgunday
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

stream: speed up async iteration of Readable - #64447

Merged
nodejs-github-bot merged 4 commits into
nodejs:mainfrom
mcollina:stream-async-iterator-perf
Aug 14, 2026
Merged

stream: speed up async iteration of Readable#64447
nodejs-github-bot merged 4 commits into
nodejs:mainfrom
mcollina:stream-async-iterator-perf

Conversation

@mcollina

@mcollinamcollina commented Jul 12, 2026

Copy link
Copy Markdown
Member

Replace the async generator backing Readable.prototype[Symbol.asyncIterator] (and .iterator()) with a hand-rolled iterator.

The generator machinery costs several extra promise allocations and microtask hops per chunk: yield awaits the yielded value and resolves the pending request through separate promises, and every next() goes through the async generator request queue. The hand-rolled iterator delivers buffered chunks as an already-resolved promise.

The observable semantics are preserved:

  • thenable chunks (object mode) are still awaited before delivery, and a rejected thenable still tears down the iterator and the stream;
  • next()/return()/throw() calls received while a request is outstanding are queued and processed in order — including return() while waiting for data, which still completes only once the pending read settles;
  • return()/throw() before the first next() complete the iterator without attaching listeners or destroying the stream;
  • the finally teardown logic (destroyOnReturn, autoDestroy, half-open duplex preservation) is unchanged;
  • error aggregation via aggregateTwoErrors is unchanged.

The one observable difference is that buffered chunks are delivered one microtask sooner than before, since the generator's yield performed an implicit Await on the yielded value. This is visible to code racing an abort against the first chunk. The flatMap AbortSignal test relied on such a race (a queueMicrotask'd abort beating the first chunk); it is reworked to be deterministic and timer-free: two mappers block until their signal aborts, the abort fires while both are in flight, and the test asserts the concurrency limit is respected (exactly two mappers start), in-flight mappers are cancelled through their signal, and iteration rejects with AbortError. The reworked test passes against both the old and the new implementation.

New regression tests cover the subtler iterator behaviors (thenable unwrapping, rejected thenables, throw(), pre-start throw(), concurrent next() ordering, and return() queued behind a pending next()); they also pass against both implementations.

Benchmark (benchmark/compare.js, 30 runs):

 confidence improvement accuracy (*) (**) (***)
streams/readable-async-iterator.js sync='no' n=100000 *** 9.84 % ±3.04% ±4.05% ±5.27%
streams/readable-async-iterator.js sync='yes' n=100000 *** 32.59 % ±5.49% ±7.34% ±9.62%

No changes on pipe.js / readable-readall.js.

🤖 Generated with Claude Code

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Review requested:

  • @nodejs/streams

@nodejs-github-botnodejs-github-bot added needs-ci PRs that need a full CI run. stream Issues and PRs related to Node.js streams. labels Jul 12, 2026
Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.
Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.
The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.
streams/readable-async-iterator.js sync='yes': +32.59% (***)
streams/readable-async-iterator.js sync='no': +9.84% (***)
Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
@mcollina
mcollinaforce-pushed the stream-async-iterator-perf branch from 2307152 to 6f9a2f3CompareJuly 12, 2026 08:36
Comment threadlib/internal/streams/readable.js Outdated
Comment on lines +1486 to +1497
if (typeof chunk.then === 'function') {
PromisePrototypeThen(PromiseResolve(chunk), (value) => {
inFlight = false;
resolve({ done: false, value });
if (queue !== null) drain();
}, (err) => {
inFlight = false;
settleError(err, reject);
if (queue !== null) drain();
});
return;
}

@aduh95aduh95Jul 12, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If then is a getter that e.g. throws on the second access, this code might throw when previously it wouldn't have. We can protect against that by storing the initial value we're getting (that might also avoid an additional promise allocation).

Suggested change
if(typeofchunk.then==='function'){
PromisePrototypeThen(PromiseResolve(chunk),(value)=>{
inFlight=false;
resolve({done: false, value });
if(queue!==null)drain();
},(err)=>{
inFlight=false;
settleError(err,reject);
if(queue!==null)drain();
});
return;
}
const{ then }=chunk;
if(typeofthen==='function'){
FunctionPrototypeCall(then,chunk,(value)=>{
inFlight=false;
resolve({done: false, value });
if(queue!==null)drain();
},(err)=>{
inFlight=false;
settleError(err,reject);
if(queue!==null)drain();
});
return;
}

Comment threadlib/internal/streams/readable.js Outdated
Comment on lines +1555 to +1558
if (typeof chunk.then === 'function') {
inFlight = true;
return PromisePrototypeThen(
PromiseResolve(chunk), onChunkFulfilled, onChunkRejected);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here

Suggested change
if(typeofchunk.then==='function'){
inFlight=true;
returnPromisePrototypeThen(
PromiseResolve(chunk),onChunkFulfilled,onChunkRejected);
const{then }=chunk;
if(typeofthen==='function'){
inFlight=true;
returnFunctionPrototypeCall(then,chunk,onChunkFulfilled,onChunkRejected);

settleError(err, reject);
}

return {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This object should ideally have a prototype of AsyncIteratorPrototype.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure it should if the sprecs doesn't require it – it does add a @@asyncDispose method which may or may not be desirable – it also adds a @@asyncIterator, which begs the question whether we should re-implement the method (re-implementing it ourselves means we're not subject to prototype tampering; otherwise, letting the built-in method be inherited would saves a bit of memory maybe?)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current implementation derives from AsyncIteratorPrototype (as a generator) so if we're trying to minimise observability then this is a fairly free move. (While the language currently only provides for the two well-known symbol methods, once we get into async iterator helpers territory, there will be significant advantages to keeping this inheritance.)

@codecov

codecovBot commented Jul 12, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.23256% with 21 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.29%. Comparing base (8a3b11c) to head (873a47e).
⚠️ Report is 472 commits behind head on main.

Files with missing linesPatch %Lines
lib/internal/streams/readable.js90.23%20 Missing and 1 partial ⚠️
Additional details and impacted files
@@ Coverage Diff @@## main #64447 +/- ##
==========================================
+ Coverage 90.24% 90.29% +0.04% 
==========================================
Files 741 760 +19 Lines 241384 247324 +5940 Branches 45480 46652 +1172 ==========================================
+ Hits 217844 223310 +5466 - Misses 15097 15477 +380 - Partials 8443 8537 +94 
Files with missing linesCoverage Δ
lib/internal/streams/readable.js96.55% <90.23%> (-0.72%)⬇️

... and 209 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Comment threadlib/internal/streams/readable.js Outdated
return new Promise((resolve, reject) => {
if (inFlight) {
queue ??= [];
queue.push({ type: 'return', value, resolve, reject });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
queue.push({type: 'return', value, resolve, reject });
queue.push({__proto__: null,type: 'return', value, resolve, reject });

Comment threadlib/internal/streams/readable.js Outdated
return new Promise((resolve, reject) => {
if (inFlight) {
queue ??= [];
queue.push({ type: 'next', value: undefined, resolve, reject });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
queue.push({type: 'next',value: undefined, resolve, reject });
queue.push({__proto__: null,type: 'next',value: undefined, resolve, reject });

Comment threadlib/internal/streams/readable.js Outdated
return new Promise((resolve, reject) => {
if (inFlight) {
queue ??= [];
queue.push({ type: 'throw', value: err, resolve, reject });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
queue.push({type: 'throw',value: err, resolve, reject });
queue.push({__proto__: null,type: 'throw',value: err, resolve, reject });

Comment threadlib/internal/streams/readable.js Outdated

function drain() {
while (!inFlight && queue.length > 0) {
const req = queue.shift();

@mertcanaltinmertcanaltinJul 12, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we replace queue.shift(); with an index-based queue for high throughput?

Comment threadlib/internal/streams/readable.js Outdated
Comment threadlib/internal/streams/readable.js Outdated
Comment threadtest/parallel/test-stream-flatMap.js Outdated
Comment on lines +84 to +89
await new Promise((resolve, reject) => {
if (signal.aborted) {
reject(signal.reason);
return;
}
signal.addEventListener('abort', () => reject(signal.reason), { once: true });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
awaitnewPromise((resolve,reject)=>{
if(signal.aborted){
reject(signal.reason);
return;
}
signal.addEventListener('abort',()=>reject(signal.reason),{once: true});
const{ promise, reject }=Promise.withResolvers();
if(signal.aborted){
reject(signal.reason);
}
signal.addEventListener('abort',()=>reject(signal.reason),{once: true});
// Promise is expected to reject.
awaitpromise;

Signed-off-by: Matteo Collina <hello@matteocollina.com>

@gurgundaygurgunday left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@mcollinamcollina added the request-ci Add this label to start a Jenkins CI on a PR. label Jul 13, 2026
@github-actionsgithub-actionsBot removed the request-ci Add this label to start a Jenkins CI on a PR. label Jul 13, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Comment threadlib/internal/streams/readable.js Outdated
Signed-off-by: Matteo Collina <hello@matteocollina.com>
@mcollina

Copy link
Copy Markdown
MemberAuthor

@MattiasBuelens updated

@gurgundaygurgunday left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

Signed-off-by: Matteo Collina <hello@matteocollina.com>
@ronagronag added request-ci Add this label to start a Jenkins CI on a PR. author ready PRs with CI started, the required approvals, and no outstanding review comments. labels Aug 6, 2026
@github-actionsgithub-actionsBot removed the request-ci Add this label to start a Jenkins CI on a PR. label Aug 6, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@mcollinamcollina added the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 14, 2026
@nodejs-github-botnodejs-github-bot added commit-queue-failed PRs whose Commit Queue landing failed and need manual intervention before retrying. and removed commit-queue PRs queued for automated landing through the Commit Queue. labels Aug 14, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator
Commit Queue failed
- Loading data for nodejs/node/pull/64447
✔ Done loading data for nodejs/node/pull/64447
----------------------------------- PR info ------------------------------------
Title stream: speed up async iteration of Readable (#64447)
Author Matteo Collina <matteo.collina@gmail.com> (@mcollina)
Branch mcollina:stream-async-iterator-perf -> nodejs:main
Labels stream, author ready, needs-ci, commit-queue
Commits 4
- stream: speed up async iteration of Readable
- fixup: address review comments
- fixup: remove [SymbolAsyncIterator]
- stream: fix lint in readable async iterator
Committers 1
- Matteo Collina <hello@matteocollina.com>
PR-URL: https://github.com/nodejs/node/pull/64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
------------------------------ Generated metadata ------------------------------
PR-URL: https://github.com/nodejs/node/pull/64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
--------------------------------------------------------------------------------
ℹ This PR was created on Sun, 12 Jul 2026 08:27:10 GMT
✔ Approvals: 3
✔ - Gürgün Dayıoğlu (@gurgunday): https://github.com/nodejs/node/pull/64447#pullrequestreview-4707049635
✔ - Mattias Buelens (@MattiasBuelens): https://github.com/nodejs/node/pull/64447#pullrequestreview-4706259826
✔ - Robert Nagy (@ronag) (TSC): https://github.com/nodejs/node/pull/64447#pullrequestreview-4838491319
✔ Last GitHub CI successful
ℹ Last Full PR CI on 2026-08-06T13:07:45Z: https://ci.nodejs.org/job/node-test-pull-request/75563/
- Querying data for job/node-test-pull-request/75563/
✔ Build data downloaded
✔ Last Jenkins CI successful
--------------------------------------------------------------------------------
✔ No git cherry-pick in progress
✔ No git am in progress
✔ No git rebase in progress
--------------------------------------------------------------------------------
- Bringing origin/main up to date...
From https://github.com/nodejs/node
* branch main -> FETCH_HEAD
✔ origin/main is now up-to-date
- Downloading patch for 64447
From https://github.com/nodejs/node
* branch refs/pull/64447/merge -> FETCH_HEAD
✔ Fetched commits as 9e23066b8af4..873a47ef6ae8
--------------------------------------------------------------------------------
Auto-merging lib/internal/streams/readable.js
[main 0a0be7f763] stream: speed up async iteration of Readable
Author: Matteo Collina <hello@matteocollina.com>
Date: Sat Jul 11 23:41:55 2026 +0200
3 files changed, 307 insertions(+), 35 deletions(-)
Auto-merging lib/internal/streams/readable.js
[main 22401b1cb5] fixup: address review comments
Author: Matteo Collina <hello@matteocollina.com>
Date: Mon Jul 13 10:00:44 2026 +0200
3 files changed, 73 insertions(+), 26 deletions(-)
Auto-merging lib/internal/streams/readable.js
[main 0b186829dd] fixup: remove [SymbolAsyncIterator]
Author: Matteo Collina <hello@matteocollina.com>
Date: Wed Jul 15 17:34:22 2026 +0200
1 file changed, 1 insertion(+), 4 deletions(-)
Auto-merging lib/internal/streams/readable.js
[main 656bc697b3] stream: fix lint in readable async iterator
Author: Matteo Collina <hello@matteocollina.com>
Date: Sun Aug 2 09:08:31 2026 +0000
1 file changed, 1 insertion(+), 1 deletion(-)
✔ Patches applied
There are 4 commits in the PR. Attempting autorebase.
(node:388) [DEP0190] DeprecationWarning: Passing args to a child process with shell option true can lead to security vulnerabilities, as the arguments are not escaped, only concatenated.
(Use `node --trace-deprecation ...` to show where the warning was created)
Rebasing (2/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
stream: speed up async iteration of Readable

Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.

Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.

The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.

streams/readable-async-iterator.js sync='yes': +32.59% ()
streams/readable-async-iterator.js sync='no': +9.84% (
)

Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD 6e6bcb4f2f] stream: speed up async iteration of Readable
Author: Matteo Collina <hello@matteocollina.com>
Date: Sat Jul 11 23:41:55 2026 +0200
3 files changed, 307 insertions(+), 35 deletions(-)
Rebasing (3/8)
Rebasing (4/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
fixup: address review comments

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD a9e0e0ad92] fixup: address review comments
Author: Matteo Collina <hello@matteocollina.com>
Date: Mon Jul 13 10:00:44 2026 +0200
3 files changed, 73 insertions(+), 26 deletions(-)
Rebasing (5/8)
Rebasing (6/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
fixup: remove [SymbolAsyncIterator]

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD 0ea470ea7b] fixup: remove [SymbolAsyncIterator]
Author: Matteo Collina <hello@matteocollina.com>
Date: Wed Jul 15 17:34:22 2026 +0200
1 file changed, 1 insertion(+), 4 deletions(-)
Rebasing (7/8)
Rebasing (8/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
stream: fix lint in readable async iterator

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD 0d2b7c1daf] stream: fix lint in readable async iterator
Author: Matteo Collina <hello@matteocollina.com>
Date: Sun Aug 2 09:08:31 2026 +0000
1 file changed, 1 insertion(+), 1 deletion(-)
Successfully rebased and updated refs/heads/main.

ℹ Add commit-queue-squash label to land the PR as one commit, or commit-queue-rebase to land as separate commits.

https://github.com/nodejs/node/actions/runs/31846615170

@mcollinamcollina added commit-queue PRs queued for automated landing through the Commit Queue. commit-queue-squash PRs the Commit Queue should land as one squashed commit. and removed commit-queue-failed PRs whose Commit Queue landing failed and need manual intervention before retrying. labels Aug 14, 2026
@nodejs-github-bot
nodejs-github-bot merged commit 4551732 into nodejs:mainAug 14, 2026
86 checks passed
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Landed in 4551732

@nodejs-github-botnodejs-github-bot removed the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 14, 2026
aduh95 pushed a commit that referenced this pull request Aug 25, 2026
Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.
Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.
The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.
streams/readable-async-iterator.js sync='yes': +32.59% (***)
streams/readable-async-iterator.js sync='no': +9.84% (***)
Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
aduh95 pushed a commit that referenced this pull request Aug 25, 2026
Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.
Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.
The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.
streams/readable-async-iterator.js sync='yes': +32.59% (***)
streams/readable-async-iterator.js sync='no': +9.84% (***)
Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

author readyPRs with CI started, the required approvals, and no outstanding review comments.commit-queue-squashPRs the Commit Queue should land as one squashed commit.needs-ciPRs that need a full CI run.streamIssues and PRs related to Node.js streams.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants

@mcollina@nodejs-github-bot@jasnell@MattiasBuelens@ronag@Renegade334@aduh95@mertcanaltin@gurgunday
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

stream: speed up async iteration of Readable - #64447

Merged
nodejs-github-bot merged 4 commits into
nodejs:mainfrom
mcollina:stream-async-iterator-perf
Aug 14, 2026
Merged

stream: speed up async iteration of Readable#64447
nodejs-github-bot merged 4 commits into
nodejs:mainfrom
mcollina:stream-async-iterator-perf

Conversation

@mcollina

@mcollinamcollina commented Jul 12, 2026

Copy link
Copy Markdown
Member

Replace the async generator backing Readable.prototype[Symbol.asyncIterator] (and .iterator()) with a hand-rolled iterator.

The generator machinery costs several extra promise allocations and microtask hops per chunk: yield awaits the yielded value and resolves the pending request through separate promises, and every next() goes through the async generator request queue. The hand-rolled iterator delivers buffered chunks as an already-resolved promise.

The observable semantics are preserved:

  • thenable chunks (object mode) are still awaited before delivery, and a rejected thenable still tears down the iterator and the stream;
  • next()/return()/throw() calls received while a request is outstanding are queued and processed in order — including return() while waiting for data, which still completes only once the pending read settles;
  • return()/throw() before the first next() complete the iterator without attaching listeners or destroying the stream;
  • the finally teardown logic (destroyOnReturn, autoDestroy, half-open duplex preservation) is unchanged;
  • error aggregation via aggregateTwoErrors is unchanged.

The one observable difference is that buffered chunks are delivered one microtask sooner than before, since the generator's yield performed an implicit Await on the yielded value. This is visible to code racing an abort against the first chunk. The flatMap AbortSignal test relied on such a race (a queueMicrotask'd abort beating the first chunk); it is reworked to be deterministic and timer-free: two mappers block until their signal aborts, the abort fires while both are in flight, and the test asserts the concurrency limit is respected (exactly two mappers start), in-flight mappers are cancelled through their signal, and iteration rejects with AbortError. The reworked test passes against both the old and the new implementation.

New regression tests cover the subtler iterator behaviors (thenable unwrapping, rejected thenables, throw(), pre-start throw(), concurrent next() ordering, and return() queued behind a pending next()); they also pass against both implementations.

Benchmark (benchmark/compare.js, 30 runs):

 confidence improvement accuracy (*) (**) (***)
streams/readable-async-iterator.js sync='no' n=100000 *** 9.84 % ±3.04% ±4.05% ±5.27%
streams/readable-async-iterator.js sync='yes' n=100000 *** 32.59 % ±5.49% ±7.34% ±9.62%

No changes on pipe.js / readable-readall.js.

🤖 Generated with Claude Code

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Review requested:

  • @nodejs/streams

@nodejs-github-botnodejs-github-bot added needs-ci PRs that need a full CI run. stream Issues and PRs related to Node.js streams. labels Jul 12, 2026
Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.
Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.
The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.
streams/readable-async-iterator.js sync='yes': +32.59% (***)
streams/readable-async-iterator.js sync='no': +9.84% (***)
Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
@mcollina
mcollinaforce-pushed the stream-async-iterator-perf branch from 2307152 to 6f9a2f3CompareJuly 12, 2026 08:36
Comment threadlib/internal/streams/readable.js Outdated
Comment on lines +1486 to +1497
if (typeof chunk.then === 'function') {
PromisePrototypeThen(PromiseResolve(chunk), (value) => {
inFlight = false;
resolve({ done: false, value });
if (queue !== null) drain();
}, (err) => {
inFlight = false;
settleError(err, reject);
if (queue !== null) drain();
});
return;
}

@aduh95aduh95Jul 12, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If then is a getter that e.g. throws on the second access, this code might throw when previously it wouldn't have. We can protect against that by storing the initial value we're getting (that might also avoid an additional promise allocation).

Suggested change
if(typeofchunk.then==='function'){
PromisePrototypeThen(PromiseResolve(chunk),(value)=>{
inFlight=false;
resolve({done: false, value });
if(queue!==null)drain();
},(err)=>{
inFlight=false;
settleError(err,reject);
if(queue!==null)drain();
});
return;
}
const{ then }=chunk;
if(typeofthen==='function'){
FunctionPrototypeCall(then,chunk,(value)=>{
inFlight=false;
resolve({done: false, value });
if(queue!==null)drain();
},(err)=>{
inFlight=false;
settleError(err,reject);
if(queue!==null)drain();
});
return;
}

Comment threadlib/internal/streams/readable.js Outdated
Comment on lines +1555 to +1558
if (typeof chunk.then === 'function') {
inFlight = true;
return PromisePrototypeThen(
PromiseResolve(chunk), onChunkFulfilled, onChunkRejected);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here

Suggested change
if(typeofchunk.then==='function'){
inFlight=true;
returnPromisePrototypeThen(
PromiseResolve(chunk),onChunkFulfilled,onChunkRejected);
const{then }=chunk;
if(typeofthen==='function'){
inFlight=true;
returnFunctionPrototypeCall(then,chunk,onChunkFulfilled,onChunkRejected);

settleError(err, reject);
}

return {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This object should ideally have a prototype of AsyncIteratorPrototype.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure it should if the sprecs doesn't require it – it does add a @@asyncDispose method which may or may not be desirable – it also adds a @@asyncIterator, which begs the question whether we should re-implement the method (re-implementing it ourselves means we're not subject to prototype tampering; otherwise, letting the built-in method be inherited would saves a bit of memory maybe?)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current implementation derives from AsyncIteratorPrototype (as a generator) so if we're trying to minimise observability then this is a fairly free move. (While the language currently only provides for the two well-known symbol methods, once we get into async iterator helpers territory, there will be significant advantages to keeping this inheritance.)

@codecov

codecovBot commented Jul 12, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.23256% with 21 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.29%. Comparing base (8a3b11c) to head (873a47e).
⚠️ Report is 472 commits behind head on main.

Files with missing linesPatch %Lines
lib/internal/streams/readable.js90.23%20 Missing and 1 partial ⚠️
Additional details and impacted files
@@ Coverage Diff @@## main #64447 +/- ##
==========================================
+ Coverage 90.24% 90.29% +0.04% 
==========================================
Files 741 760 +19 Lines 241384 247324 +5940 Branches 45480 46652 +1172 ==========================================
+ Hits 217844 223310 +5466 - Misses 15097 15477 +380 - Partials 8443 8537 +94 
Files with missing linesCoverage Δ
lib/internal/streams/readable.js96.55% <90.23%> (-0.72%)⬇️

... and 209 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Comment threadlib/internal/streams/readable.js Outdated
return new Promise((resolve, reject) => {
if (inFlight) {
queue ??= [];
queue.push({ type: 'return', value, resolve, reject });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
queue.push({type: 'return', value, resolve, reject });
queue.push({__proto__: null,type: 'return', value, resolve, reject });

Comment threadlib/internal/streams/readable.js Outdated
return new Promise((resolve, reject) => {
if (inFlight) {
queue ??= [];
queue.push({ type: 'next', value: undefined, resolve, reject });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
queue.push({type: 'next',value: undefined, resolve, reject });
queue.push({__proto__: null,type: 'next',value: undefined, resolve, reject });

Comment threadlib/internal/streams/readable.js Outdated
return new Promise((resolve, reject) => {
if (inFlight) {
queue ??= [];
queue.push({ type: 'throw', value: err, resolve, reject });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
queue.push({type: 'throw',value: err, resolve, reject });
queue.push({__proto__: null,type: 'throw',value: err, resolve, reject });

Comment threadlib/internal/streams/readable.js Outdated

function drain() {
while (!inFlight && queue.length > 0) {
const req = queue.shift();

@mertcanaltinmertcanaltinJul 12, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we replace queue.shift(); with an index-based queue for high throughput?

Comment threadlib/internal/streams/readable.js Outdated
Comment threadlib/internal/streams/readable.js Outdated
Comment threadtest/parallel/test-stream-flatMap.js Outdated
Comment on lines +84 to +89
await new Promise((resolve, reject) => {
if (signal.aborted) {
reject(signal.reason);
return;
}
signal.addEventListener('abort', () => reject(signal.reason), { once: true });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
awaitnewPromise((resolve,reject)=>{
if(signal.aborted){
reject(signal.reason);
return;
}
signal.addEventListener('abort',()=>reject(signal.reason),{once: true});
const{ promise, reject }=Promise.withResolvers();
if(signal.aborted){
reject(signal.reason);
}
signal.addEventListener('abort',()=>reject(signal.reason),{once: true});
// Promise is expected to reject.
awaitpromise;

Signed-off-by: Matteo Collina <hello@matteocollina.com>

@gurgundaygurgunday left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@mcollinamcollina added the request-ci Add this label to start a Jenkins CI on a PR. label Jul 13, 2026
@github-actionsgithub-actionsBot removed the request-ci Add this label to start a Jenkins CI on a PR. label Jul 13, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Comment threadlib/internal/streams/readable.js Outdated
Signed-off-by: Matteo Collina <hello@matteocollina.com>
@mcollina

Copy link
Copy Markdown
MemberAuthor

@MattiasBuelens updated

@gurgundaygurgunday left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

Signed-off-by: Matteo Collina <hello@matteocollina.com>
@ronagronag added request-ci Add this label to start a Jenkins CI on a PR. author ready PRs with CI started, the required approvals, and no outstanding review comments. labels Aug 6, 2026
@github-actionsgithub-actionsBot removed the request-ci Add this label to start a Jenkins CI on a PR. label Aug 6, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@mcollinamcollina added the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 14, 2026
@nodejs-github-botnodejs-github-bot added commit-queue-failed PRs whose Commit Queue landing failed and need manual intervention before retrying. and removed commit-queue PRs queued for automated landing through the Commit Queue. labels Aug 14, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator
Commit Queue failed
- Loading data for nodejs/node/pull/64447
✔ Done loading data for nodejs/node/pull/64447
----------------------------------- PR info ------------------------------------
Title stream: speed up async iteration of Readable (#64447)
Author Matteo Collina <matteo.collina@gmail.com> (@mcollina)
Branch mcollina:stream-async-iterator-perf -> nodejs:main
Labels stream, author ready, needs-ci, commit-queue
Commits 4
- stream: speed up async iteration of Readable
- fixup: address review comments
- fixup: remove [SymbolAsyncIterator]
- stream: fix lint in readable async iterator
Committers 1
- Matteo Collina <hello@matteocollina.com>
PR-URL: https://github.com/nodejs/node/pull/64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
------------------------------ Generated metadata ------------------------------
PR-URL: https://github.com/nodejs/node/pull/64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
--------------------------------------------------------------------------------
ℹ This PR was created on Sun, 12 Jul 2026 08:27:10 GMT
✔ Approvals: 3
✔ - Gürgün Dayıoğlu (@gurgunday): https://github.com/nodejs/node/pull/64447#pullrequestreview-4707049635
✔ - Mattias Buelens (@MattiasBuelens): https://github.com/nodejs/node/pull/64447#pullrequestreview-4706259826
✔ - Robert Nagy (@ronag) (TSC): https://github.com/nodejs/node/pull/64447#pullrequestreview-4838491319
✔ Last GitHub CI successful
ℹ Last Full PR CI on 2026-08-06T13:07:45Z: https://ci.nodejs.org/job/node-test-pull-request/75563/
- Querying data for job/node-test-pull-request/75563/
✔ Build data downloaded
✔ Last Jenkins CI successful
--------------------------------------------------------------------------------
✔ No git cherry-pick in progress
✔ No git am in progress
✔ No git rebase in progress
--------------------------------------------------------------------------------
- Bringing origin/main up to date...
From https://github.com/nodejs/node
* branch main -> FETCH_HEAD
✔ origin/main is now up-to-date
- Downloading patch for 64447
From https://github.com/nodejs/node
* branch refs/pull/64447/merge -> FETCH_HEAD
✔ Fetched commits as 9e23066b8af4..873a47ef6ae8
--------------------------------------------------------------------------------
Auto-merging lib/internal/streams/readable.js
[main 0a0be7f763] stream: speed up async iteration of Readable
Author: Matteo Collina <hello@matteocollina.com>
Date: Sat Jul 11 23:41:55 2026 +0200
3 files changed, 307 insertions(+), 35 deletions(-)
Auto-merging lib/internal/streams/readable.js
[main 22401b1cb5] fixup: address review comments
Author: Matteo Collina <hello@matteocollina.com>
Date: Mon Jul 13 10:00:44 2026 +0200
3 files changed, 73 insertions(+), 26 deletions(-)
Auto-merging lib/internal/streams/readable.js
[main 0b186829dd] fixup: remove [SymbolAsyncIterator]
Author: Matteo Collina <hello@matteocollina.com>
Date: Wed Jul 15 17:34:22 2026 +0200
1 file changed, 1 insertion(+), 4 deletions(-)
Auto-merging lib/internal/streams/readable.js
[main 656bc697b3] stream: fix lint in readable async iterator
Author: Matteo Collina <hello@matteocollina.com>
Date: Sun Aug 2 09:08:31 2026 +0000
1 file changed, 1 insertion(+), 1 deletion(-)
✔ Patches applied
There are 4 commits in the PR. Attempting autorebase.
(node:388) [DEP0190] DeprecationWarning: Passing args to a child process with shell option true can lead to security vulnerabilities, as the arguments are not escaped, only concatenated.
(Use `node --trace-deprecation ...` to show where the warning was created)
Rebasing (2/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
stream: speed up async iteration of Readable

Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.

Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.

The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.

streams/readable-async-iterator.js sync='yes': +32.59% ()
streams/readable-async-iterator.js sync='no': +9.84% (
)

Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD 6e6bcb4f2f] stream: speed up async iteration of Readable
Author: Matteo Collina <hello@matteocollina.com>
Date: Sat Jul 11 23:41:55 2026 +0200
3 files changed, 307 insertions(+), 35 deletions(-)
Rebasing (3/8)
Rebasing (4/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
fixup: address review comments

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD a9e0e0ad92] fixup: address review comments
Author: Matteo Collina <hello@matteocollina.com>
Date: Mon Jul 13 10:00:44 2026 +0200
3 files changed, 73 insertions(+), 26 deletions(-)
Rebasing (5/8)
Rebasing (6/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
fixup: remove [SymbolAsyncIterator]

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD 0ea470ea7b] fixup: remove [SymbolAsyncIterator]
Author: Matteo Collina <hello@matteocollina.com>
Date: Wed Jul 15 17:34:22 2026 +0200
1 file changed, 1 insertion(+), 4 deletions(-)
Rebasing (7/8)
Rebasing (8/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
stream: fix lint in readable async iterator

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD 0d2b7c1daf] stream: fix lint in readable async iterator
Author: Matteo Collina <hello@matteocollina.com>
Date: Sun Aug 2 09:08:31 2026 +0000
1 file changed, 1 insertion(+), 1 deletion(-)
Successfully rebased and updated refs/heads/main.

ℹ Add commit-queue-squash label to land the PR as one commit, or commit-queue-rebase to land as separate commits.

https://github.com/nodejs/node/actions/runs/31846615170

@mcollinamcollina added commit-queue PRs queued for automated landing through the Commit Queue. commit-queue-squash PRs the Commit Queue should land as one squashed commit. and removed commit-queue-failed PRs whose Commit Queue landing failed and need manual intervention before retrying. labels Aug 14, 2026
@nodejs-github-bot
nodejs-github-bot merged commit 4551732 into nodejs:mainAug 14, 2026
86 checks passed
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Landed in 4551732

@nodejs-github-botnodejs-github-bot removed the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 14, 2026
aduh95 pushed a commit that referenced this pull request Aug 25, 2026
Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.
Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.
The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.
streams/readable-async-iterator.js sync='yes': +32.59% (***)
streams/readable-async-iterator.js sync='no': +9.84% (***)
Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
aduh95 pushed a commit that referenced this pull request Aug 25, 2026
Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.
Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.
The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.
streams/readable-async-iterator.js sync='yes': +32.59% (***)
streams/readable-async-iterator.js sync='no': +9.84% (***)
Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

author readyPRs with CI started, the required approvals, and no outstanding review comments.commit-queue-squashPRs the Commit Queue should land as one squashed commit.needs-ciPRs that need a full CI run.streamIssues and PRs related to Node.js streams.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants

@mcollina@nodejs-github-bot@jasnell@MattiasBuelens@ronag@Renegade334@aduh95@mertcanaltin@gurgunday
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

stream: speed up async iteration of Readable - #64447

Merged
nodejs-github-bot merged 4 commits into
nodejs:mainfrom
mcollina:stream-async-iterator-perf
Aug 14, 2026
Merged

stream: speed up async iteration of Readable#64447
nodejs-github-bot merged 4 commits into
nodejs:mainfrom
mcollina:stream-async-iterator-perf

Conversation

@mcollina

@mcollinamcollina commented Jul 12, 2026

Copy link
Copy Markdown
Member

Replace the async generator backing Readable.prototype[Symbol.asyncIterator] (and .iterator()) with a hand-rolled iterator.

The generator machinery costs several extra promise allocations and microtask hops per chunk: yield awaits the yielded value and resolves the pending request through separate promises, and every next() goes through the async generator request queue. The hand-rolled iterator delivers buffered chunks as an already-resolved promise.

The observable semantics are preserved:

  • thenable chunks (object mode) are still awaited before delivery, and a rejected thenable still tears down the iterator and the stream;
  • next()/return()/throw() calls received while a request is outstanding are queued and processed in order — including return() while waiting for data, which still completes only once the pending read settles;
  • return()/throw() before the first next() complete the iterator without attaching listeners or destroying the stream;
  • the finally teardown logic (destroyOnReturn, autoDestroy, half-open duplex preservation) is unchanged;
  • error aggregation via aggregateTwoErrors is unchanged.

The one observable difference is that buffered chunks are delivered one microtask sooner than before, since the generator's yield performed an implicit Await on the yielded value. This is visible to code racing an abort against the first chunk. The flatMap AbortSignal test relied on such a race (a queueMicrotask'd abort beating the first chunk); it is reworked to be deterministic and timer-free: two mappers block until their signal aborts, the abort fires while both are in flight, and the test asserts the concurrency limit is respected (exactly two mappers start), in-flight mappers are cancelled through their signal, and iteration rejects with AbortError. The reworked test passes against both the old and the new implementation.

New regression tests cover the subtler iterator behaviors (thenable unwrapping, rejected thenables, throw(), pre-start throw(), concurrent next() ordering, and return() queued behind a pending next()); they also pass against both implementations.

Benchmark (benchmark/compare.js, 30 runs):

 confidence improvement accuracy (*) (**) (***)
streams/readable-async-iterator.js sync='no' n=100000 *** 9.84 % ±3.04% ±4.05% ±5.27%
streams/readable-async-iterator.js sync='yes' n=100000 *** 32.59 % ±5.49% ±7.34% ±9.62%

No changes on pipe.js / readable-readall.js.

🤖 Generated with Claude Code

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Review requested:

  • @nodejs/streams

@nodejs-github-botnodejs-github-bot added needs-ci PRs that need a full CI run. stream Issues and PRs related to Node.js streams. labels Jul 12, 2026
Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.
Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.
The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.
streams/readable-async-iterator.js sync='yes': +32.59% (***)
streams/readable-async-iterator.js sync='no': +9.84% (***)
Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
@mcollina
mcollinaforce-pushed the stream-async-iterator-perf branch from 2307152 to 6f9a2f3CompareJuly 12, 2026 08:36
Comment threadlib/internal/streams/readable.js Outdated
Comment on lines +1486 to +1497
if (typeof chunk.then === 'function') {
PromisePrototypeThen(PromiseResolve(chunk), (value) => {
inFlight = false;
resolve({ done: false, value });
if (queue !== null) drain();
}, (err) => {
inFlight = false;
settleError(err, reject);
if (queue !== null) drain();
});
return;
}

@aduh95aduh95Jul 12, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If then is a getter that e.g. throws on the second access, this code might throw when previously it wouldn't have. We can protect against that by storing the initial value we're getting (that might also avoid an additional promise allocation).

Suggested change
if(typeofchunk.then==='function'){
PromisePrototypeThen(PromiseResolve(chunk),(value)=>{
inFlight=false;
resolve({done: false, value });
if(queue!==null)drain();
},(err)=>{
inFlight=false;
settleError(err,reject);
if(queue!==null)drain();
});
return;
}
const{ then }=chunk;
if(typeofthen==='function'){
FunctionPrototypeCall(then,chunk,(value)=>{
inFlight=false;
resolve({done: false, value });
if(queue!==null)drain();
},(err)=>{
inFlight=false;
settleError(err,reject);
if(queue!==null)drain();
});
return;
}

Comment threadlib/internal/streams/readable.js Outdated
Comment on lines +1555 to +1558
if (typeof chunk.then === 'function') {
inFlight = true;
return PromisePrototypeThen(
PromiseResolve(chunk), onChunkFulfilled, onChunkRejected);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here

Suggested change
if(typeofchunk.then==='function'){
inFlight=true;
returnPromisePrototypeThen(
PromiseResolve(chunk),onChunkFulfilled,onChunkRejected);
const{then }=chunk;
if(typeofthen==='function'){
inFlight=true;
returnFunctionPrototypeCall(then,chunk,onChunkFulfilled,onChunkRejected);

settleError(err, reject);
}

return {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This object should ideally have a prototype of AsyncIteratorPrototype.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure it should if the sprecs doesn't require it – it does add a @@asyncDispose method which may or may not be desirable – it also adds a @@asyncIterator, which begs the question whether we should re-implement the method (re-implementing it ourselves means we're not subject to prototype tampering; otherwise, letting the built-in method be inherited would saves a bit of memory maybe?)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current implementation derives from AsyncIteratorPrototype (as a generator) so if we're trying to minimise observability then this is a fairly free move. (While the language currently only provides for the two well-known symbol methods, once we get into async iterator helpers territory, there will be significant advantages to keeping this inheritance.)

@codecov

codecovBot commented Jul 12, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.23256% with 21 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.29%. Comparing base (8a3b11c) to head (873a47e).
⚠️ Report is 472 commits behind head on main.

Files with missing linesPatch %Lines
lib/internal/streams/readable.js90.23%20 Missing and 1 partial ⚠️
Additional details and impacted files
@@ Coverage Diff @@## main #64447 +/- ##
==========================================
+ Coverage 90.24% 90.29% +0.04% 
==========================================
Files 741 760 +19 Lines 241384 247324 +5940 Branches 45480 46652 +1172 ==========================================
+ Hits 217844 223310 +5466 - Misses 15097 15477 +380 - Partials 8443 8537 +94 
Files with missing linesCoverage Δ
lib/internal/streams/readable.js96.55% <90.23%> (-0.72%)⬇️

... and 209 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Comment threadlib/internal/streams/readable.js Outdated
return new Promise((resolve, reject) => {
if (inFlight) {
queue ??= [];
queue.push({ type: 'return', value, resolve, reject });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
queue.push({type: 'return', value, resolve, reject });
queue.push({__proto__: null,type: 'return', value, resolve, reject });

Comment threadlib/internal/streams/readable.js Outdated
return new Promise((resolve, reject) => {
if (inFlight) {
queue ??= [];
queue.push({ type: 'next', value: undefined, resolve, reject });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
queue.push({type: 'next',value: undefined, resolve, reject });
queue.push({__proto__: null,type: 'next',value: undefined, resolve, reject });

Comment threadlib/internal/streams/readable.js Outdated
return new Promise((resolve, reject) => {
if (inFlight) {
queue ??= [];
queue.push({ type: 'throw', value: err, resolve, reject });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
queue.push({type: 'throw',value: err, resolve, reject });
queue.push({__proto__: null,type: 'throw',value: err, resolve, reject });

Comment threadlib/internal/streams/readable.js Outdated

function drain() {
while (!inFlight && queue.length > 0) {
const req = queue.shift();

@mertcanaltinmertcanaltinJul 12, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we replace queue.shift(); with an index-based queue for high throughput?

Comment threadlib/internal/streams/readable.js Outdated
Comment threadlib/internal/streams/readable.js Outdated
Comment threadtest/parallel/test-stream-flatMap.js Outdated
Comment on lines +84 to +89
await new Promise((resolve, reject) => {
if (signal.aborted) {
reject(signal.reason);
return;
}
signal.addEventListener('abort', () => reject(signal.reason), { once: true });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
awaitnewPromise((resolve,reject)=>{
if(signal.aborted){
reject(signal.reason);
return;
}
signal.addEventListener('abort',()=>reject(signal.reason),{once: true});
const{ promise, reject }=Promise.withResolvers();
if(signal.aborted){
reject(signal.reason);
}
signal.addEventListener('abort',()=>reject(signal.reason),{once: true});
// Promise is expected to reject.
awaitpromise;

Signed-off-by: Matteo Collina <hello@matteocollina.com>

@gurgundaygurgunday left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@mcollinamcollina added the request-ci Add this label to start a Jenkins CI on a PR. label Jul 13, 2026
@github-actionsgithub-actionsBot removed the request-ci Add this label to start a Jenkins CI on a PR. label Jul 13, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Comment threadlib/internal/streams/readable.js Outdated
Signed-off-by: Matteo Collina <hello@matteocollina.com>
@mcollina

Copy link
Copy Markdown
MemberAuthor

@MattiasBuelens updated

@gurgundaygurgunday left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

Signed-off-by: Matteo Collina <hello@matteocollina.com>
@ronagronag added request-ci Add this label to start a Jenkins CI on a PR. author ready PRs with CI started, the required approvals, and no outstanding review comments. labels Aug 6, 2026
@github-actionsgithub-actionsBot removed the request-ci Add this label to start a Jenkins CI on a PR. label Aug 6, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@mcollinamcollina added the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 14, 2026
@nodejs-github-botnodejs-github-bot added commit-queue-failed PRs whose Commit Queue landing failed and need manual intervention before retrying. and removed commit-queue PRs queued for automated landing through the Commit Queue. labels Aug 14, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator
Commit Queue failed
- Loading data for nodejs/node/pull/64447
✔ Done loading data for nodejs/node/pull/64447
----------------------------------- PR info ------------------------------------
Title stream: speed up async iteration of Readable (#64447)
Author Matteo Collina <matteo.collina@gmail.com> (@mcollina)
Branch mcollina:stream-async-iterator-perf -> nodejs:main
Labels stream, author ready, needs-ci, commit-queue
Commits 4
- stream: speed up async iteration of Readable
- fixup: address review comments
- fixup: remove [SymbolAsyncIterator]
- stream: fix lint in readable async iterator
Committers 1
- Matteo Collina <hello@matteocollina.com>
PR-URL: https://github.com/nodejs/node/pull/64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
------------------------------ Generated metadata ------------------------------
PR-URL: https://github.com/nodejs/node/pull/64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
--------------------------------------------------------------------------------
ℹ This PR was created on Sun, 12 Jul 2026 08:27:10 GMT
✔ Approvals: 3
✔ - Gürgün Dayıoğlu (@gurgunday): https://github.com/nodejs/node/pull/64447#pullrequestreview-4707049635
✔ - Mattias Buelens (@MattiasBuelens): https://github.com/nodejs/node/pull/64447#pullrequestreview-4706259826
✔ - Robert Nagy (@ronag) (TSC): https://github.com/nodejs/node/pull/64447#pullrequestreview-4838491319
✔ Last GitHub CI successful
ℹ Last Full PR CI on 2026-08-06T13:07:45Z: https://ci.nodejs.org/job/node-test-pull-request/75563/
- Querying data for job/node-test-pull-request/75563/
✔ Build data downloaded
✔ Last Jenkins CI successful
--------------------------------------------------------------------------------
✔ No git cherry-pick in progress
✔ No git am in progress
✔ No git rebase in progress
--------------------------------------------------------------------------------
- Bringing origin/main up to date...
From https://github.com/nodejs/node
* branch main -> FETCH_HEAD
✔ origin/main is now up-to-date
- Downloading patch for 64447
From https://github.com/nodejs/node
* branch refs/pull/64447/merge -> FETCH_HEAD
✔ Fetched commits as 9e23066b8af4..873a47ef6ae8
--------------------------------------------------------------------------------
Auto-merging lib/internal/streams/readable.js
[main 0a0be7f763] stream: speed up async iteration of Readable
Author: Matteo Collina <hello@matteocollina.com>
Date: Sat Jul 11 23:41:55 2026 +0200
3 files changed, 307 insertions(+), 35 deletions(-)
Auto-merging lib/internal/streams/readable.js
[main 22401b1cb5] fixup: address review comments
Author: Matteo Collina <hello@matteocollina.com>
Date: Mon Jul 13 10:00:44 2026 +0200
3 files changed, 73 insertions(+), 26 deletions(-)
Auto-merging lib/internal/streams/readable.js
[main 0b186829dd] fixup: remove [SymbolAsyncIterator]
Author: Matteo Collina <hello@matteocollina.com>
Date: Wed Jul 15 17:34:22 2026 +0200
1 file changed, 1 insertion(+), 4 deletions(-)
Auto-merging lib/internal/streams/readable.js
[main 656bc697b3] stream: fix lint in readable async iterator
Author: Matteo Collina <hello@matteocollina.com>
Date: Sun Aug 2 09:08:31 2026 +0000
1 file changed, 1 insertion(+), 1 deletion(-)
✔ Patches applied
There are 4 commits in the PR. Attempting autorebase.
(node:388) [DEP0190] DeprecationWarning: Passing args to a child process with shell option true can lead to security vulnerabilities, as the arguments are not escaped, only concatenated.
(Use `node --trace-deprecation ...` to show where the warning was created)
Rebasing (2/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
stream: speed up async iteration of Readable

Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.

Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.

The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.

streams/readable-async-iterator.js sync='yes': +32.59% ()
streams/readable-async-iterator.js sync='no': +9.84% (
)

Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD 6e6bcb4f2f] stream: speed up async iteration of Readable
Author: Matteo Collina <hello@matteocollina.com>
Date: Sat Jul 11 23:41:55 2026 +0200
3 files changed, 307 insertions(+), 35 deletions(-)
Rebasing (3/8)
Rebasing (4/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
fixup: address review comments

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD a9e0e0ad92] fixup: address review comments
Author: Matteo Collina <hello@matteocollina.com>
Date: Mon Jul 13 10:00:44 2026 +0200
3 files changed, 73 insertions(+), 26 deletions(-)
Rebasing (5/8)
Rebasing (6/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
fixup: remove [SymbolAsyncIterator]

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD 0ea470ea7b] fixup: remove [SymbolAsyncIterator]
Author: Matteo Collina <hello@matteocollina.com>
Date: Wed Jul 15 17:34:22 2026 +0200
1 file changed, 1 insertion(+), 4 deletions(-)
Rebasing (7/8)
Rebasing (8/8)
Executing: git node land --amend --yes
--------------------------------- New Message ----------------------------------
stream: fix lint in readable async iterator

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>

[detached HEAD 0d2b7c1daf] stream: fix lint in readable async iterator
Author: Matteo Collina <hello@matteocollina.com>
Date: Sun Aug 2 09:08:31 2026 +0000
1 file changed, 1 insertion(+), 1 deletion(-)
Successfully rebased and updated refs/heads/main.

ℹ Add commit-queue-squash label to land the PR as one commit, or commit-queue-rebase to land as separate commits.

https://github.com/nodejs/node/actions/runs/31846615170

@mcollinamcollina added commit-queue PRs queued for automated landing through the Commit Queue. commit-queue-squash PRs the Commit Queue should land as one squashed commit. and removed commit-queue-failed PRs whose Commit Queue landing failed and need manual intervention before retrying. labels Aug 14, 2026
@nodejs-github-bot
nodejs-github-bot merged commit 4551732 into nodejs:mainAug 14, 2026
86 checks passed
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Landed in 4551732

@nodejs-github-botnodejs-github-bot removed the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 14, 2026
aduh95 pushed a commit that referenced this pull request Aug 25, 2026
Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.
Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.
The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.
streams/readable-async-iterator.js sync='yes': +32.59% (***)
streams/readable-async-iterator.js sync='no': +9.84% (***)
Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
aduh95 pushed a commit that referenced this pull request Aug 25, 2026
Replace the async generator backing Symbol.asyncIterator with a
hand-rolled iterator. The generator machinery costs several extra
promise allocations and microtask hops per chunk: yield awaits the
yielded value and resolves the pending request through separate
promises. Buffered chunks are now delivered as an already-resolved
promise, one microtask sooner than before.
Thenable chunks are still awaited before delivery, requests received
while a next() is outstanding are queued, and return()/throw() before
the first next() complete the iterator without touching the stream.
The earlier delivery is observable by code racing an abort against
the first chunk. The flatMap AbortSignal test relied on such a race;
it is reworked to abort deterministically while two mappers are in
flight, asserting the concurrency limit, in-flight cancellation and
rejection, without depending on delivery timing or timers.
streams/readable-async-iterator.js sync='yes': +32.59% (***)
streams/readable-async-iterator.js sync='no': +9.84% (***)
Assisted-by: Claude Fable 5
Signed-off-by: Matteo Collina <matteo.collina@gmail.com>
PR-URL: #64447
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

author readyPRs with CI started, the required approvals, and no outstanding review comments.commit-queue-squashPRs the Commit Queue should land as one squashed commit.needs-ciPRs that need a full CI run.streamIssues and PRs related to Node.js streams.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants

@mcollina@nodejs-github-bot@jasnell@MattiasBuelens@ronag@Renegade334@aduh95@mertcanaltin@gurgunday