Commit bef7ce46223 for nodejs

commit bef7ce4622317631553a3331f3bdcf5b500e6791
Author: James M Snell <jasnell@gmail.com>
Date:   Wed Oct 7 13:01:27 2026 +0000

    stream: read a single stream/iter merge() source without a generator

    merge() of a single source read it with an async generator, a layer
    for every batch, on top of the abortable wrapper when a signal was
    given.

    Without a signal, read the source with MergeSourceIterator: calls to
    next() go to the source's iterator, which from() makes queue them as an
    async generator does, and return() and throw() wait for the last next()
    before closing the source, as the generator queued them. With a signal,
    return the iterator of the abortable wrapper, which already rejects a
    pending read when the signal aborts, closes the source and then ends.
    As the generator did, an abort before the first read now ends the
    iteration without opening the source.

    Iterating merge() of a single source of 16-byte chunks one per batch is
    about 1.7-2.2 times faster without a signal, and 1.5-1.7 times faster
    with one.

    Assisted-by: OpenCode
    Signed-off-by: James M Snell <jasnell@gmail.com>
    PR-URL: https://github.com/nodejs/node/pull/66504
    Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
    Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>

diff --git a/lib/internal/streams/iter/consumers.js b/lib/internal/streams/iter/consumers.js
index a278490ca40..6f967dddd1d 100644
--- a/lib/internal/streams/iter/consumers.js
+++ b/lib/internal/streams/iter/consumers.js
@@ -17,8 +17,11 @@ const {
   ArrayPrototypeSlice,
   FunctionPrototypeCall,
   ObjectFreeze,
+  ObjectSetPrototypeOf,
   Promise,
   PromisePrototypeThen,
+  PromiseReject,
+  PromiseResolve,
   SafePromiseAllReturnVoid,
   SafeSet,
   SuppressedError,
@@ -55,6 +58,7 @@ const {
 } = require('internal/streams/iter/from');

 const {
+  IterResult,
   kNullOnceOption,
   concatBytes,
   getProtocolMethod,
@@ -499,6 +503,84 @@ MergeEntry.prototype = ObjectFreeze({ __proto__: null });
  * @param {...(AsyncIterable<Uint8Array[]>|object)} args
  * @returns {AsyncIterable<Uint8Array[]>}
  */
+/**
+ * The iterator of merge() of a single source without a signal: what an
+ * async generator doing `for await (const batch of source) yield batch;`
+ * gives, without its layer for every batch. Calls to next() are passed to
+ * the source's iterator, from from(), which queues them as an async
+ * generator does. return() and throw() wait for the last next() before
+ * closing the source, as the generator would queue them, and later calls
+ * wait for them in turn. The source is opened by the first next().
+ */
+class MergeSourceIterator {
+  #source;
+  #iterator = null;
+  // The last next() of the source's iterator, and the promise of return()
+  // or throw() once one is called.
+  #last = null;
+  #closing = null;
+
+  constructor(source) {
+    this.#source = source;
+  }
+
+  next() {
+    if (this.#closing !== null) {
+      return PromisePrototypeThen(this.#closing, doneResult, doneResult);
+    }
+    try {
+      this.#iterator ??= this.#source[SymbolAsyncIterator]();
+      const next = PromiseResolve(this.#iterator.next());
+      this.#last = next;
+      return next;
+    } catch (error) {
+      this.#closing = PromiseReject(error);
+      markPromiseAsHandled(this.#closing);
+      return this.#closing;
+    }
+  }
+
+  return(value) {
+    return this.#close(() => new IterResult(true, value), false);
+  }
+
+  throw(error) {
+    return this.#close(() => { throw error; }, true);
+  }
+
+  // Close the source once the last next() has settled, if it was opened,
+  // then settle with `settle()`. Errors closing it are ignored if `quiet`,
+  // as for await ignores them when its body throws.
+  #close(settle, quiet) {
+    if (this.#closing !== null) {
+      return PromisePrototypeThen(this.#closing, settle, settle);
+    }
+    const iterator = this.#iterator;
+    if (iterator === null) {
+      this.#closing = PromiseResolve();
+      return PromisePrototypeThen(this.#closing, settle);
+    }
+    const close = () => {
+      const closed = PromiseResolve(iterator.return?.());
+      return quiet ? PromisePrototypeThen(closed, undefined, () => {}) : closed;
+    };
+    const closing = PromisePrototypeThen(this.#last ?? PromiseResolve(),
+                                         close, close);
+    this.#closing = closing;
+    markPromiseAsHandled(closing);
+    return PromisePrototypeThen(closing, settle);
+  }
+
+  [SymbolAsyncIterator]() {
+    return this;
+  }
+}
+ObjectSetPrototypeOf(MergeSourceIterator.prototype, null);
+
+function doneResult() {
+  return new IterResult(true, undefined);
+}
+
 function merge(...args) {
   let sources;
   let options;
@@ -518,6 +600,28 @@ function merge(...args) {
   // Normalize each source via from()
   const normalized = ArrayPrototypeMap(sources, (source) => from(source));

+  if (normalized.length === 1) {
+    // A single source is read without an async generator layer for every
+    // batch (see MergeSourceIterator). With a signal, the source is read through
+    // yieldAbortable(), which rejects a pending read when the signal aborts
+    // (also before the first read), closes the source, and then ends. An
+    // async iterable is made abortable before from(), so that an abort
+    // closes it even while from() is reading it.
+    const { signal } = options;
+    return {
+      __proto__: null,
+      [SymbolAsyncIterator]() {
+        if (signal === undefined) {
+          return new MergeSourceIterator(normalized[0]);
+        }
+        const source = isAsyncIterable(sources[0]) ?
+          from(yieldAbortable(sources[0], signal)) :
+          yieldAbortable(normalized[0], signal);
+        return source[SymbolAsyncIterator]();
+      },
+    };
+  }
+
   return {
     __proto__: null,
     async *[SymbolAsyncIterator]() {
@@ -527,16 +631,6 @@ function merge(...args) {

       if (normalized.length === 0) return;

-      if (normalized.length === 1) {
-        const source = signal !== undefined && isAsyncIterable(sources[0]) ?
-          from(yieldAbortable(sources[0], signal)) :
-          yieldAbortable(normalized[0], signal);
-        for await (const batch of source) {
-          yield batch;
-        }
-        return;
-      }
-
       // Multiple sources - use a ready queue so that batches that settle
       // between consumer pulls are drained synchronously without an extra
       // async tick per batch. Each source has at most one pending .next()
diff --git a/lib/internal/streams/iter/utils.js b/lib/internal/streams/iter/utils.js
index 7dd6a3fe172..7eb0da7dbfc 100644
--- a/lib/internal/streams/iter/utils.js
+++ b/lib/internal/streams/iter/utils.js
@@ -279,8 +279,8 @@ function yieldAbortable(source, signal) {
  * weakly so that the signal does not keep the iterator alive, and each
  * next() waits with a single promise that an abort rejects. As with the
  * generator:
- * - the source is opened by the first next(), and calls made while one is in
- *   progress are queued;
+ * - the source is opened by the first next(), unless the signal has aborted
+ *   by then, and calls made while one is in progress are queued;
  * - an abort before or while reading a value, or once it has been read,
  *   rejects with the abort reason;
  * - unless the source has ended, an error (including an abort) closes it:
@@ -390,6 +390,13 @@ function createAbortableIterator(source, signal) {
       return PromiseResolve(new IterResult(true, undefined));
     }
     if (state === kStart) {
+      // An abort before the first read ends the iteration without opening
+      // the source.
+      if (signal.aborted) {
+        state = kDone;
+        operations.settled();
+        return PromiseReject(signal.reason);
+      }
       try {
         iterator = source[SymbolAsyncIterator]();
       } catch (error) {
diff --git a/test/parallel/test-stream-iter-consumers-merge.js b/test/parallel/test-stream-iter-consumers-merge.js
index 5cbe773ac08..9e69d5f7fcb 100644
--- a/test/parallel/test-stream-iter-consumers-merge.js
+++ b/test/parallel/test-stream-iter-consumers-merge.js
@@ -461,7 +461,79 @@ async function testMergeMultiSourceBreakWithCleanupError() {
   );
 }

+// merge() of a single source behaves as an async generator reading it:
+// an abort rejects the pending read, closes the source and ends the
+// iteration; an abort before the first read does not open the source;
+// return() is queued behind pending reads.
+async function testMergeSingleSourceProtocol() {
+  const log = [];
+  function source(name, values, { hang = false } = {}) {
+    let i = 0;
+    return {
+      [Symbol.asyncIterator]() {
+        log.push(`${name} iterator`);
+        return {
+          next() {
+            log.push(`${name} next ${i}`);
+            if (hang && i === values.length) return new Promise(() => {});
+            return Promise.resolve(i < values.length ?
+              { done: false, value: values[i++] } : { done: true });
+          },
+          return() {
+            log.push(`${name} return`);
+            return Promise.resolve({ done: true });
+          },
+        };
+      },
+    };
+  }
+
+  async function settle(label, promise) {
+    try {
+      const result = await promise;
+      log.push(`${label}: ${result.done ? 'done' : result.value[0][0]}`);
+    } catch (error) {
+      log.push(`${label}: ${error.name}`);
+    }
+  }
+  const chunk = (n) => [Uint8Array.of(n)];
+
+  const aborted = AbortSignal.abort();
+  let it = merge(source('a', [chunk(1)]), { signal: aborted })[
+    Symbol.asyncIterator]();
+  await settle('a 1', it.next());
+  await settle('a 2', it.next());
+
+  const ac = new AbortController();
+  it = merge(source('b', [chunk(1)], { hang: true }), { signal: ac.signal })[
+    Symbol.asyncIterator]();
+  await settle('b 1', it.next());
+  const pending = it.next();
+  await setImmediate();
+  ac.abort();
+  await settle('b 2', pending);
+  await settle('b 3', it.next());
+
+  it = merge(source('c', [chunk(1), 'x', chunk(3)]))[Symbol.asyncIterator]();
+  const results = [it.next(), it.next(), it.return(), it.next()];
+  for (let i = 0; i < results.length; i++) await settle(`c ${i}`, results[i]);
+
+  it = merge(source('d', [chunk(1)]))[Symbol.asyncIterator]();
+  await settle('d return', it.return());
+  await assert.rejects(it.throw(new Error('thrown')), { message: 'thrown' });
+
+  assert.deepStrictEqual(log, [
+    'a 1: AbortError', 'a 2: done',
+    'b iterator', 'b next 0', 'b 1: 1', 'b next 1', 'b return',
+    'b 2: AbortError', 'b 3: done',
+    'c iterator', 'c next 0', 'c next 1', 'c 0: 1', 'c 1: 120', 'c return',
+    'c 2: done', 'c 3: done',
+    'd return: done',
+  ]);
+}
+
 Promise.all([
+  testMergeSingleSourceProtocol(),
   testMergeTwoSources(),
   testMergeSingleSource(),
   testMergeEmpty(),