Skip to content

stream: stream/iter cleanups - #67875

Open
jasnell wants to merge 26 commits into
nodejs:mainfrom
jasnell:jasnell/stream-iter-spec-fixes
Open

jasnell wants to merge 26 commits into
nodejs:mainfrom
jasnell:jasnell/stream-iter-spec-fixes

Conversation

@jasnell

@jasnell jasnell commented Nov 29, 2026 •

Copy link
Copy Markdown
Member

Number of updates to improve stream/iter spec alignment and correctness.

Last round of updates before graduating from experimental.

Spec PR: WinterTC55/iter-streams#62

Stateless transforms in fused runs were called as run[i](...), so
`this` inside a transform was the internal array of the run. A
transform could read or mutate it, for example `this.push(fn)` added a
transform to the pipeline while it was running. Call them as plain
functions, so `this` is undefined, as the Iterable Streams
specification requires. Stateful transforms are still called with the
transform object as `this`.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
The budget option of push(), duplex(), broadcast(), share() and
shareSync() is an [EnforceRange] unsigned long long, but it was
converted without EnforceRange and then validated separately, so
negative, non-finite and out of range values threw a RangeError.
Convert it with EnforceRange so these throw a TypeError. A budget of
0 is still rejected with a RangeError afterwards.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
The write(), writev() and end() methods of the Writers in
stream/iter return promises, but threw synchronously when their
arguments could not be converted, for example write(Symbol()) or
end({ signal: 1 }). Web IDL operations that return a promise report
conversion errors by returning a rejected promise. Do that for the
push, broadcast, fromWritable(), FileHandle and generic Writers. The
synchronous methods still throw.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
When the destination's endSync() returns a negative number,
pipeToSync() throws because the writer could not be closed
synchronously. The Iterable Streams specification requires a
TypeError, but a plain Error was thrown. Use the TypeError variant of
ERR_INVALID_STATE, so the error code is unchanged.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
Aborting the signal passed to broadcast() only cancelled the
broadcast, which closes its writer. An abort therefore looked like a
normal finish to the producer: end() resolved with the byte count and
later writes rejected with a TypeError. Fail the writer with the abort
reason first, as push() does, and then cancel the broadcast, as the
Iterable Streams specification requires.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
After Broadcast.cancel(), push() still registered a consumer, so
consumerCount became 1, and that consumer read the data left in the
buffer before reporting the cancellation. cancel() also kept the
buffered data. Discard the buffer on cancel(), and have push() on a
cancelled broadcast return an unregistered consumer that does not
call its transforms and whose pulls reject with the cancel reason, or
report done if there was none.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
The Iterable Streams specification defines Stream.broadcastFrom(),
which creates a broadcast channel fed from an existing source and
returns its Broadcast. Node.js only had Broadcast.from(), which returns
both the writer and the broadcast. Add broadcastFrom() as a named
export and on the Stream namespace, sharing the pump used by
Broadcast.from(). As in Broadcast.from(), an input implementing
Symbol.for('Stream.broadcastProtocol') creates the broadcast itself.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
share() and shareSync() ignored Symbol.for('Stream.shareProtocol') and
Symbol.for('Stream.shareSyncProtocol'); only Share.from() and
SyncShare.fromSync() checked them. Check the protocol first in
share() and shareSync() as well, as the Iterable Streams specification
requires, before normalizing the source or converting the options, and
pass the options to the protocol method as given.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
An object whose toStreamable or toAsyncStreamable method returned the
object itself made from() and fromSync() recurse until the stack was
exhausted, and the async path also printed "Exception in
PromiseRejectCallback". Limit chained protocol conversions to 100 and
throw a RangeError with code ERR_INVALID_ARG_VALUE beyond that.
Nesting through arrays and iterables does not count toward the limit.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
ondrain() returned null for any value that was not an object, so a
function implementing Symbol.for('Stream.drainableProtocol') was never
treated as drainable, although the other protocol lookups accept
functions. Let the protocol lookup decide.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
Bytes received by from(), fromSync(), transform output normalization
and writers are now copied when they are backed by a SharedArrayBuffer
or a resizable ArrayBuffer, so that what was received cannot change or
be resized afterwards. Fixed-length buffers are still used without a
copy. Receiving bytes from a detached ArrayBuffer throws a TypeError.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
Writer chunks may now be any ArrayBuffer, SharedArrayBuffer or
ArrayBufferView, which are written as their bytes, matching the
Iterable Streams WriterChunk type. Previously, anything other than a
Uint8Array was converted to a string.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
Writers created by push(), broadcast() and duplex() now have a signal
that aborts when the writer stops accepting data for a reason other
than end(): the consumer stopped reading, fail() was called, or the
broadcast was cancelled. The AbortController is created on first
access; if the writer had already stopped, the signal is created
aborted with the same reason.

Broadcast.cancel() now rejects pending writes with its reason, or with
the same TypeError the signal aborts with, after settling the
consumers, and pending writes are no longer promoted after cancel.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
When writeSync(), writevSync() or endSync() fails because the writer
has stopped, pipeToSync() now throws the abort reason of the writer's
signal instead of a RangeError saying the budget is exhausted, or a
TypeError saying the writer could not be closed. A write refused by a
closed or closing writer throws a TypeError. The signal and canWrite
are read only on those failure paths.

pipeTo() and pipeToSync() now fail the writer only while it is open, or
while awaiting the pipe's own end(), so piping into a writer that
another producer is closing no longer interrupts its drain.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
channel.abort(reason) fails this end's writer and cancels this end's
readable with the reason, so the other end's pending and later writes
reject with it, without waiting for the other end. A pending close()
rejects with the reason, and close() after abort() resolves, so
disposing an aborted channel does not throw.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
broadcast.cancel(undefined), share.cancel(undefined) and the shareSync()
equivalent now behave like cancel() with no argument: consumers
complete instead of rejecting with undefined. This matches the
Iterable Streams spec, which treats an undefined reason as not given.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
Transform output in pull(), pipeTo(), pullSync(), pipeToSync() and the
push, broadcast and share pipelines is now normalized with the same
algorithm as from() and fromSync(). Output may use the toStreamable and
(in async pipelines) toAsyncStreamable protocols, and async pipelines
await nested promises and read nested async iterables. Sync pipelines
reject async values as fromSync() does. The conversion depth bound and
the copy of shared and resizable memory apply to transform output too.

The common cases (a batch, a Uint8Array, a string or a buffer) keep
their synchronous fast paths.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
writer.fail() with no reason, including through Symbol.dispose and
Symbol.asyncDispose, now fails the writer with an AbortError instead of
undefined. This applies to push(), broadcast() and duplex() writers,
the fromWritable() writer, filehandle.writer() and the QUIC stream
writer. Later writes, end(), consumers, writer.signal and pipeToSync()
all report that same error. Reasons other than undefined are kept as
given.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
If a push stream's consumer stops after reading the last batch while
the writer is closing, end() now resolves with the byte count instead
of rejecting: all of the data was delivered. This also applies when the
other end of a duplex channel is closed or aborted after reading
everything. If undelivered data remains, end() still rejects.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
After a broadcast writer is failed without the broadcast being
cancelled, each consumer, including one added later, now reads the data
still buffered for it before rejecting with the failure reason.
Previously, consumers that already existed were detached at once and
lost that data.

A later cancel() with no reason no longer turns that failure, or a
share's source error, into a clean end: consumers, including ones added
afterwards, still reject with the stored error.

After Broadcast.cancel(), the writer rejects later writes and end()
with the cancel reason or TypeError, and a closing writer whose data
was discarded rejects end() instead of resolving it. end() and
endSync() settle pending reads before drain waiters, and a shareSync()
consumer reads its buffered data before a source error.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
Calling return() on a merge() iterator while a next() is pending now
resolves the pending call as done right away, and does not wait for the
sources' return(). Previously it could hang until a source suspended at
an await settled.

Concurrent next() calls on a merge() iterator are settled in order, and
after an abort the pending and later calls reject with the reason.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
A promise returned by a toStreamable method, even one that is also
iterable, is now rejected with ERR_INVALID_ARG_TYPE wherever a value is
normalized: in from() and fromSync() at the top level, nested values,
and transform output. Previously a nested one was awaited. Use
toAsyncStreamable for asynchronous conversion.

Also correct the fromSync() documentation, which said that
toAsyncStreamable is ignored.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
Calling return() on a pull() pipeline's iterator or a from() iterator
while next() is pending now resolves the pending calls with done at
once, instead of rejecting them with an AbortError, and closes the
upstream iterators without waiting for them. Results that arrive later
are discarded. A return() with no next() pending still waits for the
upstream return().

push() readables and broadcast and share consumers with transforms use
the same steps, so return() never sends the flush signal to their
transforms, and neither does cancel() with no reason. A share
consumer's return() resolves a pending next() at once and detaches it,
and an upstream pull still in flight is buffered for later consumers.
This also fixes a share consumer without transforms whose next() could
hang after return().

throw() on push, broadcast and share consumers closes the consumer and
rejects with its argument. Broadcast and Share cancel(reason) tear down
a consumer's transforms as an abort does. Pipelines close their
stateful transforms outermost first, and shareSync().pull() validates
its transforms before registering a consumer.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
merge(), broadcastFrom(), Broadcast.from(), share() and shareSync() now
convert their options and check for an already aborted signal before
converting any input. merge() returns an iterator that rejects with
the abort reason, and broadcastFrom() and share() return an already
cancelled object, without normalizing the input.

An already aborted pull(), merge(), broadcast or share consumer keeps
rejecting until return() or throw() is called, which then reports done.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
throw() on the iterators of push(), pull(), Broadcast.push(),
Share.pull(), merge() and from() handled a pending next() in two
different ways: push readables and pipelines rejected it with the
thrown value, and broadcast and share consumers resolved it with the
end. Per the Iterable Streams specification, throw() is now served in
order: it waits until the next() calls made before it have settled,
which settle as they would have, then stops the iterator as return()
would and rejects with its argument. Calls made while it waits report
the end, and a return() made meanwhile still stops the iterator at
once.

As throw() is handled as return(), the writer of a push() stream whose
consumer throws is cancelled without an error, as for return(): its
writes reject with ERR_INVALID_STATE, its signal aborts with that
error, and ondrain() resolves with false.

After return() or throw(), later reads of a broadcast or share consumer
report the end, even once the source has failed.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
The drainable protocol method of a QUIC stream writer returned null
when the writer had capacity, and end() waited for pending drain
waiters instead of settling them. Per the Iterable Streams drainable
protocol, it now returns null only once canWrite is null, a promise
resolved with true while there is capacity, and otherwise a promise
that resolves with true once there is, with false if the writer is
ended first, and rejects if it fails or the peer stops sending.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
@jasnell jasnell added stream Issues and PRs related to Node.js streams. experimental Issues and PRs related to experimental features. labels Nov 29, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Review requested:

  • @nodejs/quic
  • @nodejs/streams

@nodejs-github-bot nodejs-github-bot added the fs Issues and PRs related to file-system APIs and the fs module. label Nov 29, 2026
@nodejs-github-bot nodejs-github-bot added the needs-ci PRs that need a full CI run. label Nov 29, 2026
@jasnell jasnell changed the title stream: call stateless iter transforms without this stream: stream/iter cleanups Nov 29, 2026
@jasnell
jasnell requested review from mcollina and trivikr November 29, 2026 22:08
@jasnell

jasnell commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Best to review commit-by-commit. Would have spread this out over multiple prs but it takes 10x longer to review and land that way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

experimental Issues and PRs related to experimental features. fs Issues and PRs related to file-system APIs and the fs module. needs-ci PRs that need a full CI run. stream Issues and PRs related to Node.js streams.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants